diff --git a/configurations/price/default.nix b/configurations/price/default.nix new file mode 100644 index 00000000..d22e6541 --- /dev/null +++ b/configurations/price/default.nix @@ -0,0 +1,188 @@ +{ config, pkgs, ... }: + + +let + dots = config.home.homeDirectory + "/.config/home-manager/configurations/price/dots"; + xdg_config = "${dots}/xdg/config"; + xdg_local = "${dots}/xdg/config"; + dotf = configPath: + let + dot_file = "${configPath}"; + in + { + source = config.lib.file.mkOutOfStoreSymlink dot_file; + recursive = builtins.pathExists ("${dot_file}" + "/."); + }; +in +{ + + nixpkgs.config.allowUnfree = true; + # Home Manager needs a bit of information about you and the paths it should + # manage. + home.username = "sam"; + home.homeDirectory = "/home/sam"; + + # This value determines the Home Manager release that your configuration is + # compatible with. This helps avoid breakage when a new Home Manager release + # introduces backwards incompatible changes. + # + # You should not change this value, even if you update Home Manager. If you do + # want to update the value, then make sure to first check the Home Manager + # release notes. + home.stateVersion = "23.05"; # Please read the comment before changing. + + home.packages = with pkgs; [ + hyprland + waybar + neovim-nightly + nixd + wezterm + git + udiskie + openssh + eza + mullvad-vpn + firefox-devedition + swww + twitter-color-emoji + swaylock-effects + zathura + mako + jq + inotify-tools + wf-recorder + ffmpeg + ungoogled-chromium + man + man-pages + man-pages-posix + pavucontrol + playerctl + slurp + grim + feh + wireshark + thunderbird + wl-clipboard + gh + libfido2 + python3 + lua + silicon + mpv + yarn + bat + ripgrep + delta + sqlite + glibc + gifski + tlp + thermald + lxappearance + ccache + qt6ct + qt5ct + gtk-engine-murrine + fuse + imagemagick + tectonic + virt-manager + python-qt + ansible + ansible-lint + xwaylandvideobridge + spotify + feh + + # Fonts + liberation_ttf + fira-code-nerdfont + noto-fonts + noto-fonts-cjk-sans + noto-fonts-cjk-serif + noto-fonts-color-emoji + meslo-lgs-nf + roboto + # # Adds the 'hello' command to your environment. It prints a friendly + # # "Hello, world!" when run. + # pkgs.hello + + # # It is sometimes useful to fine-tune packages, for example, by applying + # # overrides. You can do that directly here, just don't forget the + # # parentheses. Maybe you want to install Nerd Fonts with a limited number of + # # fonts? + # (pkgs.nerdfonts.override { fonts = [ "FantasqueSansMono" ]; }) + + # # You can also create simple shell scripts directly inside your + # # configuration. For example, this adds a command 'my-hello' to your + # # environment: + # (pkgs.writeShellScriptBin "my-hello" '' + # echo "Hello, ${config.home.username}!" + # '') + ]; + + services = { + opensnitch-ui.enable = true; + }; + + xdg.configFile = { + "nvim" = dotf "${xdg_config}/nvim"; + "chrome-flags.conf" = dotf "${xdg_config}/chrome-flags.conf"; + "chromium-flags.conf" = dotf "${xdg_config}/chromium-flags.conf"; + "mimeapps.list" = dotf "${xdg_config}/mimeapps.list"; + "stylua.toml" = dotf "${xdg_config}/stylua.toml"; + "Trolltech.conf" = dotf "${xdg_config}/Trolltech.conf"; + "zathura" = dotf "${xdg_config}/zathura"; + "bat" = dotf "${xdg_config}/bat"; + "zsh" = dotf "${xdg_config}/zsh"; + "hypr" = dotf "${xdg_config}/hypr"; + "mako" = dotf "${xdg_config}/mako"; + "mpv" = dotf "${xdg_config}/mpv"; + "waybar" = dotf "${xdg_config}/waybar"; + "silicon" = dotf "${xdg_config}/silicon"; + "powershell" = dotf "${xdg_config}/powershell"; + "wezterm" = dotf "${xdg_config}/wezterm"; + "wofi" = dotf "${xdg_config}/wofi"; + "kitty" = dotf "${xdg_config}/kitty"; + "git" = dotf "${xdg_config}/git"; + "gtk-3.0" = dotf "${xdg_config}/gtk-3.0"; + "gtk-4.0" = dotf "${xdg_config}/gtk-4.0"; + "fontconfig" = dotf "${xdg_config}/fontconfig"; + "emacs" = dotf "${xdg_config}/emacs"; + }; + + home.file = { + ".omnisharp" = dotf "${dots}/.omnisharp"; + ".latexmkrc" = dotf "${dots}/.latexmkrc"; + ".zshrc" = dotf "${dots}/.zshrc"; + # # Building this configuration will create a copy of 'dotfiles/screenrc' in + # # the Nix store. Activating the configuration will then make '~/.screenrc' a + # # symlink to the Nix store copy. + # ".screenrc" = dotfiles/screenrc; + + # # You can also set the file content immediately. + # ".gradle/gradle.properties".text = '' + # org.gradle.console=verbose + # org.gradle.daemon.idletimeout=3600000 + # ''; + }; + + # You can also manage environment variables but you will have to manually + # source + # + # ~/.nix-profile/etc/profile.d/hm-session-vars.sh + # + # or + # + # /etc/profiles/per-user/sam/etc/profile.d/hm-session-vars.sh + # + # if you don't want to manage your shell through Home Manager. + home.sessionVariables = { + EDITOR = "nvim"; + LIBSQLITE = "${pkgs.sqlite.out}/lib/libsqlite3.so"; + }; + + # Let Home Manager install and manage itself. + programs.home-manager.enable = true; +} diff --git a/dots/.latexmkrc b/configurations/price/dots/.latexmkrc similarity index 100% rename from dots/.latexmkrc rename to configurations/price/dots/.latexmkrc diff --git a/dots/.omnisharp/omnisharp.json b/configurations/price/dots/.omnisharp/omnisharp.json similarity index 100% rename from dots/.omnisharp/omnisharp.json rename to configurations/price/dots/.omnisharp/omnisharp.json diff --git a/dots/.zshrc b/configurations/price/dots/.zshrc similarity index 100% rename from dots/.zshrc rename to configurations/price/dots/.zshrc diff --git a/dots/.config/Trolltech.conf b/configurations/price/dots/xdg/config/Trolltech.conf similarity index 100% rename from dots/.config/Trolltech.conf rename to configurations/price/dots/xdg/config/Trolltech.conf diff --git a/dots/.config/bat/config b/configurations/price/dots/xdg/config/bat/config similarity index 100% rename from dots/.config/bat/config rename to configurations/price/dots/xdg/config/bat/config diff --git a/dots/.config/chrome-flags.conf b/configurations/price/dots/xdg/config/chrome-flags.conf similarity index 100% rename from dots/.config/chrome-flags.conf rename to configurations/price/dots/xdg/config/chrome-flags.conf diff --git a/dots/.config/chromium-flags.conf b/configurations/price/dots/xdg/config/chromium-flags.conf similarity index 100% rename from dots/.config/chromium-flags.conf rename to configurations/price/dots/xdg/config/chromium-flags.conf diff --git a/dots/.config/emacs/.gitignore b/configurations/price/dots/xdg/config/emacs/.gitignore similarity index 100% rename from dots/.config/emacs/.gitignore rename to configurations/price/dots/xdg/config/emacs/.gitignore diff --git a/dots/.config/emacs/early-init.el b/configurations/price/dots/xdg/config/emacs/early-init.el similarity index 100% rename from dots/.config/emacs/early-init.el rename to configurations/price/dots/xdg/config/emacs/early-init.el diff --git a/dots/.config/emacs/init.el b/configurations/price/dots/xdg/config/emacs/init.el similarity index 100% rename from dots/.config/emacs/init.el rename to configurations/price/dots/xdg/config/emacs/init.el diff --git a/dots/.config/fontconfig/fonts.conf b/configurations/price/dots/xdg/config/fontconfig/fonts.conf similarity index 100% rename from dots/.config/fontconfig/fonts.conf rename to configurations/price/dots/xdg/config/fontconfig/fonts.conf diff --git a/dots/.config/git/allowed_signers b/configurations/price/dots/xdg/config/git/allowed_signers similarity index 100% rename from dots/.config/git/allowed_signers rename to configurations/price/dots/xdg/config/git/allowed_signers diff --git a/dots/.config/git/config b/configurations/price/dots/xdg/config/git/config similarity index 100% rename from dots/.config/git/config rename to configurations/price/dots/xdg/config/git/config diff --git a/dots/.config/git/ignore b/configurations/price/dots/xdg/config/git/ignore similarity index 100% rename from dots/.config/git/ignore rename to configurations/price/dots/xdg/config/git/ignore diff --git a/dots/.config/gtk-3.0/settings.ini b/configurations/price/dots/xdg/config/gtk-3.0/settings.ini similarity index 100% rename from dots/.config/gtk-3.0/settings.ini rename to configurations/price/dots/xdg/config/gtk-3.0/settings.ini diff --git a/dots/.config/gtk-4.0/settings.ini b/configurations/price/dots/xdg/config/gtk-4.0/settings.ini similarity index 100% rename from dots/.config/gtk-4.0/settings.ini rename to configurations/price/dots/xdg/config/gtk-4.0/settings.ini diff --git a/dots/.config/hypr/hyprland.conf b/configurations/price/dots/xdg/config/hypr/hyprland.conf similarity index 100% rename from dots/.config/hypr/hyprland.conf rename to configurations/price/dots/xdg/config/hypr/hyprland.conf diff --git a/dots/.config/hypr/scripts/disable-laptop-screen.bash b/configurations/price/dots/xdg/config/hypr/scripts/disable-laptop-screen.bash similarity index 100% rename from dots/.config/hypr/scripts/disable-laptop-screen.bash rename to configurations/price/dots/xdg/config/hypr/scripts/disable-laptop-screen.bash diff --git a/dots/.config/hypr/scripts/focus-workspace-mon.bash b/configurations/price/dots/xdg/config/hypr/scripts/focus-workspace-mon.bash similarity index 100% rename from dots/.config/hypr/scripts/focus-workspace-mon.bash rename to configurations/price/dots/xdg/config/hypr/scripts/focus-workspace-mon.bash diff --git a/dots/.config/hypr/scripts/launchers/events-monitor.bash b/configurations/price/dots/xdg/config/hypr/scripts/launchers/events-monitor.bash similarity index 100% rename from dots/.config/hypr/scripts/launchers/events-monitor.bash rename to configurations/price/dots/xdg/config/hypr/scripts/launchers/events-monitor.bash diff --git a/dots/.config/hypr/scripts/launchers/launch-desktop-portal.bash b/configurations/price/dots/xdg/config/hypr/scripts/launchers/launch-desktop-portal.bash similarity index 100% rename from dots/.config/hypr/scripts/launchers/launch-desktop-portal.bash rename to configurations/price/dots/xdg/config/hypr/scripts/launchers/launch-desktop-portal.bash diff --git a/dots/.config/hypr/scripts/launchers/launch-kbct.bash b/configurations/price/dots/xdg/config/hypr/scripts/launchers/launch-kbct.bash similarity index 100% rename from dots/.config/hypr/scripts/launchers/launch-kbct.bash rename to configurations/price/dots/xdg/config/hypr/scripts/launchers/launch-kbct.bash diff --git a/dots/.config/hypr/scripts/launchers/launch-waybar.bash b/configurations/price/dots/xdg/config/hypr/scripts/launchers/launch-waybar.bash similarity index 100% rename from dots/.config/hypr/scripts/launchers/launch-waybar.bash rename to configurations/price/dots/xdg/config/hypr/scripts/launchers/launch-waybar.bash diff --git a/dots/.config/hypr/scripts/move-workspace-mon.bash b/configurations/price/dots/xdg/config/hypr/scripts/move-workspace-mon.bash similarity index 100% rename from dots/.config/hypr/scripts/move-workspace-mon.bash rename to configurations/price/dots/xdg/config/hypr/scripts/move-workspace-mon.bash diff --git a/dots/.config/hypr/scripts/screen-cap.bash b/configurations/price/dots/xdg/config/hypr/scripts/screen-cap.bash similarity index 100% rename from dots/.config/hypr/scripts/screen-cap.bash rename to configurations/price/dots/xdg/config/hypr/scripts/screen-cap.bash diff --git a/dots/.config/hypr/wm/appearance.conf b/configurations/price/dots/xdg/config/hypr/wm/appearance.conf similarity index 100% rename from dots/.config/hypr/wm/appearance.conf rename to configurations/price/dots/xdg/config/hypr/wm/appearance.conf diff --git a/dots/.config/hypr/wm/bindings.conf b/configurations/price/dots/xdg/config/hypr/wm/bindings.conf similarity index 100% rename from dots/.config/hypr/wm/bindings.conf rename to configurations/price/dots/xdg/config/hypr/wm/bindings.conf diff --git a/dots/.config/hypr/wm/colors.conf b/configurations/price/dots/xdg/config/hypr/wm/colors.conf similarity index 100% rename from dots/.config/hypr/wm/colors.conf rename to configurations/price/dots/xdg/config/hypr/wm/colors.conf diff --git a/dots/.config/hypr/wm/env.conf b/configurations/price/dots/xdg/config/hypr/wm/env.conf similarity index 100% rename from dots/.config/hypr/wm/env.conf rename to configurations/price/dots/xdg/config/hypr/wm/env.conf diff --git a/dots/.config/hypr/wm/general.conf b/configurations/price/dots/xdg/config/hypr/wm/general.conf similarity index 100% rename from dots/.config/hypr/wm/general.conf rename to configurations/price/dots/xdg/config/hypr/wm/general.conf diff --git a/dots/.config/hypr/wm/monitors.conf b/configurations/price/dots/xdg/config/hypr/wm/monitors.conf similarity index 100% rename from dots/.config/hypr/wm/monitors.conf rename to configurations/price/dots/xdg/config/hypr/wm/monitors.conf diff --git a/dots/.config/hypr/wm/window-rules.conf b/configurations/price/dots/xdg/config/hypr/wm/window-rules.conf similarity index 100% rename from dots/.config/hypr/wm/window-rules.conf rename to configurations/price/dots/xdg/config/hypr/wm/window-rules.conf diff --git a/dots/.config/kitty/config/font.conf b/configurations/price/dots/xdg/config/kitty/config/font.conf similarity index 100% rename from dots/.config/kitty/config/font.conf rename to configurations/price/dots/xdg/config/kitty/config/font.conf diff --git a/dots/.config/kitty/config/mappings.conf b/configurations/price/dots/xdg/config/kitty/config/mappings.conf similarity index 100% rename from dots/.config/kitty/config/mappings.conf rename to configurations/price/dots/xdg/config/kitty/config/mappings.conf diff --git a/dots/.config/kitty/config/options.conf b/configurations/price/dots/xdg/config/kitty/config/options.conf similarity index 100% rename from dots/.config/kitty/config/options.conf rename to configurations/price/dots/xdg/config/kitty/config/options.conf diff --git a/dots/.config/kitty/config/os/mac.conf b/configurations/price/dots/xdg/config/kitty/config/os/mac.conf similarity index 100% rename from dots/.config/kitty/config/os/mac.conf rename to configurations/price/dots/xdg/config/kitty/config/os/mac.conf diff --git a/dots/.config/kitty/config/theme.conf b/configurations/price/dots/xdg/config/kitty/config/theme.conf similarity index 100% rename from dots/.config/kitty/config/theme.conf rename to configurations/price/dots/xdg/config/kitty/config/theme.conf diff --git a/dots/.config/kitty/kitty.conf b/configurations/price/dots/xdg/config/kitty/kitty.conf similarity index 100% rename from dots/.config/kitty/kitty.conf rename to configurations/price/dots/xdg/config/kitty/kitty.conf diff --git a/dots/.config/kitty/themes/Catppucin.conf b/configurations/price/dots/xdg/config/kitty/themes/Catppucin.conf similarity index 100% rename from dots/.config/kitty/themes/Catppucin.conf rename to configurations/price/dots/xdg/config/kitty/themes/Catppucin.conf diff --git a/dots/.config/kitty/themes/Space-Duck.conf b/configurations/price/dots/xdg/config/kitty/themes/Space-Duck.conf similarity index 100% rename from dots/.config/kitty/themes/Space-Duck.conf rename to configurations/price/dots/xdg/config/kitty/themes/Space-Duck.conf diff --git a/dots/.config/kitty/themes/kanagawa.conf b/configurations/price/dots/xdg/config/kitty/themes/kanagawa.conf similarity index 100% rename from dots/.config/kitty/themes/kanagawa.conf rename to configurations/price/dots/xdg/config/kitty/themes/kanagawa.conf diff --git a/dots/.config/kitty/themes/nightfox.conf b/configurations/price/dots/xdg/config/kitty/themes/nightfox.conf similarity index 100% rename from dots/.config/kitty/themes/nightfox.conf rename to configurations/price/dots/xdg/config/kitty/themes/nightfox.conf diff --git a/dots/.config/kitty/themes/tokyo-night.conf b/configurations/price/dots/xdg/config/kitty/themes/tokyo-night.conf similarity index 100% rename from dots/.config/kitty/themes/tokyo-night.conf rename to configurations/price/dots/xdg/config/kitty/themes/tokyo-night.conf diff --git a/dots/.config/kitty/themes/tokyo-storm.conf b/configurations/price/dots/xdg/config/kitty/themes/tokyo-storm.conf similarity index 100% rename from dots/.config/kitty/themes/tokyo-storm.conf rename to configurations/price/dots/xdg/config/kitty/themes/tokyo-storm.conf diff --git a/dots/.config/mako/config b/configurations/price/dots/xdg/config/mako/config similarity index 100% rename from dots/.config/mako/config rename to configurations/price/dots/xdg/config/mako/config diff --git a/dots/.config/mimeapps.list b/configurations/price/dots/xdg/config/mimeapps.list similarity index 100% rename from dots/.config/mimeapps.list rename to configurations/price/dots/xdg/config/mimeapps.list diff --git a/configurations/price/dots/xdg/config/nix/nix.conf b/configurations/price/dots/xdg/config/nix/nix.conf new file mode 100644 index 00000000..4b8236de --- /dev/null +++ b/configurations/price/dots/xdg/config/nix/nix.conf @@ -0,0 +1,2 @@ +experimental-features = nix-command flakes +use-xdg-base-directories = true diff --git a/dots/.config/nvim/.stylua.toml b/configurations/price/dots/xdg/config/nvim/.stylua.toml similarity index 100% rename from dots/.config/nvim/.stylua.toml rename to configurations/price/dots/xdg/config/nvim/.stylua.toml diff --git a/dots/.config/nvim/after/ftplugin/NeogitCommitMessage.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/NeogitCommitMessage.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/NeogitCommitMessage.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/NeogitCommitMessage.lua diff --git a/dots/.config/nvim/after/ftplugin/Outline.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/Outline.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/Outline.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/Outline.lua diff --git a/dots/.config/nvim/after/ftplugin/asm.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/asm.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/asm.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/asm.lua diff --git a/dots/.config/nvim/after/ftplugin/azure-pipelines.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/azure-pipelines.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/azure-pipelines.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/azure-pipelines.lua diff --git a/dots/.config/nvim/after/ftplugin/azure.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/azure.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/azure.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/azure.lua diff --git a/dots/.config/nvim/after/ftplugin/cs.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/cs.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/cs.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/cs.lua diff --git a/dots/.config/nvim/after/ftplugin/css.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/css.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/css.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/css.lua diff --git a/dots/.config/nvim/after/ftplugin/dockerfile.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/dockerfile.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/dockerfile.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/dockerfile.lua diff --git a/dots/.config/nvim/after/ftplugin/gitconfig.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/gitconfig.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/gitconfig.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/gitconfig.lua diff --git a/dots/.config/nvim/after/ftplugin/html.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/html.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/html.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/html.lua diff --git a/dots/.config/nvim/after/ftplugin/http.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/http.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/http.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/http.lua diff --git a/dots/.config/nvim/after/ftplugin/hurl.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/hurl.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/hurl.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/hurl.lua diff --git a/dots/.config/nvim/after/ftplugin/jinja2.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/jinja2.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/jinja2.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/jinja2.lua diff --git a/dots/.config/nvim/after/ftplugin/json.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/json.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/json.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/json.lua diff --git a/dots/.config/nvim/after/ftplugin/lua.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/lua.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/lua.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/lua.lua diff --git a/dots/.config/nvim/after/ftplugin/make.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/make.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/make.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/make.lua diff --git a/dots/.config/nvim/after/ftplugin/man.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/man.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/man.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/man.lua diff --git a/dots/.config/nvim/after/ftplugin/markdown.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/markdown.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/markdown.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/markdown.lua diff --git a/dots/.config/nvim/after/ftplugin/nix.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/nix.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/nix.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/nix.lua diff --git a/dots/.config/nvim/after/ftplugin/norg.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/norg.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/norg.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/norg.lua diff --git a/dots/.config/nvim/after/ftplugin/octo.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/octo.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/octo.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/octo.lua diff --git a/dots/.config/nvim/after/ftplugin/python.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/python.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/python.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/python.lua diff --git a/dots/.config/nvim/after/ftplugin/rust.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/rust.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/rust.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/rust.lua diff --git a/dots/.config/nvim/after/ftplugin/sh.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/sh.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/sh.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/sh.lua diff --git a/dots/.config/nvim/after/ftplugin/sql.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/sql.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/sql.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/sql.lua diff --git a/dots/.config/nvim/after/ftplugin/sshdconfig.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/sshdconfig.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/sshdconfig.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/sshdconfig.lua diff --git a/dots/.config/nvim/after/ftplugin/systemd.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/systemd.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/systemd.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/systemd.lua diff --git a/dots/.config/nvim/after/ftplugin/termhistory.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/termhistory.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/termhistory.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/termhistory.lua diff --git a/dots/.config/nvim/after/ftplugin/terraform.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/terraform.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/terraform.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/terraform.lua diff --git a/dots/.config/nvim/after/ftplugin/tex.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/tex.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/tex.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/tex.lua diff --git a/dots/.config/nvim/after/ftplugin/typescript.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/typescript.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/typescript.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/typescript.lua diff --git a/dots/.config/nvim/after/ftplugin/xml.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/xml.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/xml.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/xml.lua diff --git a/dots/.config/nvim/after/ftplugin/yaml.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/yaml.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/yaml.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/yaml.lua diff --git a/dots/.config/nvim/after/ftplugin/zsh.lua b/configurations/price/dots/xdg/config/nvim/after/ftplugin/zsh.lua similarity index 100% rename from dots/.config/nvim/after/ftplugin/zsh.lua rename to configurations/price/dots/xdg/config/nvim/after/ftplugin/zsh.lua diff --git a/dots/.config/nvim/ftdetect/cf3.vim b/configurations/price/dots/xdg/config/nvim/ftdetect/cf3.vim similarity index 100% rename from dots/.config/nvim/ftdetect/cf3.vim rename to configurations/price/dots/xdg/config/nvim/ftdetect/cf3.vim diff --git a/dots/.config/nvim/ftdetect/log.lua b/configurations/price/dots/xdg/config/nvim/ftdetect/log.lua similarity index 100% rename from dots/.config/nvim/ftdetect/log.lua rename to configurations/price/dots/xdg/config/nvim/ftdetect/log.lua diff --git a/dots/.config/nvim/ftplugin/cf3.vim b/configurations/price/dots/xdg/config/nvim/ftplugin/cf3.vim similarity index 100% rename from dots/.config/nvim/ftplugin/cf3.vim rename to configurations/price/dots/xdg/config/nvim/ftplugin/cf3.vim diff --git a/dots/.config/nvim/init.lua b/configurations/price/dots/xdg/config/nvim/init.lua similarity index 100% rename from dots/.config/nvim/init.lua rename to configurations/price/dots/xdg/config/nvim/init.lua diff --git a/dots/.config/nvim/lazy-lock.json b/configurations/price/dots/xdg/config/nvim/lazy-lock.json similarity index 94% rename from dots/.config/nvim/lazy-lock.json rename to configurations/price/dots/xdg/config/nvim/lazy-lock.json index 72ace1e3..56b525b6 100644 --- a/dots/.config/nvim/lazy-lock.json +++ b/configurations/price/dots/xdg/config/nvim/lazy-lock.json @@ -38,17 +38,17 @@ "hydra.nvim": { "branch": "master", "commit": "3ced42c0b6a6c85583ff0f221635a7f4c1ab0dd0" }, "image.nvim": { "branch": "master", "commit": "1cb60be1cdc108e3a3b09cb0ed115ef75ce51320" }, "inc-rename.nvim": { "branch": "main", "commit": "ed0f6f2b917cac4eb3259f907da0a481b27a3b7e" }, - "indent-blankline.nvim": { "branch": "master", "commit": "8a7b48f5823cc924f815129192288ec2e2b9288f" }, + "indent-blankline.nvim": { "branch": "master", "commit": "2546441840172cc41e70f67c52e205cc7aa3e6ed" }, "kanagawa.nvim": { "branch": "master", "commit": "c19b9023842697ec92caf72cd3599f7dd7be4456" }, "keymap-layer.nvim": { "branch": "master", "commit": "e46840f9f377766e856964a49d7f351de3188a38" }, - "lazy.nvim": { "branch": "main", "commit": "42fb1e89adb8008a401848e131c5ecb985db52f1" }, + "lazy.nvim": { "branch": "main", "commit": "e42fccc3cda70266e0841c5126de2c23e8982800" }, "live-command.nvim": { "branch": "main", "commit": "d460067d47948725a6f25b20f31ea8bbfdfe4622" }, "lsp_lines.nvim": { "branch": "main", "commit": "9e3f99fbbd28aaec80dc0158c43be8cca8dd5017" }, "lspkind.nvim": { "branch": "master", "commit": "57610d5ab560c073c465d6faf0c19f200cb67e6e" }, "markdown-preview.nvim": { "branch": "master", "commit": "a923f5fc5ba36a3b17e289dc35dc17f66d0548ee" }, "mason-lspconfig.nvim": { "branch": "main", "commit": "09be3766669bfbabbe2863c624749d8da392c916" }, "mason.nvim": { "branch": "main", "commit": "cd7835b15f5a4204fc37e0aa739347472121a54c" }, - "mini.nvim": { "branch": "main", "commit": "35e29f7d680cfeb496415cadadd8c1f68db759b9" }, + "mini.nvim": { "branch": "main", "commit": "66e3cdceaba8c0cd089d6f42cb95e04355718f7a" }, "mkdir.nvim": { "branch": "main", "commit": "c55d1dee4f099528a1853b28bb28caa802eba217" }, "neo-tree.nvim": { "branch": "main", "commit": "2c782550d8a6675f1735970d18ef5d0701f2d789" }, "neodev.nvim": { "branch": "main", "commit": "d617d9eb27e73e701e446874c6ea2cb528719260" }, @@ -72,11 +72,11 @@ "nvim-lastplace": { "branch": "main", "commit": "0bb6103c506315044872e0f84b1f736c4172bb20" }, "nvim-lightbulb": { "branch": "master", "commit": "8f00b89dd1b1dbde16872bee5fbcee2e58c9b8e9" }, "nvim-lint": { "branch": "master", "commit": "a4b0511a9e757e78c8c9f9d3f201e0d8ff158b42" }, - "nvim-lspconfig": { "branch": "master", "commit": "38da5bbe1eaab2394056109e48c7e195bdb8fdfe" }, + "nvim-lspconfig": { "branch": "master", "commit": "6428fcab6f3c09e934bc016c329806314384a41e" }, "nvim-neoclip.lua": { "branch": "main", "commit": "4e406ae0f759262518731538f2585abb9d269bac" }, "nvim-notify": { "branch": "master", "commit": "e4a2022f4fec2d5ebc79afa612f96d8b11c627b3" }, "nvim-surround": { "branch": "main", "commit": "4f0e1f470595af067eca9b872778d83c7f52f134" }, - "nvim-treesitter": { "branch": "master", "commit": "0179a89656b4ce395a4487c07ae385b8425524ae" }, + "nvim-treesitter": { "branch": "master", "commit": "0b50cf159283855b72f4c6b22f5ba3c9cf813b37" }, "nvim-treesitter-context": { "branch": "master", "commit": "8aa32aa6b84dda357849dbc0f775e69f2e04c041" }, "nvim-treesitter-endwise": { "branch": "master", "commit": "4c344ffc8d54d7e1ba2cefaaa2c10ea93aa1cc2d" }, "nvim-treesitter-textobjects": { "branch": "master", "commit": "eb208bfdfcf76efea0424747e23e44641e13aaa6" }, @@ -101,7 +101,7 @@ "telescope-smart-history.nvim": { "branch": "master", "commit": "81a4cceaa54d65d5f7c7c26178ee63b634d3e26d" }, "telescope-ui-select.nvim": { "branch": "master", "commit": "b0015e6e4b46a64192c64b68dec9a9ac5a4e5690" }, "telescope-undo.nvim": { "branch": "main", "commit": "3dec002ea3e7952071d26fbb5d01e2038a58a554" }, - "telescope.nvim": { "branch": "master", "commit": "74ce793a60759e3db0d265174f137fb627430355" }, + "telescope.nvim": { "branch": "master", "commit": "8c9fd22952d5665f54f03052440e610c1a8d84cf" }, "telescope_find_directories": { "branch": "main", "commit": "30a29238eca7be1d2eeae7c814f6c0f20bc21931" }, "tint.nvim": { "branch": "master", "commit": "862835626941d263466754b9c8e2ce2cb004f5ac" }, "todo-comments.nvim": { "branch": "main", "commit": "3094ead8edfa9040de2421deddec55d3762f64d1" }, diff --git a/dots/.config/nvim/lua/core/autocmds.lua b/configurations/price/dots/xdg/config/nvim/lua/core/autocmds.lua similarity index 100% rename from dots/.config/nvim/lua/core/autocmds.lua rename to configurations/price/dots/xdg/config/nvim/lua/core/autocmds.lua diff --git a/dots/.config/nvim/lua/core/cmds.lua b/configurations/price/dots/xdg/config/nvim/lua/core/cmds.lua similarity index 100% rename from dots/.config/nvim/lua/core/cmds.lua rename to configurations/price/dots/xdg/config/nvim/lua/core/cmds.lua diff --git a/dots/.config/nvim/lua/core/disabled.lua b/configurations/price/dots/xdg/config/nvim/lua/core/disabled.lua similarity index 100% rename from dots/.config/nvim/lua/core/disabled.lua rename to configurations/price/dots/xdg/config/nvim/lua/core/disabled.lua diff --git a/dots/.config/nvim/lua/core/filetypes.lua b/configurations/price/dots/xdg/config/nvim/lua/core/filetypes.lua similarity index 100% rename from dots/.config/nvim/lua/core/filetypes.lua rename to configurations/price/dots/xdg/config/nvim/lua/core/filetypes.lua diff --git a/dots/.config/nvim/lua/core/globals.lua b/configurations/price/dots/xdg/config/nvim/lua/core/globals.lua similarity index 100% rename from dots/.config/nvim/lua/core/globals.lua rename to configurations/price/dots/xdg/config/nvim/lua/core/globals.lua diff --git a/dots/.config/nvim/lua/core/init.lua b/configurations/price/dots/xdg/config/nvim/lua/core/init.lua similarity index 100% rename from dots/.config/nvim/lua/core/init.lua rename to configurations/price/dots/xdg/config/nvim/lua/core/init.lua diff --git a/dots/.config/nvim/lua/core/lsp.lua b/configurations/price/dots/xdg/config/nvim/lua/core/lsp.lua similarity index 100% rename from dots/.config/nvim/lua/core/lsp.lua rename to configurations/price/dots/xdg/config/nvim/lua/core/lsp.lua diff --git a/dots/.config/nvim/lua/core/mappings.lua b/configurations/price/dots/xdg/config/nvim/lua/core/mappings.lua similarity index 100% rename from dots/.config/nvim/lua/core/mappings.lua rename to configurations/price/dots/xdg/config/nvim/lua/core/mappings.lua diff --git a/dots/.config/nvim/lua/core/options.lua b/configurations/price/dots/xdg/config/nvim/lua/core/options.lua similarity index 100% rename from dots/.config/nvim/lua/core/options.lua rename to configurations/price/dots/xdg/config/nvim/lua/core/options.lua diff --git a/dots/.config/nvim/lua/core/postload.lua b/configurations/price/dots/xdg/config/nvim/lua/core/postload.lua similarity index 100% rename from dots/.config/nvim/lua/core/postload.lua rename to configurations/price/dots/xdg/config/nvim/lua/core/postload.lua diff --git a/dots/.config/nvim/lua/core/winbar.lua b/configurations/price/dots/xdg/config/nvim/lua/core/winbar.lua similarity index 100% rename from dots/.config/nvim/lua/core/winbar.lua rename to configurations/price/dots/xdg/config/nvim/lua/core/winbar.lua diff --git a/dots/.config/nvim/lua/main.lua b/configurations/price/dots/xdg/config/nvim/lua/main.lua similarity index 100% rename from dots/.config/nvim/lua/main.lua rename to configurations/price/dots/xdg/config/nvim/lua/main.lua diff --git a/dots/.config/nvim/lua/plugins/autocmds.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/autocmds.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/autocmds.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/autocmds.lua diff --git a/dots/.config/nvim/lua/plugins/configs/alpha.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/alpha.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/alpha.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/alpha.lua diff --git a/dots/.config/nvim/lua/plugins/configs/autopairs.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/autopairs.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/autopairs.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/autopairs.lua diff --git a/dots/.config/nvim/lua/plugins/configs/bufdelete.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/bufdelete.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/bufdelete.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/bufdelete.lua diff --git a/dots/.config/nvim/lua/plugins/configs/cmp.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/cmp.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/cmp.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/cmp.lua diff --git a/dots/.config/nvim/lua/plugins/configs/comment.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/comment.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/comment.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/comment.lua diff --git a/dots/.config/nvim/lua/plugins/configs/dadbod.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/dadbod.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/dadbod.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/dadbod.lua diff --git a/dots/.config/nvim/lua/plugins/configs/dap.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/dap.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/dap.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/dap.lua diff --git a/dots/.config/nvim/lua/plugins/configs/flatten.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/flatten.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/flatten.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/flatten.lua diff --git a/dots/.config/nvim/lua/plugins/configs/formatter.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/formatter.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/formatter.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/formatter.lua diff --git a/dots/.config/nvim/lua/plugins/configs/fundo.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/fundo.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/fundo.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/fundo.lua diff --git a/dots/.config/nvim/lua/plugins/configs/git.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/git.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/git.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/git.lua diff --git a/dots/.config/nvim/lua/plugins/configs/github.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/github.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/github.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/github.lua diff --git a/dots/.config/nvim/lua/plugins/configs/gx.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/gx.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/gx.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/gx.lua diff --git a/dots/.config/nvim/lua/plugins/configs/headlines.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/headlines.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/headlines.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/headlines.lua diff --git a/dots/.config/nvim/lua/plugins/configs/heirline.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/heirline.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/heirline.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/heirline.lua diff --git a/dots/.config/nvim/lua/plugins/configs/highlight-colors.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/highlight-colors.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/highlight-colors.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/highlight-colors.lua diff --git a/dots/.config/nvim/lua/plugins/configs/highlight-undo.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/highlight-undo.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/highlight-undo.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/highlight-undo.lua diff --git a/dots/.config/nvim/lua/plugins/configs/hop.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/hop.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/hop.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/hop.lua diff --git a/dots/.config/nvim/lua/plugins/configs/hydra.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/hydra.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/hydra.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/hydra.lua diff --git a/dots/.config/nvim/lua/plugins/configs/image.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/image.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/image.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/image.lua diff --git a/dots/.config/nvim/lua/plugins/configs/indent-blankline.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/indent-blankline.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/indent-blankline.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/indent-blankline.lua diff --git a/dots/.config/nvim/lua/plugins/configs/kanagawa.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/kanagawa.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/kanagawa.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/kanagawa.lua diff --git a/dots/.config/nvim/lua/plugins/configs/lastplace.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/lastplace.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/lastplace.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/lastplace.lua diff --git a/dots/.config/nvim/lua/plugins/configs/lib.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/lib.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/lib.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/lib.lua diff --git a/dots/.config/nvim/lua/plugins/configs/live-command.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/live-command.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/live-command.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/live-command.lua diff --git a/dots/.config/nvim/lua/plugins/configs/lsp.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/lsp.lua similarity index 99% rename from dots/.config/nvim/lua/plugins/configs/lsp.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/lsp.lua index dbe31ed1..5ca60dec 100644 --- a/dots/.config/nvim/lua/plugins/configs/lsp.lua +++ b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/lsp.lua @@ -486,6 +486,7 @@ return { "tflint", "vimls", "rnix", + "nixd", "marksman", "asm_lsp", "denols" diff --git a/dots/.config/nvim/lua/plugins/configs/markdown.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/markdown.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/markdown.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/markdown.lua diff --git a/dots/.config/nvim/lua/plugins/configs/mini.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/mini.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/mini.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/mini.lua diff --git a/dots/.config/nvim/lua/plugins/configs/mkdir.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/mkdir.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/mkdir.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/mkdir.lua diff --git a/dots/.config/nvim/lua/plugins/configs/move.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/move.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/move.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/move.lua diff --git a/dots/.config/nvim/lua/plugins/configs/neo-tree.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/neo-tree.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/neo-tree.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/neo-tree.lua diff --git a/dots/.config/nvim/lua/plugins/configs/neoclip.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/neoclip.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/neoclip.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/neoclip.lua diff --git a/dots/.config/nvim/lua/plugins/configs/neoformat.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/neoformat.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/neoformat.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/neoformat.lua diff --git a/dots/.config/nvim/lua/plugins/configs/neorg.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/neorg.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/neorg.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/neorg.lua diff --git a/dots/.config/nvim/lua/plugins/configs/neoscroll.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/neoscroll.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/neoscroll.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/neoscroll.lua diff --git a/dots/.config/nvim/lua/plugins/configs/nftables.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/nftables.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/nftables.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/nftables.lua diff --git a/dots/.config/nvim/lua/plugins/configs/nibbler.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/nibbler.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/nibbler.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/nibbler.lua diff --git a/dots/.config/nvim/lua/plugins/configs/noice.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/noice.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/noice.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/noice.lua diff --git a/dots/.config/nvim/lua/plugins/configs/nvim-lint.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/nvim-lint.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/nvim-lint.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/nvim-lint.lua diff --git a/dots/.config/nvim/lua/plugins/configs/nvim-ufo.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/nvim-ufo.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/nvim-ufo.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/nvim-ufo.lua diff --git a/dots/.config/nvim/lua/plugins/configs/rest-nvim.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/rest-nvim.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/rest-nvim.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/rest-nvim.lua diff --git a/dots/.config/nvim/lua/plugins/configs/statuscol.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/statuscol.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/statuscol.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/statuscol.lua diff --git a/dots/.config/nvim/lua/plugins/configs/surround.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/surround.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/surround.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/surround.lua diff --git a/dots/.config/nvim/lua/plugins/configs/telescope.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/telescope.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/telescope.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/telescope.lua diff --git a/dots/.config/nvim/lua/plugins/configs/tint.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/tint.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/tint.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/tint.lua diff --git a/dots/.config/nvim/lua/plugins/configs/toggleterm.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/toggleterm.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/toggleterm.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/toggleterm.lua diff --git a/dots/.config/nvim/lua/plugins/configs/treesitter.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/treesitter.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/treesitter.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/treesitter.lua diff --git a/dots/.config/nvim/lua/plugins/configs/trouble.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/trouble.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/trouble.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/trouble.lua diff --git a/dots/.config/nvim/lua/plugins/configs/various-textobjs.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/various-textobjs.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/various-textobjs.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/various-textobjs.lua diff --git a/dots/.config/nvim/lua/plugins/configs/vim-repeat.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/vim-repeat.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/vim-repeat.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/vim-repeat.lua diff --git a/dots/.config/nvim/lua/plugins/configs/vim-table-mode.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/vim-table-mode.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/vim-table-mode.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/vim-table-mode.lua diff --git a/dots/.config/nvim/lua/plugins/configs/vim-visual-multi.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/vim-visual-multi.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/vim-visual-multi.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/vim-visual-multi.lua diff --git a/dots/.config/nvim/lua/plugins/configs/vimtex.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/vimtex.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/vimtex.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/vimtex.lua diff --git a/dots/.config/nvim/lua/plugins/configs/which-key.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/configs/which-key.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/configs/which-key.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/configs/which-key.lua diff --git a/dots/.config/nvim/lua/plugins/init.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/init.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/init.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/init.lua diff --git a/dots/.config/nvim/lua/plugins/postload.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/postload.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/postload.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/postload.lua diff --git a/dots/.config/nvim/lua/plugins/snippets/python.lua b/configurations/price/dots/xdg/config/nvim/lua/plugins/snippets/python.lua similarity index 100% rename from dots/.config/nvim/lua/plugins/snippets/python.lua rename to configurations/price/dots/xdg/config/nvim/lua/plugins/snippets/python.lua diff --git a/dots/.config/nvim/lua/utils/funcs.lua b/configurations/price/dots/xdg/config/nvim/lua/utils/funcs.lua similarity index 100% rename from dots/.config/nvim/lua/utils/funcs.lua rename to configurations/price/dots/xdg/config/nvim/lua/utils/funcs.lua diff --git a/dots/.config/nvim/spell/en.utf-8.add b/configurations/price/dots/xdg/config/nvim/spell/en.utf-8.add similarity index 100% rename from dots/.config/nvim/spell/en.utf-8.add rename to configurations/price/dots/xdg/config/nvim/spell/en.utf-8.add diff --git a/dots/.config/nvim/spell/en.utf-8.add.spl b/configurations/price/dots/xdg/config/nvim/spell/en.utf-8.add.spl similarity index 100% rename from dots/.config/nvim/spell/en.utf-8.add.spl rename to configurations/price/dots/xdg/config/nvim/spell/en.utf-8.add.spl diff --git a/dots/.config/nvim/syntax/cf3.vim b/configurations/price/dots/xdg/config/nvim/syntax/cf3.vim similarity index 100% rename from dots/.config/nvim/syntax/cf3.vim rename to configurations/price/dots/xdg/config/nvim/syntax/cf3.vim diff --git a/dots/.config/nvim/syntax/log.vim b/configurations/price/dots/xdg/config/nvim/syntax/log.vim similarity index 100% rename from dots/.config/nvim/syntax/log.vim rename to configurations/price/dots/xdg/config/nvim/syntax/log.vim diff --git a/dots/.config/powershell/Microsoft.PowerShell_profile.ps1 b/configurations/price/dots/xdg/config/powershell/Microsoft.PowerShell_profile.ps1 similarity index 100% rename from dots/.config/powershell/Microsoft.PowerShell_profile.ps1 rename to configurations/price/dots/xdg/config/powershell/Microsoft.PowerShell_profile.ps1 diff --git a/dots/.config/silicon/themes/kanagawa.tmTheme b/configurations/price/dots/xdg/config/silicon/themes/kanagawa.tmTheme similarity index 100% rename from dots/.config/silicon/themes/kanagawa.tmTheme rename to configurations/price/dots/xdg/config/silicon/themes/kanagawa.tmTheme diff --git a/dots/.config/stylua.toml b/configurations/price/dots/xdg/config/stylua.toml similarity index 100% rename from dots/.config/stylua.toml rename to configurations/price/dots/xdg/config/stylua.toml diff --git a/dots/.config/systemd/user/.gitignore b/configurations/price/dots/xdg/config/systemd/user/.gitignore similarity index 100% rename from dots/.config/systemd/user/.gitignore rename to configurations/price/dots/xdg/config/systemd/user/.gitignore diff --git a/dots/.config/systemd/user/compositor.target b/configurations/price/dots/xdg/config/systemd/user/compositor.target similarity index 100% rename from dots/.config/systemd/user/compositor.target rename to configurations/price/dots/xdg/config/systemd/user/compositor.target diff --git a/dots/.config/systemd/user/polkit.service b/configurations/price/dots/xdg/config/systemd/user/polkit.service similarity index 100% rename from dots/.config/systemd/user/polkit.service rename to configurations/price/dots/xdg/config/systemd/user/polkit.service diff --git a/dots/.config/systemd/user/scripts/init-wallpapers.bash b/configurations/price/dots/xdg/config/systemd/user/scripts/init-wallpapers.bash similarity index 100% rename from dots/.config/systemd/user/scripts/init-wallpapers.bash rename to configurations/price/dots/xdg/config/systemd/user/scripts/init-wallpapers.bash diff --git a/dots/.config/systemd/user/swww-init-wallpapers.service b/configurations/price/dots/xdg/config/systemd/user/swww-init-wallpapers.service similarity index 100% rename from dots/.config/systemd/user/swww-init-wallpapers.service rename to configurations/price/dots/xdg/config/systemd/user/swww-init-wallpapers.service diff --git a/dots/.config/systemd/user/swww.service b/configurations/price/dots/xdg/config/systemd/user/swww.service similarity index 100% rename from dots/.config/systemd/user/swww.service rename to configurations/price/dots/xdg/config/systemd/user/swww.service diff --git a/dots/.config/waybar/config b/configurations/price/dots/xdg/config/waybar/config similarity index 100% rename from dots/.config/waybar/config rename to configurations/price/dots/xdg/config/waybar/config diff --git a/dots/.config/waybar/scripts/get-media.bash b/configurations/price/dots/xdg/config/waybar/scripts/get-media.bash similarity index 100% rename from dots/.config/waybar/scripts/get-media.bash rename to configurations/price/dots/xdg/config/waybar/scripts/get-media.bash diff --git a/dots/.config/waybar/scripts/get-pacman-package-updates.bash b/configurations/price/dots/xdg/config/waybar/scripts/get-pacman-package-updates.bash similarity index 100% rename from dots/.config/waybar/scripts/get-pacman-package-updates.bash rename to configurations/price/dots/xdg/config/waybar/scripts/get-pacman-package-updates.bash diff --git a/dots/.config/waybar/scripts/set-rfkill.bash b/configurations/price/dots/xdg/config/waybar/scripts/set-rfkill.bash similarity index 100% rename from dots/.config/waybar/scripts/set-rfkill.bash rename to configurations/price/dots/xdg/config/waybar/scripts/set-rfkill.bash diff --git a/dots/.config/waybar/style.css b/configurations/price/dots/xdg/config/waybar/style.css similarity index 100% rename from dots/.config/waybar/style.css rename to configurations/price/dots/xdg/config/waybar/style.css diff --git a/dots/.config/wezterm/.editorconfig b/configurations/price/dots/xdg/config/wezterm/.editorconfig similarity index 100% rename from dots/.config/wezterm/.editorconfig rename to configurations/price/dots/xdg/config/wezterm/.editorconfig diff --git a/dots/.config/wezterm/.stylua.toml b/configurations/price/dots/xdg/config/wezterm/.stylua.toml similarity index 100% rename from dots/.config/wezterm/.stylua.toml rename to configurations/price/dots/xdg/config/wezterm/.stylua.toml diff --git a/dots/.config/wezterm/config/events.lua b/configurations/price/dots/xdg/config/wezterm/config/events.lua similarity index 100% rename from dots/.config/wezterm/config/events.lua rename to configurations/price/dots/xdg/config/wezterm/config/events.lua diff --git a/dots/.config/wezterm/config/fonts.lua b/configurations/price/dots/xdg/config/wezterm/config/fonts.lua similarity index 100% rename from dots/.config/wezterm/config/fonts.lua rename to configurations/price/dots/xdg/config/wezterm/config/fonts.lua diff --git a/dots/.config/wezterm/config/gpu.lua b/configurations/price/dots/xdg/config/wezterm/config/gpu.lua similarity index 100% rename from dots/.config/wezterm/config/gpu.lua rename to configurations/price/dots/xdg/config/wezterm/config/gpu.lua diff --git a/dots/.config/wezterm/config/keybinds.lua b/configurations/price/dots/xdg/config/wezterm/config/keybinds.lua similarity index 100% rename from dots/.config/wezterm/config/keybinds.lua rename to configurations/price/dots/xdg/config/wezterm/config/keybinds.lua diff --git a/dots/.config/wezterm/config/misc.lua b/configurations/price/dots/xdg/config/wezterm/config/misc.lua similarity index 100% rename from dots/.config/wezterm/config/misc.lua rename to configurations/price/dots/xdg/config/wezterm/config/misc.lua diff --git a/dots/.config/wezterm/config/os/linux.lua b/configurations/price/dots/xdg/config/wezterm/config/os/linux.lua similarity index 100% rename from dots/.config/wezterm/config/os/linux.lua rename to configurations/price/dots/xdg/config/wezterm/config/os/linux.lua diff --git a/dots/.config/wezterm/config/os/windows.lua b/configurations/price/dots/xdg/config/wezterm/config/os/windows.lua similarity index 100% rename from dots/.config/wezterm/config/os/windows.lua rename to configurations/price/dots/xdg/config/wezterm/config/os/windows.lua diff --git a/dots/.config/wezterm/config/rendering.lua b/configurations/price/dots/xdg/config/wezterm/config/rendering.lua similarity index 100% rename from dots/.config/wezterm/config/rendering.lua rename to configurations/price/dots/xdg/config/wezterm/config/rendering.lua diff --git a/dots/.config/wezterm/config/tabbar.lua b/configurations/price/dots/xdg/config/wezterm/config/tabbar.lua similarity index 100% rename from dots/.config/wezterm/config/tabbar.lua rename to configurations/price/dots/xdg/config/wezterm/config/tabbar.lua diff --git a/dots/.config/wezterm/config/theme/colors.lua b/configurations/price/dots/xdg/config/wezterm/config/theme/colors.lua similarity index 100% rename from dots/.config/wezterm/config/theme/colors.lua rename to configurations/price/dots/xdg/config/wezterm/config/theme/colors.lua diff --git a/dots/.config/wezterm/config/theme/theme.lua b/configurations/price/dots/xdg/config/wezterm/config/theme/theme.lua similarity index 100% rename from dots/.config/wezterm/config/theme/theme.lua rename to configurations/price/dots/xdg/config/wezterm/config/theme/theme.lua diff --git a/dots/.config/wezterm/lib/inspect.lua b/configurations/price/dots/xdg/config/wezterm/lib/inspect.lua similarity index 100% rename from dots/.config/wezterm/lib/inspect.lua rename to configurations/price/dots/xdg/config/wezterm/lib/inspect.lua diff --git a/dots/.config/wezterm/lib/log.lua b/configurations/price/dots/xdg/config/wezterm/lib/log.lua similarity index 100% rename from dots/.config/wezterm/lib/log.lua rename to configurations/price/dots/xdg/config/wezterm/lib/log.lua diff --git a/dots/.config/wezterm/lib/wlib.lua b/configurations/price/dots/xdg/config/wezterm/lib/wlib.lua similarity index 100% rename from dots/.config/wezterm/lib/wlib.lua rename to configurations/price/dots/xdg/config/wezterm/lib/wlib.lua diff --git a/dots/.config/wezterm/wezterm.lua b/configurations/price/dots/xdg/config/wezterm/wezterm.lua similarity index 100% rename from dots/.config/wezterm/wezterm.lua rename to configurations/price/dots/xdg/config/wezterm/wezterm.lua diff --git a/dots/.config/wofi/config b/configurations/price/dots/xdg/config/wofi/config similarity index 100% rename from dots/.config/wofi/config rename to configurations/price/dots/xdg/config/wofi/config diff --git a/dots/.config/wofi/style.css b/configurations/price/dots/xdg/config/wofi/style.css similarity index 100% rename from dots/.config/wofi/style.css rename to configurations/price/dots/xdg/config/wofi/style.css diff --git a/dots/.config/zathura/zathurarc b/configurations/price/dots/xdg/config/zathura/zathurarc similarity index 100% rename from dots/.config/zathura/zathurarc rename to configurations/price/dots/xdg/config/zathura/zathurarc diff --git a/dots/.config/zsh/config/completions/completions/_Note b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_Note similarity index 100% rename from dots/.config/zsh/config/completions/completions/_Note rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_Note diff --git a/dots/.config/zsh/config/completions/completions/_aws b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_aws similarity index 100% rename from dots/.config/zsh/config/completions/completions/_aws rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_aws diff --git a/dots/.config/zsh/config/completions/completions/_bat b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_bat similarity index 100% rename from dots/.config/zsh/config/completions/completions/_bat rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_bat diff --git a/dots/.config/zsh/config/completions/completions/_cargo b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_cargo similarity index 100% rename from dots/.config/zsh/config/completions/completions/_cargo rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_cargo diff --git a/dots/.config/zsh/config/completions/completions/_cmake b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_cmake similarity index 100% rename from dots/.config/zsh/config/completions/completions/_cmake rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_cmake diff --git a/dots/.config/zsh/config/completions/completions/_curl b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_curl similarity index 100% rename from dots/.config/zsh/config/completions/completions/_curl rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_curl diff --git a/dots/.config/zsh/config/completions/completions/_delta b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_delta similarity index 100% rename from dots/.config/zsh/config/completions/completions/_delta rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_delta diff --git a/dots/.config/zsh/config/completions/completions/_dotnet b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_dotnet similarity index 100% rename from dots/.config/zsh/config/completions/completions/_dotnet rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_dotnet diff --git a/dots/.config/zsh/config/completions/completions/_exa b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_exa similarity index 100% rename from dots/.config/zsh/config/completions/completions/_exa rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_exa diff --git a/dots/.config/zsh/config/completions/completions/_fail2ban-client b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_fail2ban-client similarity index 100% rename from dots/.config/zsh/config/completions/completions/_fail2ban-client rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_fail2ban-client diff --git a/dots/.config/zsh/config/completions/completions/_fd b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_fd similarity index 100% rename from dots/.config/zsh/config/completions/completions/_fd rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_fd diff --git a/dots/.config/zsh/config/completions/completions/_firewalld b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_firewalld similarity index 100% rename from dots/.config/zsh/config/completions/completions/_firewalld rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_firewalld diff --git a/dots/.config/zsh/config/completions/completions/_gh b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_gh similarity index 100% rename from dots/.config/zsh/config/completions/completions/_gh rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_gh diff --git a/dots/.config/zsh/config/completions/completions/_golang b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_golang similarity index 100% rename from dots/.config/zsh/config/completions/completions/_golang rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_golang diff --git a/dots/.config/zsh/config/completions/completions/_j b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_j similarity index 100% rename from dots/.config/zsh/config/completions/completions/_j rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_j diff --git a/dots/.config/zsh/config/completions/completions/_kubectl b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_kubectl similarity index 100% rename from dots/.config/zsh/config/completions/completions/_kubectl rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_kubectl diff --git a/dots/.config/zsh/config/completions/completions/_minikube b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_minikube similarity index 100% rename from dots/.config/zsh/config/completions/completions/_minikube rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_minikube diff --git a/dots/.config/zsh/config/completions/completions/_mpv b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_mpv similarity index 100% rename from dots/.config/zsh/config/completions/completions/_mpv rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_mpv diff --git a/dots/.config/zsh/config/completions/completions/_ninja b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_ninja similarity index 100% rename from dots/.config/zsh/config/completions/completions/_ninja rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_ninja diff --git a/dots/.config/zsh/config/completions/completions/_nvim-env b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_nvim-env similarity index 100% rename from dots/.config/zsh/config/completions/completions/_nvim-env rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_nvim-env diff --git a/dots/.config/zsh/config/completions/completions/_openssl b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_openssl similarity index 100% rename from dots/.config/zsh/config/completions/completions/_openssl rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_openssl diff --git a/dots/.config/zsh/config/completions/completions/_pgsql_utils b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_pgsql_utils similarity index 100% rename from dots/.config/zsh/config/completions/completions/_pgsql_utils rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_pgsql_utils diff --git a/dots/.config/zsh/config/completions/completions/_poetry b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_poetry similarity index 100% rename from dots/.config/zsh/config/completions/completions/_poetry rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_poetry diff --git a/dots/.config/zsh/config/completions/completions/_rg b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_rg similarity index 100% rename from dots/.config/zsh/config/completions/completions/_rg rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_rg diff --git a/dots/.config/zsh/config/completions/completions/_rustup b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_rustup similarity index 100% rename from dots/.config/zsh/config/completions/completions/_rustup rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_rustup diff --git a/dots/.config/zsh/config/completions/completions/_shellcheck b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_shellcheck similarity index 100% rename from dots/.config/zsh/config/completions/completions/_shellcheck rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_shellcheck diff --git a/dots/.config/zsh/config/completions/completions/_vagrant b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_vagrant similarity index 100% rename from dots/.config/zsh/config/completions/completions/_vagrant rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_vagrant diff --git a/dots/.config/zsh/config/completions/completions/_wezterm b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_wezterm similarity index 100% rename from dots/.config/zsh/config/completions/completions/_wezterm rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_wezterm diff --git a/dots/.config/zsh/config/completions/completions/_yarn b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_yarn similarity index 100% rename from dots/.config/zsh/config/completions/completions/_yarn rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_yarn diff --git a/dots/.config/zsh/config/completions/completions/_yt-dlp b/configurations/price/dots/xdg/config/zsh/config/completions/completions/_yt-dlp similarity index 100% rename from dots/.config/zsh/config/completions/completions/_yt-dlp rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/_yt-dlp diff --git a/dots/.config/zsh/config/completions/completions/aws_zsh_completer.sh b/configurations/price/dots/xdg/config/zsh/config/completions/completions/aws_zsh_completer.sh similarity index 100% rename from dots/.config/zsh/config/completions/completions/aws_zsh_completer.sh rename to configurations/price/dots/xdg/config/zsh/config/completions/completions/aws_zsh_completer.sh diff --git a/dots/.config/zsh/config/completions/init.zsh b/configurations/price/dots/xdg/config/zsh/config/completions/init.zsh similarity index 100% rename from dots/.config/zsh/config/completions/init.zsh rename to configurations/price/dots/xdg/config/zsh/config/completions/init.zsh diff --git a/dots/.config/zsh/config/init.zsh b/configurations/price/dots/xdg/config/zsh/config/init.zsh similarity index 100% rename from dots/.config/zsh/config/init.zsh rename to configurations/price/dots/xdg/config/zsh/config/init.zsh diff --git a/dots/.config/zsh/config/omz/init.zsh b/configurations/price/dots/xdg/config/zsh/config/omz/init.zsh similarity index 100% rename from dots/.config/zsh/config/omz/init.zsh rename to configurations/price/dots/xdg/config/zsh/config/omz/init.zsh diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.gitattributes b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.gitattributes new file mode 100644 index 00000000..0f952061 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.gitattributes @@ -0,0 +1,2 @@ +modules/** linguist-vendored +modules/Src/aloxaf/*.c -linguist-vendored diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.github/ISSUE_TEMPLATE/bug_report.md b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.github/ISSUE_TEMPLATE/bug_report.md new file mode 100644 index 00000000..e804a3af --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.github/ISSUE_TEMPLATE/bug_report.md @@ -0,0 +1,42 @@ +--- +name: Bug report +about: Create a report to help us improve +title: "[BUG]" +labels: bug +assignees: '' + +--- + +#### Describe the bug +A clear and concise description of what the bug is. + +I can make sure: +- [ ] I am using the latest version of fzf-tab +- [ ] this is the minimal zshrc which can reproduce this bug +- [ ] fzf-tab is loaded after `compinit` +- [ ] fzf-tab is loaded after plugins which will wrap Tab, like [junegunn/fzf/completion.zsh](https://github.com/junegunn/fzf/blob/master/shell/completion.zsh) +- [ ] fzf-tab is loaded before zsh-autosuggestions, zsh-syntax-highlighting and fast-syntax-highlighting. + +#### To Reproduce +Steps to reproduce the behavior: +1. Type '...' +2. Press Tab +4. See error + +#### Expected behavior +A clear and concise description of what you expected to happen. + +#### Screenshots +If applicable, add screenshots to help explain your problem. + +#### Environment: + - OS: [e.g. Arch Linux] + - zsh version: [e.g. 5.8.1] + +#### Minimal zshrc +If applicable, add a minimal zshrc to help us analyze. + +#### Log +If applicable, use `C-x .` to trigger completion and provide the log. + +If there are only three lines in your log, please make sure your fzf-tab is loaded with the correct order (see the checklist above). diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.github/ISSUE_TEMPLATE/feature_request.md b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..524940e5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: "[FR]" +labels: enhancement +assignees: '' + +--- + +**Is your feature request related to a problem? Please describe.** +A clear and concise description of what the problem is. Ex. I'm always frustrated when [...] + +**Describe the solution you'd like** +A clear and concise description of what you want to happen. + +**Describe alternatives you've considered** +A clear and concise description of any alternative solutions or features you've considered. + +**Additional context** +Add any other context or screenshots about the feature request here. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.github/ISSUE_TEMPLATE/question.md b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.github/ISSUE_TEMPLATE/question.md new file mode 100644 index 00000000..9d2f92cc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.github/ISSUE_TEMPLATE/question.md @@ -0,0 +1,11 @@ +--- +name: Question +about: Ask a question about fzf-tab +title: "[Q]" +labels: question +assignees: '' + +--- + +**Describe your question** +A clear and concise description of your question. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.github/workflows/ci.yaml b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.github/workflows/ci.yaml new file mode 100644 index 00000000..893f8a45 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.github/workflows/ci.yaml @@ -0,0 +1,36 @@ +name: ci + +on: + pull_request: + push: + branches: + - master + +jobs: + test: + name: run test + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macos-latest] + steps: + - name: checkout + uses: actions/checkout@v1 + with: + fetch-depth: 1 + + - name: install zsh (ubuntu) + if: matrix.os == 'ubuntu-latest' + run: sudo apt-get install zsh + + - name: test completion (ubuntu) + if: matrix.os == 'ubuntu-latest' + run: cd test && zsh -f runtests.zsh fzftab.ztst + + - name: build binary module + run: zsh -fc 'source ./fzf-tab.zsh && build-fzf-tab-module' + + - name: test binary module (ubuntu) + if: matrix.os == 'ubuntu-latest' + run: cd test && zsh -f runtests.zsh fzftab.ztst + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.gitignore b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.gitignore new file mode 100644 index 00000000..416cfaac --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/.gitignore @@ -0,0 +1 @@ +*.zwc diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/LICENSE b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/LICENSE new file mode 100644 index 00000000..a3c39ebb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019-2021 Aloxaf + +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. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/README.md new file mode 100644 index 00000000..d324d03d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/README.md @@ -0,0 +1,140 @@ +# fzf-tab + +[![CI](https://github.com/Aloxaf/fzf-tab/workflows/ci/badge.svg)](https://github.com/Aloxaf/fzf-tab/actions?query=workflow%3Aci) +[![GitHub license](https://img.shields.io/github/license/Aloxaf/fzf-tab)](https://github.com/Aloxaf/fzf-tab/blob/master/LICENSE) + +Replace zsh's default completion selection menu with fzf! + +[![asciicast](https://asciinema.org/a/293849.svg)](https://asciinema.org/a/293849) + + +**Table of Contents** + +- [fzf-tab](#fzf-tab) +- [Install](#install) + - [Manual](#manual) + - [Antigen](#antigen) + - [Zinit](#zinit) + - [Oh-My-Zsh](#oh-my-zsh) + - [Prezto](#prezto) +- [Usage](#usage) + - [Configure](#configure) + - [Binary module](#binary-module) +- [Difference from other plugins](#difference-from-other-plugins) +- [Compatibility with other plugins](#compatibility-with-other-plugins) +- [Related projects](#related-projects) + + + +# Install + +**NOTE: fzf-tab needs to be loaded after `compinit`, but before plugins which will wrap widgets, such as [zsh-autosuggestions](https://github.com/zsh-users/zsh-autosuggestions) or [fast-syntax-highlighting](https://github.com/zdharma-continuum/fast-syntax-highlighting)!!** + +**NOTE 2: fzf-tab ALSO needs [fzf](https://github.com/junegunn/fzf) installed, otherwise it cannot work!** + +### Manual + +First, clone this repository. + +```zsh +git clone https://github.com/Aloxaf/fzf-tab ~/somewhere +``` + +Then add the following line to your `~/.zshrc`. + +```zsh +source ~/somewhere/fzf-tab.plugin.zsh +``` + +### Antigen + +```zsh +antigen bundle Aloxaf/fzf-tab +``` + +### Zinit + +```zsh +zinit light Aloxaf/fzf-tab +``` + +### Oh-My-Zsh + +Clone this repository to your custom directory and then add `fzf-tab` to your plugin list. + +```zsh +git clone https://github.com/Aloxaf/fzf-tab ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/fzf-tab +``` + +### Prezto + +Clone this repository to your contrib directory and then add `fzf-tab` to your module list in `.zpreztorc`. + +```zsh +git clone https://github.com/Aloxaf/fzf-tab $ZPREZTODIR/contrib/fzf-tab +``` + +# Usage + +Just press Tab as usual~ + +Available keybindings: + +- Ctrl+Space: select multiple results, can be configured by `fzf-bindings` tag + +- F1/F2: switch between groups, can be configured by `switch-group` tag + +- /: trigger continuous completion (useful when completing a deep path), can be configured by `continuous-trigger` tag + +Available commands: + +- `disable-fzf-tab`: disable fzf-tab and fallback to compsys + +- `enable-fzf-tab`: enable fzf-tab + +- `toggle-fzf-tab`: toggle the state of fzf-tab. This is also a zle widget. + +## Configure + +A common configuration is: + +```zsh +# disable sort when completing `git checkout` +zstyle ':completion:*:git-checkout:*' sort false +# set descriptions format to enable group support +zstyle ':completion:*:descriptions' format '[%d]' +# set list-colors to enable filename colorizing +zstyle ':completion:*' list-colors ${(s.:.)LS_COLORS} +# preview directory's content with exa when completing cd +zstyle ':fzf-tab:complete:cd:*' fzf-preview 'exa -1 --color=always $realpath' +# switch group using `,` and `.` +zstyle ':fzf-tab:*' switch-group ',' '.' +``` + +For more information, please see [Wiki#Configuration](https://github.com/Aloxaf/fzf-tab/wiki/Configuration). + +## Binary module + +By default, fzf-tab uses [zsh-ls-colors](https://github.com/xPMo/zsh-ls-colors) to parse and apply ZLS_COLORS if you have set the `list-colors` tag. + +However, it is a pure zsh script and is slow if you have too many files to colorize. +fzf-tab is shipped with a binary module to speed up this process. You can build it with `build-fzf-tab-module`, then it will be enabled automatically. + +# Difference from other plugins + +fzf-tab doesn't do "complete", it just shows you the results of the default completion system. + +So it works EVERYWHERE (variables, function names, directory stack, in-word completion, etc.). +And most of your configuration for default completion system is still valid. + +# Compatibility with other plugins + +Some plugins may also bind "^I" to their custom widget, like [fzf/shell/completion.zsh](https://github.com/junegunn/fzf/blob/master/shell/completion.zsh) or [ohmyzsh/lib/completion.zsh](https://github.com/ohmyzsh/ohmyzsh/blob/master/lib/completion.zsh#L61-L73). + +By default, fzf-tab will call the widget previously bound to "^I" to get the completion list. So there is no problem in most cases, unless fzf-tab is initialized before a plugin which doesn't handle the previous binding properly. + +So if you find your fzf-tab doesn't work properly, **please make sure it is the last plugin to bind "^I"** (If you don't know what I mean, just put it to the end of your plugin list). + +# Related projects + +- https://github.com/lincheney/fzf-tab-completion (fzf tab completion for zsh, bash and GNU readline apps) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/fzf-tab.plugin.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/fzf-tab.plugin.zsh new file mode 100644 index 00000000..f78964c2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/fzf-tab.plugin.zsh @@ -0,0 +1,3 @@ +0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}" +0="${${(M)0:#/*}:-$PWD/$0}" +source "${0:A:h}/fzf-tab.zsh" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/fzf-tab.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/fzf-tab.zsh new file mode 100644 index 00000000..b81716db --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/fzf-tab.zsh @@ -0,0 +1,417 @@ +# temporarily change options +'builtin' 'local' '-a' '_ftb_opts' +[[ ! -o 'aliases' ]] || _ftb_opts+=('aliases') +[[ ! -o 'sh_glob' ]] || _ftb_opts+=('sh_glob') +[[ ! -o 'no_brace_expand' ]] || _ftb_opts+=('no_brace_expand') +'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand' + +# thanks Valodim/zsh-capture-completion +-ftb-compadd() { + # parse all options + local -A apre hpre dscrs _oad _mesg + local -a isfile _opts __ expl + zparseopts -E -a _opts P:=apre p:=hpre d:=dscrs X+:=expl O:=_oad A:=_oad D:=_oad f=isfile \ + i: S: s: I: x:=_mesg r: R: W: F: M+: E: q e Q n U C \ + J:=__ V:=__ a=__ l=__ k=__ o=__ 1=__ 2=__ + + # store $curcontext for further usage + _ftb_curcontext=${curcontext#:} + + # just delegate and leave if any of -O, -A or -D are given or fzf-tab is not enabled + # or fzf-tab is disabled in the current context + if (( $#_oad != 0 || ! IN_FZF_TAB )) \ + || { -ftb-zstyle -m disabled-on "any" } \ + || ({ -ftb-zstyle -m disabled-on "files" } && [[ -n $isfile ]]); then + builtin compadd "$@" + return + fi + + # store matches in $__hits and descriptions in $__dscr + local -a __hits __dscr + if (( $#dscrs == 1 )); then + __dscr=( "${(@P)${(v)dscrs}}" ) + fi + builtin compadd -A __hits -D __dscr "$@" + local ret=$? + if (( $#__hits == 0 )); then + if is-at-least 5.9 && (( $#_mesg != 0 )); then + builtin compadd -x $_mesg + fi + return $ret + fi + + # only store the fist `-X` + expl=$expl[2] + + # keep order of group description + [[ -n $expl ]] && _ftb_groups+=$expl + + # store these values in _ftb_compcap + local -a keys=(apre hpre PREFIX SUFFIX IPREFIX ISUFFIX) + local key expanded __tmp_value=$'<\0>' # placeholder + for key in $keys; do + expanded=${(P)key} + if [[ -n $expanded ]]; then + __tmp_value+=$'\0'$key$'\0'$expanded + fi + done + if [[ -n $expl ]]; then + # store group index + __tmp_value+=$'\0group\0'$_ftb_groups[(ie)$expl] + fi + if [[ -n $isfile ]]; then + # NOTE: need a extra ${} here or ~ expansion won't work + __tmp_value+=$'\0realdir\0'${${(Qe)~${:-$IPREFIX$hpre}}} + fi + _opts+=("${(@kv)apre}" "${(@kv)hpre}" $isfile) + __tmp_value+=$'\0args\0'${(pj:\1:)_opts} + + if (( $+builtins[fzf-tab-compcap-generate] )); then + fzf-tab-compcap-generate __hits __dscr __tmp_value + else + # dscr - the string to show to users + # word - the string to be inserted + local dscr word i + for i in {1..$#__hits}; do + word=$__hits[i] dscr=$__dscr[i] + if [[ -n $dscr ]]; then + dscr=${dscr//$'\n'} + elif [[ -n $word ]]; then + dscr=$word + fi + _ftb_compcap+=$dscr$'\2'$__tmp_value$'\0word\0'$word + done + fi + + # tell zsh that the match is successful + builtin compadd -U -qS '' -R -ftb-remove-space '' +} + +# when insert multi results, a whitespace will be added to each result +# remove left space of our fake result because I can't remove right space +# FIXME: what if the left char is not whitespace: `echo $widgets[\t` +-ftb-remove-space() { + [[ $LBUFFER[-1] == ' ' ]] && LBUFFER[-1]='' +} + +-ftb-zstyle() { + zstyle $1 ":fzf-tab:$_ftb_curcontext" ${@:2} +} + +-ftb-complete() { + local -a _ftb_compcap + local -Ua _ftb_groups + local choice choices _ftb_curcontext continuous_trigger print_query accept_line bs=$'\2' nul=$'\0' + local ret=0 + + # must run with user options; don't move `emulate -L zsh` above this line + (( $+builtins[fzf-tab-compcap-generate] )) && fzf-tab-compcap-generate -i + COLUMNS=500 _ftb__main_complete "$@" || ret=$? + (( $+builtins[fzf-tab-compcap-generate] )) && fzf-tab-compcap-generate -o + + emulate -L zsh -o extended_glob + + local _ftb_query _ftb_complist=() _ftb_headers=() command opts + -ftb-generate-complist # sets `_ftb_complist` + + -ftb-zstyle -s continuous-trigger continuous_trigger || { + [[ $OSTYPE == msys ]] && continuous_trigger=// || continuous_trigger=/ + } + + case $#_ftb_complist in + 0) return 1;; + 1) + choices=("EXPECT_KEY" "${_ftb_compcap[1]%$bs*}") + if (( _ftb_continue_last )); then + choices[1]=$continuous_trigger + fi + ;; + *) + -ftb-generate-query # sets `_ftb_query` + -ftb-generate-header # sets `_ftb_headers` + -ftb-zstyle -s print-query print_query || print_query=alt-enter + -ftb-zstyle -s accept-line accept_line + + choices=("${(@f)"$(builtin print -rl -- $_ftb_headers $_ftb_complist | -ftb-fzf)"}") + ret=$? + # choices=(query_string expect_key returned_word) + + # insert query string directly + if [[ $choices[2] == $print_query ]] || [[ -n $choices[1] && $#choices == 1 ]] ; then + local -A v=("${(@0)${_ftb_compcap[1]}}") + local -a args=("${(@ps:\1:)v[args]}") + [[ -z $args[1] ]] && args=() # don't pass an empty string + IPREFIX=$v[IPREFIX] PREFIX=$v[PREFIX] SUFFIX=$v[SUFFIX] ISUFFIX=$v[ISUFFIX] + # NOTE: should I use `-U` here?, ../f\tabcd -> ../abcd + builtin compadd "${args[@]:--Q}" -Q -- $choices[1] + + compstate[list]= + compstate[insert]= + if (( $#choices[1] > 0 )); then + compstate[insert]='2' + [[ $RBUFFER == ' '* ]] || compstate[insert]+=' ' + fi + return $ret + fi + choices[1]=() + + choices=("${(@)${(@)choices%$nul*}#*$nul}") + + unset CTXT + ;; + esac + + if [[ -n $choices[1] && $choices[1] == $continuous_trigger ]]; then + typeset -gi _ftb_continue=1 + typeset -gi _ftb_continue_last=1 + fi + + if [[ -n $choices[1] && $choices[1] == $accept_line ]]; then + typeset -gi _ftb_accept=1 + fi + choices[1]=() + + for choice in "$choices[@]"; do + local -A v=("${(@0)${_ftb_compcap[(r)${(b)choice}$bs*]#*$bs}}") + local -a args=("${(@ps:\1:)v[args]}") + [[ -z $args[1] ]] && args=() # don't pass an empty string + IPREFIX=$v[IPREFIX] PREFIX=$v[PREFIX] SUFFIX=$v[SUFFIX] ISUFFIX=$v[ISUFFIX] + builtin compadd "${args[@]:--Q}" -Q -- "$v[word]" + done + + compstate[list]= + compstate[insert]= + if (( $#choices == 1 )); then + compstate[insert]='2' + [[ $RBUFFER == ' '* ]] || compstate[insert]+=' ' + elif (( $#choices > 1 )); then + compstate[insert]='all' + fi + return $ret +} + +fzf-tab-debug() { + (( $+_ftb_debug_cnt )) || typeset -gi _ftb_debug_cnt + local tmp=${TMPPREFIX:-/tmp/zsh}-$$-fzf-tab-$(( ++_ftb_debug_cnt )).log + local -i debug_fd=-1 IN_FZF_TAB=1 + { + exec {debug_fd}>&2 2>| $tmp + local -a debug_indent; debug_indent=( '%'{3..20}'(e. .)' ) + local PROMPT4 PS4="${(j::)debug_indent}+%N:%i> " + setopt xtrace + : $ZSH_NAME $ZSH_VERSION + zle .fzf-tab-orig-$_ftb_orig_widget + unsetopt xtrace + if (( debug_fd != -1 )); then + zle -M "fzf-tab-debug: Trace output left in $tmp" + fi + } always { + (( debug_fd != -1 )) && exec 2>&$debug_fd {debug_fd}>&- + } +} + +fzf-tab-complete() { + # this name must be ugly to avoid clashes + local -i _ftb_continue=1 _ftb_continue_last=0 _ftb_accept=0 ret=0 + # hide the cursor until finishing completion, so that users won't see cursor up and down + # NOTE: MacOS Terminal doesn't support civis & cnorm + echoti civis >/dev/tty 2>/dev/null + while (( _ftb_continue )); do + _ftb_continue=0 + local IN_FZF_TAB=1 + { + zle .fzf-tab-orig-$_ftb_orig_widget + ret=$? + } always { + IN_FZF_TAB=0 + } + if (( _ftb_continue )); then + zle .split-undo + zle .reset-prompt + zle -R + zle fzf-tab-dummy + fi + done + echoti cnorm >/dev/tty 2>/dev/null + zle .redisplay + (( _ftb_accept )) && zle .accept-line + return $ret +} + +# this function does nothing, it is used to be wrapped by other plugins like f-sy-h. +# this make it possible to call the wrapper function without causing any other side effects. +fzf-tab-dummy() { } + +zle -N fzf-tab-debug +zle -N fzf-tab-complete +zle -N fzf-tab-dummy + +disable-fzf-tab() { + emulate -L zsh -o extended_glob + (( $+_ftb_orig_widget )) || return 0 + + bindkey '^I' $_ftb_orig_widget + case $_ftb_orig_list_grouped in + 0) zstyle ':completion:*' list-grouped false ;; + 1) zstyle ':completion:*' list-grouped true ;; + 2) zstyle -d ':completion:*' list-grouped ;; + esac + unset _ftb_orig_widget _ftb_orig_list_groupded + + # unhook compadd so that _approximate can work properply + unfunction compadd 2>/dev/null + + functions[_main_complete]=$functions[_ftb__main_complete] + functions[_approximate]=$functions[_ftb__approximate] + + # Don't remove .fzf-tab-orig-$_ftb_orig_widget as we won't be able to reliably + # create it if enable-fzf-tab is called again. +} + +enable-fzf-tab() { + emulate -L zsh -o extended_glob + (( ! $+_ftb_orig_widget )) || disable-fzf-tab + + typeset -g _ftb_orig_widget="${${$(builtin bindkey '^I')##* }:-expand-or-complete}" + if (( ! $+widgets[.fzf-tab-orig-$_ftb_orig_widget] )); then + # Widgets that get replaced by compinit. + local compinit_widgets=( + complete-word + delete-char-or-list + expand-or-complete + expand-or-complete-prefix + list-choices + menu-complete + menu-expand-or-complete + reverse-menu-complete + ) + # Note: We prefix the name of the widget with '.' so that it doesn't get wrapped. + if [[ $widgets[$_ftb_orig_widget] == builtin && + $compinit_widgets[(Ie)$_ftb_orig_widget] != 0 ]]; then + # We are initializing before compinit and being asked to fall back to a completion + # widget that isn't defined yet. Create our own copy of the widget ahead of time. + zle -C .fzf-tab-orig-$_ftb_orig_widget .$_ftb_orig_widget _main_complete + else + # Copy the widget before it's wrapped by zsh-autosuggestions and zsh-syntax-highlighting. + zle -A $_ftb_orig_widget .fzf-tab-orig-$_ftb_orig_widget + fi + fi + + zstyle -t ':completion:*' list-grouped false + typeset -g _ftb_orig_list_grouped=$? + + zstyle ':completion:*' list-grouped false + bindkey -M emacs '^I' fzf-tab-complete + bindkey -M viins '^I' fzf-tab-complete + bindkey -M emacs '^X.' fzf-tab-debug + bindkey -M viins '^X.' fzf-tab-debug + + # make sure we can copy them + autoload +X -Uz _main_complete _approximate + + # hook compadd + functions[compadd]=$functions[-ftb-compadd] + + # hook _main_complete to trigger fzf-tab + functions[_ftb__main_complete]=$functions[_main_complete] + function _main_complete() { -ftb-complete "$@" } + + # TODO: This is not a full support, see #47 + # _approximate will also hook compadd + # let it call -ftb-compadd instead of builtin compadd so that fzf-tab can capture result + # make sure _approximate has been loaded. + functions[_ftb__approximate]=$functions[_approximate] + function _approximate() { + # if not called by fzf-tab, don't do anything with compadd + (( ! IN_FZF_TAB )) || unfunction compadd + _ftb__approximate + (( ! IN_FZF_TAB )) || functions[compadd]=$functions[-ftb-compadd] + } +} + +toggle-fzf-tab() { + emulate -L zsh -o extended_glob + if (( $+_ftb_orig_widget )); then + disable-fzf-tab + else + enable-fzf-tab + fi +} + +build-fzf-tab-module() { + local use_bundle + local NPROC + if [[ ${OSTYPE} == darwin* ]]; then + [[ -n ${module_path[1]}/**/*.bundle(#qN) ]] && use_bundle=true + NPROC=$(sysctl -n hw.logicalcpu) + else + NPROC=$(nproc) + fi + pushd $FZF_TAB_HOME/modules + CPPFLAGS=-I/usr/local/include CFLAGS="-g -Wall -O2 -std=c99" LDFLAGS=-L/usr/local/lib ./configure --disable-gdbm --without-tcsetpgrp ${use_bundle:+DL_EXT=bundle} + make -j${NPROC} + local ret=$? + popd + if (( ${ret} != 0 )); then + print -P "%F{red}%BThe module building has failed. See the output above for details.%f%b" >&2 + else + print -P "%F{green}%BThe module has been built successfully.%f%b" + fi +} + +zmodload zsh/zutil +zmodload zsh/mapfile +zmodload -F zsh/stat b:zstat + +0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}" +0="${${(M)0:#/*}:-$PWD/$0}" +FZF_TAB_HOME="${0:A:h}" + +source "$FZF_TAB_HOME"/lib/zsh-ls-colors/ls-colors.zsh fzf-tab-lscolors + +typeset -ga _ftb_group_colors=( + $'\x1b[94m' $'\x1b[32m' $'\x1b[33m' $'\x1b[35m' $'\x1b[31m' $'\x1b[38;5;27m' $'\x1b[36m' + $'\x1b[38;5;100m' $'\x1b[38;5;98m' $'\x1b[91m' $'\x1b[38;5;80m' $'\x1b[92m' + $'\x1b[38;5;214m' $'\x1b[38;5;165m' $'\x1b[38;5;124m' $'\x1b[38;5;120m' +) + +# init +() { + emulate -L zsh -o extended_glob + + if (( ! $fpath[(I)$FZF_TAB_HOME/lib] )); then + fpath+=($FZF_TAB_HOME/lib) + fi + + autoload -Uz is-at-least -- $FZF_TAB_HOME/lib/-#ftb*(:t) + + if (( $+FZF_TAB_COMMAND || $+FZF_TAB_OPTS || $+FZF_TAB_QUERY || $+FZF_TAB_SINGLE_GROUP || $+fzf_tab_preview_init )) \ + || zstyle -m ":fzf-tab:*" command '*' \ + || zstyle -m ":fzf-tab:*" extra-opts '*'; then + print -P "%F{red}%B[fzf-tab] Sorry, your configuration is not supported anymore\n" \ + "See https://github.com/Aloxaf/fzf-tab/pull/132 for more information%f%b" + fi + + if [[ -n $FZF_TAB_HOME/modules/Src/aloxaf/fzftab.(so|bundle)(#qN) ]]; then + module_path+=("$FZF_TAB_HOME/modules/Src") + zmodload aloxaf/fzftab + + if [[ $FZF_TAB_MODULE_VERSION != "0.2.2" ]]; then + zmodload -u aloxaf/fzftab + local rebuild + print -Pn "%F{yellow}fzftab module needs to be rebuild, rebuild now?[Y/n]:%f" + read -q rebuild + if [[ $rebuild == y ]]; then + build-fzf-tab-module + zmodload aloxaf/fzftab + fi + fi + fi +} + +enable-fzf-tab +zle -N toggle-fzf-tab + +# restore options +(( ${#_ftb_opts} )) && setopt ${_ftb_opts[@]} +'builtin' 'unset' '_ftb_opts' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-colorize b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-colorize new file mode 100644 index 00000000..3b1909bd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-colorize @@ -0,0 +1,34 @@ +#!/hint/zsh +emulate -L zsh -o cbases -o octalzeroes + +local REPLY +local -a reply stat lstat + +# fzf-tab-lscolors::match-by $1 lstat follow +zstat -A lstat -L -- $1 +# follow symlink +(( lstat[3] & 0170000 )) && zstat -A stat -- $1 2>/dev/null + +fzf-tab-lscolors::from-mode "$1" "$lstat[3]" $stat[3] +# fall back to name +[[ -z $REPLY ]] && fzf-tab-lscolors::from-name $1 + +# If this is a symlink +if [[ -n $lstat[14] ]]; then + local sym_color=$REPLY + local rsv_color=$REPLY + local rsv=$lstat[14] + # If this is not a broken symlink + if [[ -e $rsv ]]; then + # fzf-tab-lscolors::match-by $rsv stat + zstat -A stat -- $rsv + fzf-tab-lscolors::from-mode $rsv $stat[3] + # fall back to name + [[ -z $REPLY ]] && fzf-tab-lscolors::from-name $rsv + rsv_color=$REPLY + fi + dpre=$'\033[0m\033['$sym_color'm' + dsuf+=$'\033[0m -> \033['$rsv_color'm'$rsv +else + dpre=$'\033[0m\033['$REPLY'm' +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-fzf b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-fzf new file mode 100755 index 00000000..2cb42282 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-fzf @@ -0,0 +1,108 @@ +#!/hint/zsh + +# import math functions +autoload -Uz zmathfunc +zmathfunc + +local tmp_dir=${TMPPREFIX:-/tmp/zsh}-fzf-tab-$USER +[[ -d $tmp_dir ]] || command mkdir $tmp_dir + +local ftb_preview_init=" +zmodload zsh/mapfile +local -a _ftb_compcap=(\"\${(@f)mapfile[$tmp_dir/compcap.$$]}\") +local -a _ftb_groups=(\"\${(@f)mapfile[$tmp_dir/groups.$$]}\") +local bs=\$'\2' +# get description +export desc=\${\${\"\$(<{f})\"%\$'\0'*}#*\$'\0'} +# get ctxt for current completion +local -A ctxt=(\"\${(@0)\${_ftb_compcap[(r)\${(b)desc}\$bs*]#*\$bs}}\") +# get group +if (( \$+ctxt[group] )); then + export group=\$_ftb_groups[\$ctxt[group]] +fi +# get original word +export word=\${(Q)ctxt[word]} +# get real path if it is file +if (( \$+ctxt[realdir] )); then + export realpath=\${ctxt[realdir]}\$word +fi +$(typeset -p words) +" +local binds=tab:down,btab:up,change:top,ctrl-space:toggle,bspace:backward-delete-char/eof,ctrl-h:backward-delete-char/eof +local fzf_command fzf_flags fzf_preview debug_command tmp switch_group fzf_pad fzf_min_height +local ret=0 + +-ftb-zstyle -s fzf-command fzf_command || fzf_command=fzf +-ftb-zstyle -a fzf-bindings tmp && binds+=,${(j:,:)tmp} +-ftb-zstyle -a fzf-flags fzf_flags +-ftb-zstyle -s fzf-preview fzf_preview +-ftb-zstyle -a switch-group switch_group || switch_group=(F1 F2) +-ftb-zstyle -s fzf-pad fzf_pad || fzf_pad=2 +-ftb-zstyle -s fzf-min-height fzf_min_height || fzf_min_height=0 + +-ftb-zstyle -a debug-command debug_command && { + ${(eX)debug_command} $fzf_flags + return +} + +print -rl -- $_ftb_compcap > $tmp_dir/compcap.$$ +print -rl -- $_ftb_groups > $tmp_dir/groups.$$ +print -r -- ${ftb_preview_init/{f}/\$1} > $tmp_dir/ftb_preview_init.$$ + +binds=${binds//{_FTB_INIT_}/. $tmp_dir/ftb_preview_init.$$ {f} $'\n'} + +local -i header_lines=$#_ftb_headers +local -i lines=$(( $#_ftb_compcap + fzf_pad + header_lines )) +local reload_command="$commands[zsh] -f $FZF_TAB_HOME/lib/ftb-switch-group $$ $header_lines $tmp_dir" + +# detect if we will use tmux popup +local use_tmux_popup=0 +if [[ $fzf_command == "ftb-tmux-popup" ]]; then + use_tmux_popup=1 +fi + +if (( ! use_tmux_popup )); then + # fzf will cause the current line to refresh, so move the cursor down. + echoti cud1 >/dev/tty + # reset cursor before call fzf + echoti cnorm >/dev/tty 2>/dev/null +fi + +cat > $tmp_dir/completions.$$ + +local dd='gdd' +if (( ${+commands[$dd]} == 0 )) ; then + dd='dd' +fi +if (( ${+commands[$dd]} == 0 )) ; then + dd='true' # nop if dd is not installed +fi + +_ftb_query="${_ftb_query}$(command "$dd" bs=1G count=1 status=none iflag=nonblock < /dev/tty 2>/dev/null)" || true + +SHELL=$ZSH_NAME $fzf_command \ + --ansi \ + --bind=$binds \ + --bind="${switch_group[1]}:reload($reload_command -1),${switch_group[2]}:reload($reload_command 1)" \ + --color=hl:$(( header_lines == 0 ? 188 : 255 )) \ + --cycle \ + --delimiter='\x00' \ + --expect=$continuous_trigger,$print_query,$accept_line \ + --header-lines=$header_lines \ + --height=${FZF_TMUX_HEIGHT:=$(( min(max(lines, fzf_min_height), LINES / 3 * 2) ))} \ + --layout=reverse \ + --multi \ + --nth=2,3 \ + --print-query \ + --query=$_ftb_query \ + --tiebreak=begin \ + ${fzf_preview:+--preview=${ftb_preview_init/{f}/'{f}'}$fzf_preview} \ + $fzf_flags < $tmp_dir/completions.$$ || ret=$? + +if (( ! use_tmux_popup )); then + echoti civis >/dev/tty 2>/dev/null + echoti cuu1 >/dev/tty +fi + +command rm $tmp_dir/*.$$ 2>/dev/null +return $ret diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-generate-complist b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-generate-complist new file mode 100644 index 00000000..42dd0339 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-generate-complist @@ -0,0 +1,113 @@ +#!/hint/zsh + +local dsuf dpre k _v filepath first_word show_group default_color prefix bs=$'\b' +local -a list_colors group_colors tcandidates reply match mbegin mend +local -i same_word=1 colorful=0 +local -Ua duplicate_groups=() +local -A word_map=() + +(( $#_ftb_compcap == 0 )) && return + +-ftb-zstyle -s show-group show_group || show_group=full +-ftb-zstyle -s default-color default_color || default_color=$'\x1b[37m' +-ftb-zstyle -s prefix prefix || { + zstyle -m ':completion:*:descriptions' format '*' && prefix='·' +} +-ftb-zstyle -a group-colors group_colors || group_colors=($_ftb_group_colors) +zstyle -a ":completion:$_ftb_curcontext" list-colors list_colors + +# init colorize +if (( $+builtins[fzf-tab-candidates-generate] )); then + fzf-tab-candidates-generate -i list_colors +else + local -A namecolors=(${(@s:=:)${(@s.:.)list_colors}:#[[:alpha:]][[:alpha:]]=*}) + local -A modecolors=(${(@Ms:=:)${(@s.:.)list_colors}:#[[:alpha:]][[:alpha:]]=*}) + (( $#namecolors == 0 && $#modecolors == 0 )) && list_colors=() +fi + +if (( $#_ftb_groups == 1 )); then + -ftb-zstyle -m single-group prefix || prefix='' + -ftb-zstyle -m single-group color || group_colors=("$default_color") +fi + +if (( $+builtins[fzf-tab-candidates-generate] )); then + fzf-tab-candidates-generate +else + for k _v in "${(@ps:\2:)_ftb_compcap}"; do + local -A v=("${(@0)_v}") + [[ $v[word] == ${first_word:=$v[word]} ]] || same_word=0 + + # add character and color to describe the type of the files + dsuf='' dpre='' + if (( $+v[realdir] )); then + filepath=$v[realdir]${(Q)v[word]} + if [[ -d $filepath ]]; then + dsuf=/ + fi + # add color and resolve symlink if have list-colors + # detail: http://zsh.sourceforge.net/Doc/Release/Zsh-Modules.html#The-zsh_002fcomplist-Module + if (( $#list_colors )) && [[ -a $filepath || -L $filepath ]]; then + -ftb-colorize $filepath + colorful=1 + elif [[ -L $filepath ]]; then + dsuf=@ + fi + if [[ $options[list_types] == off ]]; then + dsuf='' + fi + fi + + # add color to description if they have group index + if (( $+v[group] )); then + local color=$group_colors[$v[group]] + # add a hidden group index at start of string to keep group order when sorting + # first group index is for builtin sort, sencond is for GNU sort + tcandidates+=$v[group]$'\b'$color$prefix$dpre$'\0'$v[group]$'\b'$k$'\0'$dsuf + else + tcandidates+=$default_color$dpre$'\0'$k$'\0'$dsuf + fi + + # check group with duplicate member + if [[ $show_group == brief ]]; then + if (( $+word_map[$v[word]] && $+v[group] )); then + duplicate_groups+=$v[group] # add this group + duplicate_groups+=$word_map[$v[word]] # add previous group + fi + word_map[$v[word]]=$v[group] + fi + done +fi + +(( same_word )) && tcandidates[2,-1]=() + +# sort and remove sort group or other index +zstyle -T ":completion:$_ftb_curcontext" sort +if (( $? != 1 )); then + if (( colorful )); then + # if enable list_colors, we should skip the first field + if [[ ${commands[sort]:A:t} != (|busybox*) ]]; then + # this is faster but doesn't work if `find` is from busybox + tcandidates=(${(f)"$(command sort -u -t '\0' -k 2 <<< ${(pj:\n:)tcandidates})"}) + else + # slower but portable + tcandidates=(${(@o)${(@)tcandidates:/(#b)([^$'\0']#)$'\0'(*)/$match[2]$'\0'$match[1]}}) + tcandidates=(${(@)tcandidates/(#b)(*)$'\0'([^$'\0']#)/$match[2]$'\0'$match[1]}) + fi + else + tcandidates=("${(@o)tcandidates}") + fi +fi +typeset -gUa _ftb_complist=("${(@)tcandidates//[0-9]#$bs}") + +# hide needless group +if (( $#_ftb_groups )); then + local i to_hide indexs=({1..$#_ftb_groups}) + case $show_group in + brief) to_hide=(${indexs:|duplicate_groups}) ;; + none) to_hide=($indexs) ;; + esac + for i in $to_hide; do + # NOTE: _ftb_groups is unique array + _ftb_groups[i]="__hide__$i" + done +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-generate-header b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-generate-header new file mode 100644 index 00000000..a54fee12 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-generate-header @@ -0,0 +1,35 @@ +#!/hint/zsh + +typeset -ga _ftb_headers=() +local i tmp group_colors +local -i mlen=0 len=0 + +if (( $#_ftb_groups == 1 )) && { ! -ftb-zstyle -m single-group "header" }; then + return +fi + +# calculate the max column width +for i in $_ftb_groups; do + (( $#i > mlen )) && mlen=$#i +done +mlen+=1 + +-ftb-zstyle -a group-colors group_colors || group_colors=($_ftb_group_colors) + +for (( i=1; i<=$#_ftb_groups; i++ )); do + [[ $_ftb_groups[i] == "__hide__"* ]] && continue + + if (( len + $#_ftb_groups[i] > COLUMNS - 5 )); then + _ftb_headers+=$tmp + tmp='' && len=0 + fi + if (( len + mlen > COLUMNS - 5 )); then + # the last column doesn't need padding + _ftb_headers+=$tmp$group_colors[i]$_ftb_groups[i]$'\033[00m' + tmp='' && len=0 + else + tmp+=$group_colors[i]${(r:$mlen:)_ftb_groups[i]}$'\033[00m' + len+=$mlen + fi +done +(( $#tmp )) && _ftb_headers+=$tmp diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-generate-query b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-generate-query new file mode 100644 index 00000000..4f546049 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/-ftb-generate-query @@ -0,0 +1,40 @@ +#!/hint/zsh + +if zmodload -s zsh/pcre; then + setopt localoptions rematch_pcre +fi + +local key qtype tmp query_string +typeset -g _ftb_query= +-ftb-zstyle -a query-string query_string || query_string=(prefix input first) +for qtype in $query_string; do + if [[ $qtype == prefix ]]; then + # find the longest common prefix among descriptions + local -a keys=(${_ftb_compcap%$'\2'*}) + tmp=$keys[1] + local MATCH match mbegin mend prefix=(${(s::)tmp}) + for key in ${keys:1}; do + (( $#tmp )) || break + [[ $key == $tmp* ]] && continue + # interpose characters from the current common prefix and $key and see how + # many pairs of equal characters we get at the start of the resulting string + [[ ${(j::)${${(s::)key[1,$#tmp]}:^prefix}} =~ '^(((.)\3)*)' ]] + # truncate common prefix and maintain loop invariant: ${(s::)tmp} == $prefix + tmp[$#MATCH/2+1,-1]="" + prefix[$#MATCH/2+1,-1]=() + done + elif [[ $qtype == input ]]; then + local fv=${_ftb_compcap[1]#*$'\2'} + local -A v=("${(@0)fv}") + tmp=$v[PREFIX] + if (( $RBUFFER[(i)$v[SUFFIX]] != 1 )); then + tmp=${tmp/%$v[SUFFIX]} + fi + tmp=${${tmp#$v[hpre]}#$v[apre]} + fi + if (( $query_string[(I)longest] )); then + (( $#tmp > $#_ftb_query )) && _ftb_query=$tmp + elif [[ -n $tmp ]]; then + _ftb_query=$tmp && break + fi +done diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/ftb-switch-group b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/ftb-switch-group new file mode 100644 index 00000000..8d069567 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/ftb-switch-group @@ -0,0 +1,38 @@ +#!/hint/zsh +emulate -L zsh -o extended_glob + +zmodload zsh/mapfile + +# receive arguments +local pid=$1 header_lines=$2 tmp_dir=$3 offset=$@[-1] + +# read completion list +local -a list=(${(f)mapfile[$tmp_dir/completions.$pid]}) + +# get total group count +if (( $#list > 10000 )); then + local -Ua total=(${(f)"$(print -l ${list:$header_lines} | grep -a -oP '^\x1b\[[0-9;]*m')"}) +else + local -Ua total=(${(M)${list:$header_lines}#$'\x1b['[0-9;]#*m}) +fi + +# get current group index, start from 2 +local current=2 +if [[ -f $tmp_dir/current-group.$pid ]]; then + current=$(( $(<$tmp_dir/current-group.$pid) + offset )) +fi +(( current > $#total )) && current=1 +(( current == 0 )) && current=$#total +echo $current > $tmp_dir/current-group.$pid + +# print headers +if (( header_lines != 0 )); then + print -l ${list[1,header_lines]/${total[current]}/$'\x1b[1m'} +fi + +# print current group +if (( $#list > 10000 )); then + print -l ${list:$header_lines} | grep -a -F "${total[current]}" +else + print -l ${(M)${list:$header_lines}:#${total[current]}*} +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/ftb-tmux-popup b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/ftb-tmux-popup new file mode 100755 index 00000000..a1101aa2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/ftb-tmux-popup @@ -0,0 +1,99 @@ +#!/hint/zsh +# Show results with tmux popup +# Example usage: +# zstyle ':fzf-tab:*' fzf-command ftb-tmux-popup +# zstyle ':fzf-tab:*' popup-pad 0 0 +# It can also be used as a standalone tool, like: +# ls | ftb-tmux-popup +emulate -L zsh -o extended_glob + +# import math functions (only if they're not already defined) +if (( ! $+functions[zsh_math_func_min] )); then + autoload -Uz zmathfunc + zmathfunc +fi + +: ${tmp_dir:=${TMPPREFIX:-/tmp/zsh}-fzf-tab-$USER} + +# fallback to fzf if it is not running in tmux +if (( ! $+TMUX_PANE )); then + fzf $@ + return +fi + +local ret=0 + +local -a fzf_opts=($@) +fzf_opts=(${${fzf_opts/--height*}/--layout*}) + +# get position of cursor and size of window +local -a tmp=($(command tmux display-message -p "#{pane_top} #{cursor_y} #{pane_left} #{cursor_x} #{window_height} #{window_width} #{status} #{status-position}")) +local cursor_y=$((tmp[1] + tmp[2])) cursor_x=$((tmp[3] + tmp[4])) window_height=$tmp[5] window_width=$tmp[6] window_top=0 + +if [[ $tmp[8] == 'top' ]]; then + window_top=$tmp[7] + cursor_y=$((cursor_y + window_top)) +fi + +# if not called by fzf-tab +if (( ! $+IN_FZF_TAB )); then + [[ -d $tmp_dir ]] || mkdir -p $tmp_dir + cat > $tmp_dir/completions.$$ +fi + +local text REPLY comp_lines comp_length length popup_pad popup_min_size + +zstyle -a ":fzf-tab:$_ftb_curcontext" popup-pad popup_pad || popup_pad=(0 0) +zstyle -a ":fzf-tab:$_ftb_curcontext" popup-min-size popup_min_size || popup_min_size=(0 0) + +# get the size of content, note we should remove all ANSI color code +comp_lines=$(( ${#${(f)mapfile[$tmp_dir/completions.$$]}} + $popup_pad[2] )) +if (( comp_lines <= 500 )); then + comp_length=0 + for line in ${(f)mapfile[$tmp_dir/completions.$$]}; do + length=${(m)#${(S)line//$'\x1b['[0-9]#*m}} + (( length >= comp_length )) && comp_length=$length + done +else + # FIXME: can't get the correct width of CJK characters. + comp_length=$( command perl -ne 's/\x1b\[[0-9;]*m//g;s/\x00//g; $m= length() if $m < length(); END { print $m }' < $tmp_dir/completions.$$ ) +fi +comp_length=$(( comp_length + $popup_pad[1] )) + +local popup_height popup_y popup_width popup_x adjust_height + +# adjust the popup height if the fzf finder info style is not default +if (( $fzf_opts[(I)--info=*(hidden|inline)*] > 0 )); then + adjust_height=-1 +fi + +# calculate the popup height and y position +if (( cursor_y * 2 > window_height )); then + # show above the cursor + popup_height=$(( min(max(comp_lines + 4, popup_min_size[2]), cursor_y - window_top) + adjust_height )) + popup_y=$cursor_y + if zstyle -T ":fzf-tab:$_ftb_curcontext" popup-smart-tab; then + fzf_opts+=(--bind=tab:up,btab:down) + fi +else + # show below the cursor + popup_height=$(( min(max(comp_lines + 4, popup_min_size[2]), window_height - cursor_y + window_top - 1) + adjust_height )) + popup_y=$(( cursor_y + popup_height + 1 )) + fzf_opts+=(--layout=reverse) +fi + +# calculate the popup width and x position +popup_width=$(( min(max(comp_length + 5, popup_min_size[1]), window_width) )) +popup_x=$(( cursor_x + popup_width > window_width ? window_width - popup_width : cursor_x )) + +echo -E "$commands[fzf] ${(qq)fzf_opts[@]} < $tmp_dir/completions.$$ > $tmp_dir/result-$$" > $tmp_dir/fzf-$$ +{ + tmux popup -x $popup_x -y $popup_y \ + -w $popup_width -h $popup_height \ + -d $PWD -E ". $tmp_dir/fzf-$$" || ret=$? + echo -E "$(<$tmp_dir/result-$$)" +} always { + command rm $tmp_dir/*-$$ + (( $+IN_FZF_TAB )) || command rm $tmp_dir/completions.$$ +} +return $ret diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/zsh-ls-colors/LICENSE b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/zsh-ls-colors/LICENSE new file mode 100644 index 00000000..940b4c2b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/zsh-ls-colors/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2019 Gamma + +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. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/zsh-ls-colors/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/zsh-ls-colors/README.md new file mode 100644 index 00000000..7736ce66 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/zsh-ls-colors/README.md @@ -0,0 +1,114 @@ +# zsh-ls-colors + +![Demo screenshot](https://raw.githubusercontent.com/xPMo/zsh-ls-colors/image/demo.png) + +A zsh library to use `LS_COLORS` in scripts or other plugins. + +For a simple demo, see the `demo` script in this repo. + +For more advanced usage, +instructions are located at top of the source files for `from-mode` and `from-name`. +If a use case isn't adequately covered, +please open an issue! + +## Using zsh-ls-colors in a plugin + +You can use this as a submodule or a subtree. + +### submodule: + +```sh +# Add (only once) +git submodule add git://github.com/xPMo/zsh-ls-colors.git ls-colors +git commit -m 'Add ls-colors as submodule' + +# Update +cd ls-colors +git fetch +git checkout origin/master +cd .. +git commit ls-colors -m 'Update ls-colors to latest' +``` + +### Subtree: + +```sh +# Initial add +git subtree add --prefix=ls-colors/ --squash -m 'Add ls-colors as a subtree' \ + git://github.com/xPMo/zsh-ls-colors.git master + +# Update +git subtree pull --prefix=ls-colors/ --squash -m 'Update ls-colors to latest' \ + git://github.com/xPMo/zsh-ls-colors.git master + + +# Or, after adding a remote: +git remote add ls-colors git://github.com/xPMo/zsh-ls-colors.git + +# Initial add +git subtree add --prefix=ls-colors/ --squash -m 'Add ls-colors as a subtree' ls-colors master + +# Update +git subtree pull --prefix=ls-colors/ --squash -m 'Update ls-colors to latest' ls-colors master +``` + +### Function namespacing + +Since functions are a public namespace, +this plugin allows you to customize the preifix for your plugin: + +```zsh +# load functions as my-lscolors::{init,match-by,from-name,from-mode} +source ${0:h}/ls-colors/ls-colors.zsh my-lscolors +``` + +### Parameter namespacing + +While indirect parameter expansion exists with `${(P)var}`, +it doesn't play nicely with array parameters. + +There are multiple strategies to prevent unnecessary re-parsing: + +```zsh +# Call once when loading. +# Pollutes global namespace but prevents re-parsing +ls-color::init +``` + +```zsh +# Don't call init at all and only use ::match-by. +# Doesn't pollute global namespace but reparses LS_COLORS on every call +ls-color::match-by $file lstat +``` + +```zsh +# Initialize within a scope with local parameters. +# Best for not polluting global namespace when multiple filenames need to be parsed. +(){ + local -A namecolors modecolors + ls-color::init + + for arg; do + ... + done +} +``` + +```zsh +# Serialize: +typeset -g LS_COLORS_CACHE_FILE=$(mktemp) +(){ + local -A namecolors modecolors + ls-color::init + typeset -p modecolors namecolors >| $LS_COLORS_CACHE_FILE + zcompile $LS_COLORS_CACHE_FILE +} + +my-function(){ + local -A namecolors modecolors + source $LS_COLORS_CACHE_FILE + + ... +} +``` + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/zsh-ls-colors/demo b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/zsh-ls-colors/demo new file mode 100755 index 00000000..a5e468d2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/zsh-ls-colors/demo @@ -0,0 +1,65 @@ +#!/usr/bin/env zsh +# set $0 (ref: zdharma.org/Zsh-100-Commits-Club/Zsh-Plugin-Standard.html#zero-handling) +0="${${ZERO:-${0:#$ZSH_ARGZERO}}:-${(%):-%N}}" +0="${${(M)0:#/*}:-$PWD/$0}" + +# load library functions +source ls-colors.zsh '' + +# to name the functions with a different namespace +# call source with a different argument +#source my-plugin::ls + +# init (sets modecolors and namecolors) +# You have options. Either you can pollute global namespace: +ls-color::init +# Or you can have ::match-by re-parse colors on every call +: # (do nothing) +# Or if you have multiple calls, you can parse colors once for a scope: +(){ + local -A modecolors namecolors + ls-color::init + + for arg; do + ls-color::match-by $arg lstat + : do something else + done +} + + +# colors can also be added for other globs after init as well: +namecolors[*.md]='01' # bold markdown files + +# EXTENDED_GLOB is enabled when matching, so things like this are possible: +namecolors[(#i)(*/|)license(|.*)]='04' # underline LICENSE, or license.txt, or similar + +local file reply +# color each file in the argument list +for file; do + ls-color::match-by $file all + # point to symlink resolution if it exists + print '\e['$reply[1]'m'$file'\e[0m'${reply[2]:+' → \e['$reply[3]'m'$reply[2]'\e[0m'} +done + +# ======================= +# Alternate manual method: +for file; do + ls-color::match-by $file lstat follow + if [[ $reply[2] ]]; then + # This is a symlink + symlink_color=$reply[1] + # If broken, use link color for destination + resolved_color=$reply[1] + resolved=$reply[2] + if [[ -e $file ]]; then + # Not broken, update destination color + ls-color::match-by $file stat + resolved_color=$reply[1] + fi + print '\e['$symlink_color'm'$file'\e[0m → \e['$resolved_color'm'$resolved'\e[0m' + else + # This is not a symlink + print '\e['$reply[1]'m'$file'\e[0m' + fi +done + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/zsh-ls-colors/ls-colors.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/zsh-ls-colors/ls-colors.zsh new file mode 100644 index 00000000..276a7bb7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/lib/zsh-ls-colors/ls-colors.zsh @@ -0,0 +1,186 @@ +#!/usr/bin/env zsh + +# set the prefix for all functions +local pfx=${1:-'ls-color'} + +# {{{ From mode +# Usage: +# $1: filename +# $2: The value of struct stat st_mode +# If empty, modecolors lookup will be skipped +# $3: (If symlink) The value of struct stat st_mode +# for the target of $1's symlink. If unset, +# interpret as a broken link. +# Sets REPLY to the console code +${pfx}::from-mode () { + + emulate -L zsh + setopt cbases octalzeroes extendedglob + + [[ -z $2 ]] && return 1 + + local -i reg=0 + local -a codes + + local -i st_mode=$(($2)) + # See man 7 inode for more info + # file type + case $(( st_mode & 0170000 )) in + $(( 0140000 )) ) codes=( $modecolors[so] ) ;; + $(( 0120000 )) ) # symlink, special handling + if ! (($+3)); then + REPLY=$modecolors[or] + elif [[ $modecolors[ln] = target ]]; then + "$0" "$1" "${@:3}" + else + REPLY=$modecolors[ln] + fi + return + ;; + $(( 0100000 )) ) codes=( ); reg=1 ;; # regular file + $(( 0060000 )) ) codes=( $modecolors[bd] ) ;; + $(( 0040000 )) ) codes=( $modecolors[di] ) ;; + $(( 0020000 )) ) codes=( $modecolors[cd] ) ;; + $(( 0010000 )) ) codes=( $modecolors[pi] ) ;; + esac + + # setuid/setgid/sticky/other-writable + (( st_mode & 04000 )) && codes+=( $modecolors[su] ) + (( st_mode & 02000 )) && codes+=( $modecolors[sg] ) + (( ! reg )) && case $(( st_mode & 01002 )) in + # sticky + $(( 01000 )) ) codes+=( $modecolors[st] ) ;; + # other-writable + $(( 00002 )) ) codes+=( $modecolors[ow] ) ;; + # other-writable and sticky + $(( 01002 )) ) codes+=( $modecolors[tw] ) ;; + esac + + # executable + if (( ! $#codes )); then + (( st_mode & 0111 )) && codes+=( $modecolors[ex] ) + fi + + # return nonzero if no matching code + [[ ${REPLY::=${(j:;:)codes}} ]] +} # }}} +# {{{ From name +# Usage: +# $1: filename +# +# Sets REPLY to the console code +${pfx}::from-name () { + + emulate -L zsh + setopt extendedglob + + # Return non-zero if no keys match + [[ ${REPLY::=$namecolors[(k)$1]} ]] +} # }}} +# {{{ Init +# WARNING: initializes namecolors and modecolors in global scope +${pfx}::init () { + emulate -L zsh + + # Use $1 if provided, otherwise use LS_COLORS + # Use LSCOLORS on BSD + local LS_COLORS=${1:-${LS_COLORS:-$LSCOLORS}} + + # read in LS_COLORS + typeset -gA namecolors=(${(@s:=:)${(@s.:.)LS_COLORS}:#[[:alpha:]][[:alpha:]]=*}) + typeset -gA modecolors=(${(@Ms:=:)${(@s.:.)LS_COLORS}:#[[:alpha:]][[:alpha:]]=*}) +} +# }}} +# {{{ Match by +# Usage: +# $1: filename +# Optional (must be $2): g[lobal]: Use existing stat | lstat in parent scope +# ${@:2}: Append to reply: +# - l[stat] : Look up using lstat (don't follow symlink), if empty match name +# - s[tat] : Look up using stat (do follow symlink), if empty match name +# - n[ame] : Only match name +# - f[ollow]: Get resolution path of symlink +# - L[stat] : Same as above but don't match name +# - S[tat] : Same as above but don't match name +# - a[ll] : If a broken symlink: lstat follow lstat +# : If a symlink : lstat follow stat +# : Otherwise : lstat +# - A[ll] : If a broken symlink: Lstat follow Lstat +# : If a symlink : Lstat follow Stat +# : Otherwise : Lstat +# +# or returns non-zero +${pfx}::match-by () { + emulate -L zsh + setopt extendedglob cbases octalzeroes + + local arg REPLY name=$1 pfx=${0%::match-by} + shift + + # init in local scope if not using global params + if ! [[ -v namecolors && -v modecolors ]]; then + local -A namecolors modecolors + ${pfx}::init + fi + + if [[ ${1:l} = (g|global) ]]; then + shift + else + local -a stat lstat + declare -ga reply=() + fi + + zmodload -F zsh/stat b:zstat + for arg; do + case ${arg[1]:l} in + n|name) + ${pfx}::from-name $name + reply+=("$REPLY") + ;; + l|lstat) + (($#lstat)) || zstat -A lstat -L $name || return 1 + if ((lstat[3] & 0170000 )); then + # follow symlink + (($#stat)) || zstat -A stat $name 2>/dev/null + fi + ${pfx}::from-mode "$name" "$lstat[3]" $stat[3] + if [[ $REPLY || ${2[1]} = L ]]; then + reply+=("$REPLY") + else # fall back to name + "$0" "$name" g n + fi + ;; + s|stat) + (($#stat)) || zstat -A stat $name || return 1 + ${pfx}::from-mode $name $stat[3] + reply+=("$REPLY") + if [[ $REPLY || ${arg[1]} = S ]]; then + reply+=("$REPLY") + else # fall back to name + "$0" "$name" g n + fi + ;; + f|follow) + (($#lstat)) || zstat -A lstat -L $name || return 1 + reply+=("$lstat[14]") + ;; + a|all) + # Match case + "$0" "$name" g ${${${arg[1]%a}:+L}:-l} + # won't append if empty + reply+=($lstat[14]) + # $stat[14] will be empty if not a symlink + if [[ $lstat[14] ]]; then + if [[ -e $name ]]; then + "$0" "$name" g ${${${arg[1]%a}:+S}:-s} + else + reply+=($reply[-2]) + fi + fi + ;; + *) return 2 ;; + esac + done +} +# }}} +# vim: set foldmethod=marker: diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.cvsignore b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.cvsignore new file mode 100644 index 00000000..95cdc587 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.cvsignore @@ -0,0 +1,16 @@ +Makefile +META-FAQ +config.cache +config.h +config.h.in +config.log +config.modules +config.modules.sh +config.status +configure +cscope.out +stamp-h +stamp-h.in +autom4te.cache +*.swp +.git diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.distfiles b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.distfiles new file mode 100644 index 00000000..d618a779 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.distfiles @@ -0,0 +1,4 @@ +DISTFILES_SRC=' + META-FAQ + configure config.h.in stamp-h.in +' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.editorconfig b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.editorconfig new file mode 100644 index 00000000..808512ec --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.editorconfig @@ -0,0 +1,15 @@ +# Top-most editorconfig file + +root = true + +[*] +end_of_line = lf +tab_width = 8 +indent_size = 2 +indent_style = tab + +[ChangeLog] +indent_size = 8 + +[*.[ch]] +indent_size = 4 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.gitignore b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.gitignore new file mode 100644 index 00000000..f4201365 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.gitignore @@ -0,0 +1,155 @@ +Makefile +tags +TAGS +*.o +*.o.c +*.orig +*.a +*.so +*.dll +*~ +.*.sw? +\#* + +/META-FAQ +/config.cache +/config.h +/config.log +/config.modules +/config.modules.sh +/config.status +/config.status.lineno +/cscope.out +/stamp-h +/autom4te.cache + +Config/defs.mk + +CVS +.#* + +Doc/help +Doc/help.txt +Doc/help/[_a-zA-Z0-9]* + +Doc/intro.pdf +Doc/intro.ps +Doc/intro.a4.pdf +Doc/intro.a4.ps +Doc/intro.us.pdf +Doc/intro.us.ps +Doc/version.yo +Doc/texi2html.conf +Doc/zsh*.1 +Doc/zsh.texi +Doc/zsh.info* +Doc/*.html +Doc/zsh.aux +Doc/zsh.toc +Doc/zsh.cp +Doc/zsh.cps +Doc/zsh.fn +Doc/zsh.fns +Doc/zsh.ky +Doc/zsh.kys +Doc/zsh.pg +Doc/zsh.pgs +Doc/zsh.vr +Doc/zsh.vrs +Doc/zsh.log +Doc/zsh.dvi +Doc/zsh_a4.dvi +Doc/zsh_us.dvi +Doc/zsh.tp +Doc/zsh.tps +Doc/zsh.idx +Doc/zsh_*.ps +Doc/infodir +Doc/zsh.pdf +Doc/zsh_a4.pdf +Doc/zsh_us.pdf + +Doc/Zsh/modlist.yo +Doc/Zsh/modmenu.yo +Doc/Zsh/manmodmenu.yo + +Etc/FAQ +Etc/FAQ.html + +Src/*.epro +Src/*.export +Src/*.mdh +Src/*.mdh.tmp +Src/*.mdhi +Src/*.mdhs +Src/*.syms +Src/Makemod.in +Src/Makemod +Src/[_a-zA-Z0-9]*.pro +Src/ansi2knr +Src/bltinmods.list +Src/cscope.out +Src/libzsh.so* +Src/modules-bltin +Src/modules.index +Src/modules.index.tmp +Src/modules.stamp +Src/patchlevel.h +Src/sigcount.h +Src/signames.c +Src/signames2.c +Src/stamp-modobjs +Src/stamp-modobjs.tmp +Src/tags +Src/TAGS +Src/version.h +Src/zsh +Src/zsh.exe +Src/zshcurses.h +Src/zshpaths.h +Src/zshterm.h +Src/zshxmods.h + +Src/Builtins/Makefile.in +Src/Builtins/*.export +Src/Builtins/so_locations +Src/Builtins/*.pro +Src/Builtins/*.epro +Src/Builtins/*.syms +Src/Builtins/*.mdh +Src/Builtins/*.mdhi +Src/Builtins/*.mdhs +Src/Builtins/*.mdh.tmp +Src/Builtins/rlimits.h + +Src/Modules/Makefile.in +Src/Modules/*.export +Src/Modules/so_locations +Src/Modules/*.pro +Src/Modules/*.epro +Src/Modules/*.syms +Src/Modules/*.mdh +Src/Modules/*.mdhi +Src/Modules/*.mdhs +Src/Modules/*.mdh.tmp +Src/Modules/errnames.c +Src/Modules/errcount.h +Src/Modules/curses_keys.h + +Src/Zle/Makefile.in +Src/Zle/*.export +Src/Zle/so_locations +Src/Zle/*.pro +Src/Zle/*.epro +Src/Zle/*.syms +Src/Zle/*.mdh +Src/Zle/*.mdhi +Src/Zle/*.mdhs +Src/Zle/*.mdh.tmp +Src/Zle/thingies.list +Src/Zle/widgets.list +Src/Zle/zle_things.h +Src/Zle/zle_widget.h + +Test/*.tmp +/.project diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.preconfig b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.preconfig new file mode 100755 index 00000000..f9729bd9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/.preconfig @@ -0,0 +1,7 @@ +#! /bin/sh + +set -e + +autoconf +autoheader +echo > stamp-h.in diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/.cvsignore b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/.cvsignore new file mode 100644 index 00000000..dd265a71 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/.cvsignore @@ -0,0 +1,2 @@ +defs.mk +*.swp diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/.distfiles b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/.distfiles new file mode 100644 index 00000000..f03668b3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/.distfiles @@ -0,0 +1,2 @@ +DISTFILES_SRC=' +' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/aczshoot.m4 b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/aczshoot.m4 new file mode 100644 index 00000000..3b90c6c7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/aczshoot.m4 @@ -0,0 +1,8 @@ +AC_DEFUN([zsh_OOT], +[ +AC_CHECK_HEADERS(stdarg.h varargs.h termios.h termio.h) + +AC_TYPE_SIGNAL + +AC_DEFINE([ZSH_OOT_MODULE], [], [Out-of-tree module]) +]) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/clean.mk b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/clean.mk new file mode 100644 index 00000000..918a84ff --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/clean.mk @@ -0,0 +1,43 @@ +# +# Makefile fragment for cleanup +# +# Copyright (c) 1995-1997 Richard Coleman +# All rights reserved. +# +# Permission is hereby granted, without written agreement and without +# license or royalty fees, to use, copy, modify, and distribute this +# software and to distribute modified versions of this software for any +# purpose, provided that the above copyright notice and the following +# two paragraphs appear in all copies of this software. +# +# In no event shall Richard Coleman or the Zsh Development Group be liable +# to any party for direct, indirect, special, incidental, or consequential +# damages arising out of the use of this software and its documentation, +# even if Richard Coleman and the Zsh Development Group have been advised of +# the possibility of such damage. +# +# Richard Coleman and the Zsh Development Group specifically disclaim any +# warranties, including, but not limited to, the implied warranties of +# merchantability and fitness for a particular purpose. The software +# provided hereunder is on an "as is" basis, and Richard Coleman and the +# Zsh Development Group have no obligation to provide maintenance, +# support, updates, enhancements, or modifications. +# + +mostlyclean: mostlyclean-recursive mostlyclean-here +clean: clean-recursive clean-here +distclean: distclean-recursive distclean-here +realclean: realclean-recursive realclean-here + +mostlyclean-here: +clean-here: mostlyclean-here +distclean-here: clean-here +realclean-here: distclean-here + +mostlyclean-recursive clean-recursive distclean-recursive realclean-recursive: + @subdirs='$(SUBDIRS)'; if test -n "$$subdirs"; then \ + target=`echo $@ | sed s/-recursive//`; \ + for subdir in $$subdirs; do \ + (cd $$subdir && $(MAKE) $(MAKEDEFS) $$target) || exit 1; \ + done; \ + fi diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/config.mk b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/config.mk new file mode 100644 index 00000000..fd9abf6a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/config.mk @@ -0,0 +1,42 @@ +# +# Makefile fragment for building Makefiles +# +# Copyright (c) 1995-1997 Richard Coleman +# All rights reserved. +# +# Permission is hereby granted, without written agreement and without +# license or royalty fees, to use, copy, modify, and distribute this +# software and to distribute modified versions of this software for any +# purpose, provided that the above copyright notice and the following +# two paragraphs appear in all copies of this software. +# +# In no event shall Richard Coleman or the Zsh Development Group be liable +# to any party for direct, indirect, special, incidental, or consequential +# damages arising out of the use of this software and its documentation, +# even if Richard Coleman and the Zsh Development Group have been advised of +# the possibility of such damage. +# +# Richard Coleman and the Zsh Development Group specifically disclaim any +# warranties, including, but not limited to, the implied warranties of +# merchantability and fitness for a particular purpose. The software +# provided hereunder is on an "as is" basis, and Richard Coleman and the +# Zsh Development Group have no obligation to provide maintenance, +# support, updates, enhancements, or modifications. +# + +config: Makefile + @subdirs='$(SUBDIRS)'; for subdir in $$subdirs; do \ + (cd $$subdir && $(MAKE) $(MAKEDEFS) $@) || exit 1; \ + done + +CONFIG_INCS = \ +$(dir_top)/Config/clean.mk $(dir_top)/Config/config.mk \ +$(dir_top)/Config/defs.mk $(dir_top)/Config/version.mk + +Makefile: Makefile.in $(dir_top)/config.status $(CONFIG_INCS) + cd $(dir_top) && \ + $(SHELL) ./config.status `echo $(subdir)/$@ | sed 's%^./%%'` + +$(dir_top)/Config/defs.mk: $(sdir_top)/Config/defs.mk.in $(dir_top)/config.status + cd $(dir_top) && \ + $(SHELL) ./config.status Config/defs.mk diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/defs.mk.in b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/defs.mk.in new file mode 100644 index 00000000..2bc17482 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/defs.mk.in @@ -0,0 +1,114 @@ +# +# Basic Makefile definitions +# +# Copyright (c) 1995-1997 Richard Coleman +# All rights reserved. +# +# Permission is hereby granted, without written agreement and without +# license or royalty fees, to use, copy, modify, and distribute this +# software and to distribute modified versions of this software for any +# purpose, provided that the above copyright notice and the following +# two paragraphs appear in all copies of this software. +# +# In no event shall Richard Coleman or the Zsh Development Group be liable +# to any party for direct, indirect, special, incidental, or consequential +# damages arising out of the use of this software and its documentation, +# even if Richard Coleman and the Zsh Development Group have been advised of +# the possibility of such damage. +# +# Richard Coleman and the Zsh Development Group specifically disclaim any +# warranties, including, but not limited to, the implied warranties of +# merchantability and fitness for a particular purpose. The software +# provided hereunder is on an "as is" basis, and Richard Coleman and the +# Zsh Development Group have no obligation to provide maintenance, +# support, updates, enhancements, or modifications. +# + +# fundamentals +SHELL = /bin/sh +@SET_MAKE@ +EXEEXT = @EXEEXT@ + +# headers +ZSH_CURSES_H = @ZSH_CURSES_H@ +ZSH_TERM_H = @ZSH_TERM_H@ + +# install basename +tzsh = @tzsh@ + +# installation directories +prefix = @prefix@ +exec_prefix = @exec_prefix@ +bindir = @bindir@ +libdir = @libdir@ +MODDIR = $(libdir)/$(tzsh)/$(VERSION) +infodir = @infodir@ +mandir = @mandir@ +datarootdir = @datarootdir@ +datadir = @datadir@ +fndir = @fndir@ +fixed_sitefndir = @fixed_sitefndir@ +sitefndir = @sitefndir@ +scriptdir = @scriptdir@ +sitescriptdir = @sitescriptdir@ +htmldir = @htmldir@ +runhelpdir = @runhelpdir@ +runhelp = @runhelp@ + +# compilation +CC = @CC@ +CPP = @CPP@ +CPPFLAGS = @CPPFLAGS@ +DEFS = @DEFS@ +CFLAGS = @CFLAGS@ +LDFLAGS = @LDFLAGS@ +EXTRA_LDFLAGS = @EXTRA_LDFLAGS@ +DLCFLAGS = @DLCFLAGS@ +DLLDFLAGS = @DLLDFLAGS@ +LIBLDFLAGS = @LIBLDFLAGS@ +EXELDFLAGS = @EXELDFLAGS@ +LIBS = @LIBS@ +DL_EXT = @DL_EXT@ +DLLD = @DLLD@ +EXPOPT = @EXPOPT@ +IMPOPT = @IMPOPT@ + +# utilities +AWK = @AWK@ +ANSI2KNR = @ANSI2KNR@ +YODL = @YODL@ @YODL_OPTIONS@ +YODL2TXT = @YODL@2txt +YODL2HTML = @YODL@2html + +# install utility +INSTALL_PROGRAM = @INSTALL_PROGRAM@ +INSTALL_DATA = @INSTALL_DATA@ + +# variables used in determining what to install +FUNCTIONS_SUBDIRS = @FUNCTIONS_SUBDIRS@ + +# Additional fpath entries (eg. for vendor specific directories). +additionalfpath = @additionalfpath@ + +# flags passed to recursive makes in subdirectories +MAKEDEFS = \ +prefix='$(prefix)' exec_prefix='$(exec_prefix)' bindir='$(bindir)' \ +libdir='$(libdir)' MODDIR='$(MODDIR)' infodir='$(infodir)' mandir='$(mandir)' \ +datadir='$(datadir)' fndir='$(fndir)' htmldir='$(htmldir)' runhelpdir='$(runhelpdir)' \ +CC='$(CC)' CPPFLAGS='$(CPPFLAGS)' DEFS='$(DEFS)' CFLAGS='$(CFLAGS)' \ +LDFLAGS='$(LDFLAGS)' EXTRA_LDFLAGS='$(EXTRA_LDFLAGS)' \ +DLCFLAGS='$(DLCFLAGS)' DLLDFLAGS='$(DLLDFLAGS)' \ +LIBLDFLAGS='$(LIBLDFLAGS)' EXELDFLAGS='$(EXELDFLAGS)' \ +LIBS='$(LIBS)' DL_EXT='$(DL_EXT)' DLLD='$(DLLD)' \ +AWK='$(AWK)' ANSI2KNR='$(ANSI2KNR)' \ +YODL='$(YODL)' YODL2TXT='$(YODL2TXT)' YODL2HTML='$(YODL2HTML)' \ +FUNCTIONS_INSTALL='$(FUNCTIONS_INSTALL)' tzsh='$(tzsh)' + +# override built-in suffix list +.SUFFIXES: + +# parallel build is not supported (pmake, gmake) +.NOTPARALLEL: + +# parallel build is not supported (dmake) +.NO_PARALLEL: diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/installfns.sh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/installfns.sh new file mode 100755 index 00000000..149f359c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/installfns.sh @@ -0,0 +1,74 @@ +#!/bin/sh + +fndir=$DESTDIR$fndir +scriptdir=$DESTDIR$scriptdir + +/bin/sh $sdir_top/mkinstalldirs $fndir || exit 1; + +allfuncs="`grep ' functions=.' ${dir_top}/config.modules | + sed -e '/^#/d' -e '/ link=no/d' -e 's/^.* functions=//'`" + +allfuncs="`cd $sdir_top; echo ${allfuncs}`" + +test -d installfnsdir || mkdir installfnsdir + +# We now have a list of files, but we need to use `test -f' to check +# (1) the glob got expanded (2) we are not looking at directories. +for file in $allfuncs; do + if test -f $sdir_top/$file; then + case "$file" in + */CVS/*) continue;; + esac + if test x$FUNCTIONS_SUBDIRS != x && test x$FUNCTIONS_SUBDIRS != xno; then + case "$file" in + Completion/*/*) + subdir="`echo $file | sed -e 's%/[^/]*/[^/]*$%%'`" + instdir="$fndir/$subdir" + ;; + Completion/*) + instdir="$fndir/Completion" + ;; + Scripts/*) + instdir="$scriptdir" + ;; + *) + subdir="`echo $file | sed -e 's%/[^/]*$%%' -e 's%^Functions/%%'`" + instdir="$fndir/$subdir" + ;; + esac + else + case "$file" in + Scripts/*) + instdir="$scriptdir" + ;; + *) + instdir="$fndir" + ;; + esac + fi + basename=`basename $file` + ok=0 + if test -d $instdir || /bin/sh $sdir_top/mkinstalldirs $instdir; then + if sed "s|@runhelpdir@|$runhelpdir|" <$sdir_top/$file \ + >installfnsdir/$basename; then + if $INSTALL_DATA installfnsdir/$basename $instdir; then + ok=1 + fi + fi + fi + case $ok in + 0) + rm -rf installfnsdir + exit 1 + ;; + esac + read line < $sdir_top/$file + case "$line" in + '#!'*) + chmod +x $instdir/`echo $file | sed -e 's%^.*/%%'` + ;; + esac + fi +done + +rm -rf installfnsdir diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/uninstallfns.sh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/uninstallfns.sh new file mode 100755 index 00000000..7c223889 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/uninstallfns.sh @@ -0,0 +1,59 @@ +#!/bin/sh + +fndir=$DESTDIR$fndir +scriptdir=$DESTDIR$scriptdir + +allfuncs="`grep ' functions=' ${dir_top}/config.modules | + sed -e '/^#/d' -e '/ link=no/d' -e 's/^.* functions=//'`" + +allfuncs="`cd ${sdir_top}; echo ${allfuncs}`" + +case $fndir in + *$VERSION*) + # Version specific function directory, safe to remove completely. + rm -rf $fndir + ;; + *) # The following will only apply with a custom install directory + # with no version information. This is rather undesirable. + # But let's try and do the best we can. + # We now have a list of files, but we need to use `test -f' to check + # (1) the glob got expanded (2) we are not looking at directories. + for file in $allfuncs; do + case $file in + Scripts/*) + ;; + *) + if test -f $sdir_top/$file; then + if test x$FUNCTIONS_SUBDIRS != x -a x$FUNCTIONS_SUBDIRS != xno; then + file=`echo $file | sed -e 's%%^(Functions|Completion)/%'` + rm -f $fndir/$file + else + bfile="`echo $file | sed -e 's%^.*/%%'`" + rm -f "$fndir/$bfile" + fi + fi + ;; + esac + done + ;; +esac + +case $scriptdir in + *$VERSION*) + # $scriptdir might be the parent of fndir. + rm -rf $scriptdir + ;; + *) for file in $allfuncs; do + case $file in + Scripts/*) + if test -f $sdir_top/$file; then + bfile="`echo $file | sed -e 's%^.*/%%'`" + rm -f "$scriptdir/$bfile" + fi + ;; + esac + done + ;; +esac + +exit 0 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/version.mk b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/version.mk new file mode 100644 index 00000000..0ebed5e7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Config/version.mk @@ -0,0 +1,31 @@ +# +# Makefile fragment for version numbers +# +# Copyright (c) 1995-1997 Richard Coleman +# All rights reserved. +# +# Permission is hereby granted, without written agreement and without +# license or royalty fees, to use, copy, modify, and distribute this +# software and to distribute modified versions of this software for any +# purpose, provided that the above copyright notice and the following +# two paragraphs appear in all copies of this software. +# +# In no event shall Richard Coleman or the Zsh Development Group be liable +# to any party for direct, indirect, special, incidental, or consequential +# damages arising out of the use of this software and its documentation, +# even if Richard Coleman and the Zsh Development Group have been advised of +# the possibility of such damage. +# +# Richard Coleman and the Zsh Development Group specifically disclaim any +# warranties, including, but not limited to, the implied warranties of +# merchantability and fitness for a particular purpose. The software +# provided hereunder is on an "as is" basis, and Richard Coleman and the +# Zsh Development Group have no obligation to provide maintenance, +# support, updates, enhancements, or modifications. +# + +# This must also serve as a shell script, so do not add spaces around the +# `=' signs. + +VERSION=5.3.1-dev-0 +VERSION_DATE='December 22, 2016' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/LICENCE b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/LICENCE new file mode 100644 index 00000000..08fcf88f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/LICENCE @@ -0,0 +1,37 @@ +Unless otherwise noted in the header of specific files, files in this +distribution have the licence shown below. + +However, note that certain shell functions are licensed under versions +of the GNU General Public Licence. Anyone distributing the shell as a +binary including those files needs to take account of this. Search +shell functions for "Copyright" for specific copyright information. +None of the core functions are affected by this, so those files may +simply be omitted. + +-- + +The Z Shell is copyright (c) 1992-2017 Paul Falstad, Richard Coleman, +Zoltán Hidvégi, Andrew Main, Peter Stephenson, Sven Wischnowsky, and +others. All rights reserved. Individual authors, whether or not +specifically named, retain copyright in all changes; in what follows, they +are referred to as `the Zsh Development Group'. This is for convenience +only and this body has no legal status. The Z shell is distributed under +the following licence; any provisions made in individual files take +precedence. + +Permission is hereby granted, without written agreement and without +licence or royalty fees, to use, copy, modify, and distribute this +software and to distribute modified versions of this software for any +purpose, provided that the above copyright notice and the following +two paragraphs appear in all copies of this software. + +In no event shall the Zsh Development Group be liable to any party for +direct, indirect, special, incidental, or consequential damages arising out +of the use of this software and its documentation, even if the Zsh +Development Group have been advised of the possibility of such damage. + +The Zsh Development Group specifically disclaim any warranties, including, +but not limited to, the implied warranties of merchantability and fitness +for a particular purpose. The software provided hereunder is on an "as is" +basis, and the Zsh Development Group have no obligation to provide +maintenance, support, updates, enhancements, or modifications. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Makefile.in b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Makefile.in new file mode 100644 index 00000000..4f9aa1aa --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Makefile.in @@ -0,0 +1,87 @@ +# +# Makefile for top level of zsh distribution +# +# Copyright (c) 1995-1997 Richard Coleman +# All rights reserved. +# +# Permission is hereby granted, without written agreement and without +# license or royalty fees, to use, copy, modify, and distribute this +# software and to distribute modified versions of this software for any +# purpose, provided that the above copyright notice and the following +# two paragraphs appear in all copies of this software. +# +# In no event shall Richard Coleman or the Zsh Development Group be liable +# to any party for direct, indirect, special, incidental, or consequential +# damages arising out of the use of this software and its documentation, +# even if Richard Coleman and the Zsh Development Group have been advised of +# the possibility of such damage. +# +# Richard Coleman and the Zsh Development Group specifically disclaim any +# warranties, including, but not limited to, the implied warranties of +# merchantability and fitness for a particular purpose. The software +# provided hereunder is on an "as is" basis, and Richard Coleman and the +# Zsh Development Group have no obligation to provide maintenance, +# support, updates, enhancements, or modifications. +# + +subdir = . +dir_top = . +SUBDIRS = Src + +@VERSION_MK@ + +# source/build directories +VPATH = @srcdir@ +sdir = @srcdir@ +sdir_top = @top_srcdir@ +INSTALL = @INSTALL@ + +@DEFS_MK@ + +# ========== DEPENDENCIES FOR BUILDING ========== + +# default target +all: config.h config.modules + cd Src && $(MAKE) $(MAKEDEFS) $@ + +# prepare module configuration +prep: + @cd Src && $(MAKE) $(MAKEDEFS) $@ + +# ========== DEPENDENCIES FOR CLEANUP ========== + +@CLEAN_MK@ + +distclean-here: + rm -f Makefile config.h config.status config.log config.cache config.modules config.modules.sh stamp-h Config/defs.mk + rm -rf autom4te.cache + +realclean-here: + cd $(sdir) && rm -f config.h.in stamp-h.in configure + +# ========== DEPENDENCIES FOR MAINTENANCE ========== + +@CONFIG_MK@ + +config: config.h + +config.status: $(sdir)/configure + $(SHELL) ./config.status --recheck + +$(sdir)/configure: $(sdir)/aclocal.m4 $(sdir)/aczsh.m4 $(sdir)/configure.ac + cd $(sdir) && autoconf + +config.h: stamp-h +stamp-h: $(sdir)/config.h.in config.status + cd $(dir_top) && $(SHELL) ./config.status config.h $@ + +config.modules: $(sdir)/config.h.in config.status config.modules.sh + cd $(dir_top) && $(SHELL) ./config.status $@ && \ + $(SHELL) ./config.modules.sh + +$(sdir)/config.h.in: $(sdir)/stamp-h.in +$(sdir)/stamp-h.in: $(sdir)/configure + cd $(sdir) && autoheader + echo > $(sdir)/stamp-h.in + +FORCE: diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/RECOMPILE_REQUEST b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/RECOMPILE_REQUEST new file mode 100644 index 00000000..cbf32b01 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/RECOMPILE_REQUEST @@ -0,0 +1 @@ +1580588806 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/.cvsignore b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/.cvsignore new file mode 100644 index 00000000..47b31911 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/.cvsignore @@ -0,0 +1,35 @@ +*.dll +*.epro +*.export +*.mdh +*.mdh.tmp +*.mdhi +*.mdhs +*.o +*.o.c +*.so +*.swp +*.syms +Makefile +Makemod.in Makemod +[_a-zA-Z0-9]*.pro +ansi2knr +bltinmods.list +cscope.out +libzsh.so* +modules-bltin +modules.index +modules.index.tmp +modules.stamp +patchlevel.h +sigcount.h +signames.c signames2.c +stamp-modobjs +stamp-modobjs.tmp +tags TAGS +version.h +zsh +zshcurses.h +zshpaths.h +zshterm.h +zshxmods.h diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/.distfiles b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/.distfiles new file mode 100644 index 00000000..f03668b3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/.distfiles @@ -0,0 +1,2 @@ +DISTFILES_SRC=' +' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/.exrc b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/.exrc new file mode 100644 index 00000000..91d0b39e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/.exrc @@ -0,0 +1,2 @@ +set ai +set sw=4 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/.indent.pro b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/.indent.pro new file mode 100644 index 00000000..1b41514f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/.indent.pro @@ -0,0 +1,27 @@ +--dont-format-comments +--procnames-start-lines +--no-parameter-indentation +--indent-level4 +--line-comments-indentation4 +--cuddle-else +--brace-indent0 +--dont-star-comments +--blank-lines-after-declarations +--blank-lines-after-procedures +--no-blank-lines-after-commas +--comment-indentation33 +--declaration-comment-column33 +--no-comment-delimiters-on-blank-lines +--continuation-indentation4 +--case-indentation0 +--else-endif-column33 +--no-space-after-casts +--no-blank-before-sizeof +--declaration-indentation0 +--continue-at-parentheses +--no-space-after-function-call-names +--swallow-optional-blank-lines +--dont-space-special-semicolon +--tab-size8 +--line-length132 +--braces-on-if-line diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/Makefile.in b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/Makefile.in new file mode 100644 index 00000000..2987b649 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/Makefile.in @@ -0,0 +1,164 @@ +# +# Makefile for Src subdirectory +# +# Copyright (c) 1995-1997 Richard Coleman +# All rights reserved. +# +# Permission is hereby granted, without written agreement and without +# license or royalty fees, to use, copy, modify, and distribute this +# software and to distribute modified versions of this software for any +# purpose, provided that the above copyright notice and the following +# two paragraphs appear in all copies of this software. +# +# In no event shall Richard Coleman or the Zsh Development Group be liable +# to any party for direct, indirect, special, incidental, or consequential +# damages arising out of the use of this software and its documentation, +# even if Richard Coleman and the Zsh Development Group have been advised of +# the possibility of such damage. +# +# Richard Coleman and the Zsh Development Group specifically disclaim any +# warranties, including, but not limited to, the implied warranties of +# merchantability and fitness for a particular purpose. The software +# provided hereunder is on an "as is" basis, and Richard Coleman and the +# Zsh Development Group have no obligation to provide maintenance, +# support, updates, enhancements, or modifications. +# + +subdir = Src +dir_top = .. +SUBDIRS = + +@VERSION_MK@ + +# source/build directories +VPATH = @srcdir@ +sdir = @srcdir@ +sdir_top = @top_srcdir@ +INSTALL = @INSTALL@ +LN = @LN@ + +@DEFS_MK@ + +sdir_src = $(sdir) +dir_src = . + +# ========= DEPENDENCIES FOR BUILDING ========== + +LINK = $(CC) $(LDFLAGS) $(EXELDFLAGS) $(EXTRA_LDFLAGS) -o $@ +DLLINK = $(DLLD) $(LDFLAGS) $(LIBLDFLAGS) $(DLLDFLAGS) -o $@ + +all: zsh.export modules +.PHONY: all + +modules: headers +.PHONY: modules + +L = @L@ + +LSTMP = +LLIST = +NSTMP = stamp-modobjs +NLIST = `cat stamp-modobjs` + +LIBZSH = libzsh-$(VERSION).$(DL_EXT) +NIBZSH = +INSTLIB = @INSTLIB@ +UNINSTLIB = @UNINSTLIB@ + +ZSH_EXPORT = $(EXPOPT)zsh.export +ZSH_NXPORT = +ENTRYOBJ = modentry..o +NNTRYOBJ = + +LDRUNPATH = LD_RUN_PATH=$(libdir)/$(tzsh) +NDRUNPATH = + +EXTRAZSHOBJS = @EXTRAZSHOBJS@ + +stamp-modobjs: modobjs + @if cmp -s stamp-modobjs.tmp stamp-modobjs; then \ + rm -f stamp-modobjs.tmp; \ + echo "\`stamp-modobjs' is up to date."; \ + else \ + mv -f stamp-modobjs.tmp stamp-modobjs; \ + echo "Updated \`stamp-modobjs'."; \ + fi + +modobjs: headers rm-modobjs-tmp +.PHONY: modobjs + +rm-modobjs-tmp: + rm -f stamp-modobjs.tmp +.PHONY: rm-modobjs-tmp + +@CONFIG_MK@ + +Makemod: $(CONFIG_INCS) $(dir_top)/config.modules + @case $(sdir_top) in \ + /*) top_srcdir=$(sdir_top) ;; \ + *) top_srcdir=$(subdir)/$(sdir_top) ;; \ + esac; \ + export top_srcdir; \ + echo 'cd $(dir_top) && $(SHELL)' \ + '$$top_srcdir/$(subdir)/mkmakemod.sh $(subdir) Makemod'; \ + cd $(dir_top) && \ + $(SHELL) $$top_srcdir/$(subdir)/mkmakemod.sh $(subdir) Makemod +prep: Makemod + @$(MAKE) -f Makemod $(MAKEDEFS) prep || rm -f Makemod +.PHONY: prep + +FORCE: +.PHONY: FORCE + +# ========== LINKING IN MODULES ========== + +mymods.conf: + @echo Linking with the standard modules. + +modules: $(@E@NTRYOBJ) + +$(ENTRYOBJ): FORCE + @$(MAKE) -f Makemod $(MAKEDEFS) $@ + +# ========== DEPENDENCIES FOR CLEANUP ========== + +# Since module cleanup rules depend on Makemod, they come first. This +# forces module stuff to get cleaned before Makemod itself gets +# deleted. + +mostlyclean-here: + rm -f stamp-modobjs stamp-modobjs.tmp +.PHONY: mostlyclean-here + +clean-here: + rm -f modules.stamp zsh$(EXEEXT) + rm -f libzsh-*.$(DL_EXT) +.PHONY: clean-here + +distclean-here: + rm -f TAGS tags + rm -f Makefile +.PHONY: distclean-here + +mostlyclean: mostlyclean-modules +clean: clean-modules +distclean: distclean-modules +realclean: realclean-modules +.PHONY: mostlyclean clean distclean realclean + +# Don't remake Makemod just to delete things, even if it doesn't exist. +mostlyclean-modules clean-modules distclean-modules realclean-modules: + if test -f Makemod; then \ + $(MAKE) -f Makemod $(MAKEDEFS) `echo $@ | sed 's/-modules//'`; \ + fi; \ + exit 0 +.PHONY: mostlyclean-modules clean-modules distclean-modules \ + realclean-modules + +@CLEAN_MK@ + +# ========== RECURSIVE MAKES ========== + +modobjs modules headers proto zsh.export: Makemod + @$(MAKE) -f Makemod $(MAKEDEFS) $@ +.PHONY: headers proto diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/Makemod.in.in b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/Makemod.in.in new file mode 100644 index 00000000..ea0cdc3a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/Makemod.in.in @@ -0,0 +1,192 @@ +# +# Makemod.in.in +# +# Copyright (c) 1995-1997 Richard Coleman +# All rights reserved. +# +# Permission is hereby granted, without written agreement and without +# license or royalty fees, to use, copy, modify, and distribute this +# software and to distribute modified versions of this software for any +# purpose, provided that the above copyright notice and the following +# two paragraphs appear in all copies of this software. +# +# In no event shall Richard Coleman or the Zsh Development Group be liable +# to any party for direct, indirect, special, incidental, or consequential +# damages arising out of the use of this software and its documentation, +# even if Richard Coleman and the Zsh Development Group have been advised of +# the possibility of such damage. +# +# Richard Coleman and the Zsh Development Group specifically disclaim any +# warranties, including, but not limited to, the implied warranties of +# merchantability and fitness for a particular purpose. The software +# provided hereunder is on an "as is" basis, and Richard Coleman and the +# Zsh Development Group have no obligation to provide maintenance, +# support, updates, enhancements, or modifications. +# + +# ========== OVERRIDABLE VARIABLES ========== + +# subdir is done by mkmakemod.sh +# dir_top is done by mkmakemod.sh +# SUBDIRS is done by mkmakemod.sh + +@VERSION_MK@ + +# source/build directories +VPATH = @srcdir@ +sdir = @srcdir@ +sdir_top = @top_srcdir@ +INSTALL = @INSTALL@ + +@DEFS_MK@ + +sdir_src = $(sdir_top)/Src +dir_src = $(dir_top)/Src + +# ========== COMPILATION RULES ========== + +DNCFLAGS = + +COMPILE = $(CC) -c -I. -I$(dir_top)/Src -I$(sdir_top)/Src -I$(sdir_top)/Src/Zle -I$(sdir) $(CPPFLAGS) $(DEFS) $(CFLAGS) $(D@L@CFLAGS) +DLCOMPILE = $(CC) -c -I. -I$(dir_top)/Src -I$(sdir_top)/Src -I$(sdir_top)/Src/Zle -I$(sdir) $(CPPFLAGS) $(DEFS) -DMODULE $(CFLAGS) $(DLCFLAGS) +LINK = $(CC) $(LDFLAGS) $(EXELDFLAGS) $(EXTRA_LDFLAGS) -o $@ +DLLINK = $(DLLD) $(LDFLAGS) $(LIBLDFLAGS) $(DLLDFLAGS) -o $@ + +KNR_OBJ=.o +KNROBJ=._foo_ + +ANSIOBJ=.o +ANSI_OBJ=._foo_ + +.SUFFIXES: .c .$(DL_EXT) ..o .._foo_ .o ._foo_ .syms .pro .epro + +.c$(ANSI@U@OBJ): + $(COMPILE) -o $@ $< + @rm -f $(dir_src)/stamp-modobjs + +.c$(KNR@U@OBJ): + @ANSI2KNR@ $< > $@.c + $(COMPILE) -o $@ $@.c + rm -f $@.c + @rm -f $(dir_src)/stamp-modobjs + +.c.$(ANSI@U@OBJ): + $(DLCOMPILE) -o $@ $< + +.c.$(KNR@U@OBJ): + @ANSI2KNR@ $< > $@.c + $(DLCOMPILE) -o $@ $@.c + rm -f $@.c + +.c.syms: + $(AWK) -f $(sdir_src)/makepro.awk $< $(subdir) > $@ + +.syms.epro: + (echo '/* Generated automatically */'; sed -n '/^E/{s/^E//;p;}' < $<) \ + > $@ + (echo '/* Generated automatically */'; sed -n '/^L/{s/^L//;p;}' < $<) \ + > `echo $@ | sed 's/\.epro$$/.pro/'` + +PROTODEPS = $(sdir_src)/makepro.awk + +# ========== DEPENDENCIES FOR BUILDING ========== + +all: modobjs modules +.PHONY: all + +modobjs: $(MODOBJS) +modules: $(MODULES) +headers: $(MDHS) +proto: $(PROTOS) +.PHONY: modobjs modules headers proto + +prep: + @case $(sdir_top) in \ + /*) top_srcdir=$(sdir_top) ;; \ + *) top_srcdir=$(subdir)/$(sdir_top) ;; \ + esac; \ + export top_srcdir; \ + cd $(dir_top) || exit 1; \ + subdirs='$(SUBDIRS)'; \ + for subdir in $$subdirs; do \ + dir=$(subdir)/$$subdir; \ + test -d $$dir || mkdir $$dir; \ + $(SHELL) $$top_srcdir/Src/mkmakemod.sh $$dir Makefile || exit 1; \ + ( cd $$dir && $(MAKE) $(MAKEDEFS) $@ ) || exit 1; \ + done +.PHONY: prep + +headers: $(dir_src)/modules.stamp +$(dir_src)/modules.stamp: $(MDDS) + $(MAKE) -f $(makefile) $(MAKEDEFS) prep + echo 'timestamp for *.mdd files' > $@ +.PHONY: headers + +FORCE: +.PHONY: FORCE + +# ========== DEPENDENCIES FOR INSTALLING ========== + +install: install.bin install.modules +uninstall: uninstall.bin uninstall.modules +.PHONY: install uninstall + +install.bin: install.bin-here +uninstall.bin: uninstall.bin-here +install.modules: install.modules-here +uninstall.modules: uninstall.modules-here +.PHONY: install.bin uninstall.bin install.modules uninstall.modules + +install.bin-here uninstall.bin-here: +install.modules-here uninstall.modules-here: +.PHONY: install.bin-here install.modules-here + +# ========== DEPENDENCIES FOR CLEANUP ========== + +@CLEAN_MK@ + +mostlyclean-here: + rm -f *.o *.export *.$(DL_EXT) +.PHONY: mostlyclean-here + +clean-here: + rm -f *.o.c *.syms *.pro *.epro *.mdh *.mdhi *.mdhs *.mdh.tmp +.PHONY: clean-here + +distclean-here: + rm -f $(makefile) $(makefile).in +.PHONY: distclean-here + +# ========== RECURSIVE MAKES ========== + +install.bin uninstall.bin install.modules uninstall.modules \ +modobjs modules headers proto: + @subdirs='$(SUBDIRS)'; for subdir in $$subdirs; do \ + ( cd $$subdir && $(MAKE) $(MAKEDEFS) $@ ) || exit 1; \ + done + +# ========== DEPENDENCIES FOR MAINTENANCE ========== + +$(makefile): $(makefile).in $(dir_top)/config.status + @case $(sdir_top) in \ + /*) top_srcdir=$(sdir_top) ;; \ + *) top_srcdir=$(subdir)/$(sdir_top) ;; \ + esac; \ + export top_srcdir; \ + echo 'cd $(dir_top) && $(SHELL)' \ + '$$top_srcdir/Src/mkmakemod.sh -m $(subdir) $(makefile)'; \ + cd $(dir_top) && \ + $(SHELL) $$top_srcdir/Src/mkmakemod.sh -m $(subdir) $(makefile) + +$(makefile).in: $(sdir_src)/mkmakemod.sh $(sdir_src)/Makemod.in.in $(MDDS) \ + $(dir_top)/config.modules + @case $(sdir_top) in \ + /*) top_srcdir=$(sdir_top) ;; \ + *) top_srcdir=$(subdir)/$(sdir_top) ;; \ + esac; \ + export top_srcdir; \ + echo 'cd $(dir_top) && $(SHELL)' \ + '$$top_srcdir/Src/mkmakemod.sh -i $(subdir) $(makefile)'; \ + cd $(dir_top) && \ + $(SHELL) $$top_srcdir/Src/mkmakemod.sh -i $(subdir) $(makefile) + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/.cvsignore b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/.cvsignore new file mode 100644 index 00000000..f72db844 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/.cvsignore @@ -0,0 +1,18 @@ +Makefile +Makefile.in +*.export +so_locations +*.pro +*.epro +*.syms +*.o +*.o.c +*.so +*.mdh +*.mdhi +*.mdhs +*.mdh.tmp +*.swp +errnames.c errcount.h +*.dll +curses_keys.h diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/.distfiles b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/.distfiles new file mode 100644 index 00000000..f03668b3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/.distfiles @@ -0,0 +1,2 @@ +DISTFILES_SRC=' +' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/.exrc b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/.exrc new file mode 100644 index 00000000..91d0b39e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/.exrc @@ -0,0 +1,2 @@ +set ai +set sw=4 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/.gitignore b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/.gitignore new file mode 100644 index 00000000..92f708e2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/.gitignore @@ -0,0 +1,8 @@ +Makefile.in +*.epro +*.export +*.mdh +*.mdhi +*.mdhs +*.pro +*.syms diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/fzftab.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/fzftab.c new file mode 100644 index 00000000..adaf2a0e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/fzftab.c @@ -0,0 +1,541 @@ +#include "fzftab.mdh" +#include "fzftab.pro" +#include +#include +#include +#include + +const char* get_color(char* file, const struct stat* sb); +const char* get_suffix(char* file, const struct stat* sb); +const char* colorize_from_mode(char* file, const struct stat* sb); +const char* colorize_from_name(char* file); +char** fzf_tab_colorize(char* file); +int compile_patterns(char* nam, char** list_colors); +char* ftb_strcat(char* dst, int n, ...); + +/* Indixes into the terminal string arrays. */ +#define COL_NO 0 +#define COL_FI 1 +#define COL_DI 2 +#define COL_LN 3 +#define COL_PI 4 +#define COL_SO 5 +#define COL_BD 6 +#define COL_CD 7 +#define COL_OR 8 +#define COL_MI 9 +#define COL_SU 10 +#define COL_SG 11 +#define COL_TW 12 +#define COL_OW 13 +#define COL_ST 14 +#define COL_EX 15 +#define COL_LC 16 +#define COL_RC 17 +#define COL_EC 18 +#define COL_TC 19 +#define COL_SP 20 +#define COL_MA 21 +#define COL_HI 22 +#define COL_DU 23 +#define COL_SA 24 + +#define NUM_COLS 25 + +/* Names of the terminal strings. */ +static char* colnames[] = { "no", "fi", "di", "ln", "pi", "so", "bd", "cd", "or", "mi", "su", "sg", + "tw", "ow", "st", "ex", "lc", "rc", "ec", "tc", "sp", "ma", "hi", "du", "sa", NULL }; + +/* Default values. */ +static char* defcols[] + = { "0", "0", "1;31", "1;36", "33", "1;35", "1;33", "1;33", NULL, NULL, "37;41", "30;43", + "30;42", "34;42", "37;44", "1;32", "\033[", "m", NULL, "0", "0", "7", NULL, NULL, "0" }; + +static char* fzf_tab_module_version; + +struct pattern { + Patprog pat; + char color[50]; +}; + +static int opt_list_type = OPT_INVALID; +static int pat_cnt = 0; +static struct pattern* name_color = NULL; +static char mode_color[NUM_COLS][20]; + +// TODO: use ZLS_COLORS ? +int compile_patterns(char* nam, char** list_colors) +{ + // clean old name_color and set pat_cnt = 0 + if (pat_cnt != 0) { + while (--pat_cnt) { + freepatprog(name_color[pat_cnt].pat); + } + free(name_color); + } + // initialize mode_color with default value + for (int i = 0; i < NUM_COLS; i++) { + if (defcols[i]) { + strcpy(mode_color[i], defcols[i]); + } + } + // empty array, just return + if (list_colors == NULL) { + return 0; + } + + // how many pattens? + while (list_colors[pat_cnt] != NULL) { + pat_cnt++; + } + name_color = zshcalloc(pat_cnt * sizeof(struct pattern)); + + for (int i = 0; i < pat_cnt; i++) { + char* pat = ztrdup(list_colors[i]); + char* color = strrchr(pat, '='); + if (color == NULL) + continue; + *color = '\0'; + tokenize(pat); + remnulargs(pat); + + // mode=color + bool skip = false; + for (int j = 0; j < NUM_COLS; j++) { + if (strpfx(colnames[j], list_colors[i])) { + strcpy(mode_color[j], color + 1); + name_color[i].pat = NULL; + skip = true; + } + } + if (skip) { + continue; + } + + // name=color + if ((name_color[i].pat = patcompile(pat, PAT_ZDUP, NULL))) { + strcpy(name_color[i].color, color + 1); + } + + free(pat); + } + return 0; +} + +// TODO: use zsh mod_export function `file_type` ? +const char* get_suffix(char* file, const struct stat* sb) +{ + struct stat sb2; + mode_t filemode = sb->st_mode; + + if (S_ISBLK(filemode)) + return "#"; + else if (S_ISCHR(filemode)) + return "%"; + else if (S_ISDIR(filemode)) + return "/"; + else if (S_ISFIFO(filemode)) + return "|"; + else if (S_ISLNK(filemode)) + if (strpfx(mode_color[COL_LN], "target")) { + if (stat(file, &sb2) == -1) { + return "@"; + } + return get_suffix(file, &sb2); + } else { + return "@"; + } + else if (S_ISREG(filemode)) + return (filemode & S_IXUGO) ? "*" : ""; + else if (S_ISSOCK(filemode)) + return "="; + else + return "?"; +} + +const char* get_color(char* file, const struct stat* sb) +{ + // no list-colors, return empty color + if (pat_cnt == 0) { + return ""; + } + const char* ret; + if ((ret = colorize_from_mode(file, sb)) || (ret = colorize_from_name(file))) { + return ret; + } + return mode_color[COL_FI]; +} + +const char* colorize_from_name(char* file) +{ + for (int i = 0; i < pat_cnt; i++) { + if (name_color && name_color[i].pat && pattry(name_color[i].pat, file)) { + return name_color[i].color; + } + } + return NULL; +} + +const char* colorize_from_mode(char* file, const struct stat* sb) +{ + struct stat sb2; + + switch (sb->st_mode & S_IFMT) { + case S_IFDIR: + return mode_color[COL_DI]; + case S_IFLNK: { + if (strpfx(mode_color[COL_LN], "target")) { + if (stat(file, &sb2) == -1) { + return mode_color[COL_OR]; + } + return get_color(file, &sb2); + } + } + case S_IFIFO: + return mode_color[COL_PI]; + case S_IFSOCK: + return mode_color[COL_SO]; + case S_IFBLK: + return mode_color[COL_BD]; + case S_IFCHR: + return mode_color[COL_CD]; + default: + break; + } + + if (sb->st_mode & S_ISUID) { + return mode_color[COL_SU]; + } else if (sb->st_mode & S_ISGID) { + return mode_color[COL_SG]; + // tw ow st ?? + } else if (sb->st_mode & S_IXUSR) { + return mode_color[COL_EX]; + } + + /* Check for suffix alias */ + size_t len = strlen(file); + /* shortest valid suffix format is a.b */ + if (len > 2) { + const char* suf = file + len - 1; + while (suf > file + 1) { + if (suf[-1] == '.') { + if (sufaliastab->getnode(sufaliastab, suf)) { + return mode_color[COL_SA]; + } + break; + } + suf--; + } + } + + return NULL; +} + +struct { + char** array; + size_t len; + size_t size; +} ftb_compcap; + +// Usage: +// initialize fzf-tab-generate-compcap -i +// output to _ftb_compcap fzf-tab-generate-compcap -o +// add a entry fzf-tab-generate-compcap word desc opts +static int bin_fzf_tab_compcap_generate(char* nam, char** args, Options ops, UNUSED(int func)) +{ + if (OPT_ISSET(ops, 'o')) { + // write final result to _ftb_compcap + setaparam("_ftb_compcap", ftb_compcap.array); + ftb_compcap.array = NULL; + return 0; + } else if (OPT_ISSET(ops, 'i')) { + // init + if (ftb_compcap.array) + freearray(ftb_compcap.array); + ftb_compcap.array = zshcalloc(1024 * sizeof(char*)); + ftb_compcap.len = 0, ftb_compcap.size = 1024; + return 0; + } + if (ftb_compcap.array == NULL) { + zwarnnam(nam, "please initialize it first"); + return 1; + } + + // get paramaters + char **words = getaparam(args[0]), **dscrs = getaparam(args[1]), *opts = getsparam(args[2]); + if (!words || !dscrs || !opts) { + zwarnnam(nam, "wrong argument"); + return 1; + } + + char *bs = metafy("\2", 1, META_DUP), *nul = metafy("\0word\0", 6, META_DUP); + size_t dscrs_cnt = arrlen(dscrs); + + for (int i = 0; words[i]; i++) { + // TODO: replace '\n' + char* buffer = zshcalloc(256 * sizeof(char)); + char* dscr = i < dscrs_cnt ? dscrs[i] : words[i]; + + buffer = ftb_strcat(buffer, 5, dscr, bs, opts, nul, words[i]); + ftb_compcap.array[ftb_compcap.len++] = buffer; + + if (ftb_compcap.len == ftb_compcap.size) { + ftb_compcap.array + = zrealloc(ftb_compcap.array, (1024 + ftb_compcap.size) * sizeof(char*)); + ftb_compcap.size += 1024; + memset(ftb_compcap.array + ftb_compcap.size - 1024, 0, 1024 * sizeof(char*)); + } + } + + zsfree(bs); + zsfree(nul); + + return 0; +} + +// cat n string, return the pointer to the new string +// `size` is the size of dst +// dst will be reallocated if is not big enough +char* ftb_strcat(char* dst, int n, ...) +{ + va_list valist; + va_start(valist, n); + + char* final = zrealloc(dst, 128); + size_t size = 128, max_len = 128 - 1; + dst = final; + + for (int i = 0, idx = 0; i < n; i++) { + char* src = va_arg(valist, char*); + for (; *src != '\0'; dst++, src++, idx++) { + if (idx == max_len) { + size += size / 2; + final = zrealloc(final, size); + max_len = size - 1; + dst = &final[idx]; + } + *dst = *src; + } + } + *dst = '\0'; + va_end(valist); + + return final; +} + +// accept an +char** fzf_tab_colorize(char* file) +{ + // TODO: can avoid so many zalloc here? + file = unmeta(file); + + struct stat sb; + if (lstat(file, &sb) == -1) { + return NULL; + } + + const char* suffix = ""; + if (isset(opt_list_type)) { + suffix = get_suffix(file, &sb); + } + const char* color = get_color(file, &sb); + + char* symlink = ""; + const char* symcolor = ""; + if ((sb.st_mode & S_IFMT) == S_IFLNK) { + symlink = zalloc(PATH_MAX); + int end = readlink(file, symlink, PATH_MAX); + symlink[end] = '\0'; + if (stat(file, &sb) == -1) { + symcolor = mode_color[COL_OR]; + } else { + char tmp[PATH_MAX]; + realpath(file, tmp); + symcolor = get_color(file, &sb); + } + } + + char** reply = zshcalloc((4 + 1) * sizeof(char*)); + + if (strlen(color) != 0) { + reply[0] = zalloc(128); + reply[1] = zalloc(128); + sprintf(reply[0], "%s%s%s", mode_color[COL_LC], color, mode_color[COL_RC]); + sprintf(reply[1], "%s%s%s", mode_color[COL_LC], "0", mode_color[COL_RC]); + } else { + reply[0] = ztrdup(""); + reply[1] = ztrdup(""); + } + + reply[2] = ztrdup(suffix); + + if (symlink[0] != '\0') { + reply[3] = zalloc(PATH_MAX); + sprintf(reply[3], "%s%s%s%s%s%s%s", mode_color[COL_LC], symcolor, mode_color[COL_RC], + symlink, mode_color[COL_LC], "0", mode_color[COL_RC]); + free(symlink); + } else { + reply[3] = ztrdup(""); + } + for (int i = 0; i < 4; i++) { + reply[i] = metafy(reply[i], -1, META_REALLOC); + } + + return reply; +} + +static int bin_fzf_tab_candidates_generate(char* nam, char** args, Options ops, UNUSED(int func)) +{ + if (OPT_ISSET(ops, 'i')) { + // compile list_colors pattern + if (*args == NULL) { + zwarnnam(nam, "please specify an array"); + return 1; + } else { + char** array = getaparam(*args); + return compile_patterns(nam, array); + } + } + + char **ftb_compcap = getaparam("_ftb_compcap"), **group_colors = getaparam("group_colors"), + *default_color = getsparam("default_color"), *prefix = getsparam("prefix"); + + size_t group_colors_len = arrlen(group_colors); + size_t ftb_compcap_len = arrlen(ftb_compcap); + + char *bs = metafy("\b", 1, META_DUP), *nul = metafy("\0", 1, META_DUP), + *soh = metafy("\2", 1, META_DUP); + + char **candidates = zshcalloc(sizeof(char*) * (ftb_compcap_len + 1)), + *filepath = zshcalloc(PATH_MAX * sizeof(char)), *dpre = zshcalloc(128), + *dsuf = zshcalloc(128); + + char* first_word = zshcalloc(512 * sizeof(char)); + int same_word = 1; + + for (int i = 0; i < ftb_compcap_len; i++) { + char *word = "", *group = NULL, *realdir = NULL; + strcpy(dpre, ""); + strcpy(dsuf, ""); + + // extract all the variables what we need + char** compcap = sepsplit(ftb_compcap[i], soh, 1, 0); + char* desc = compcap[0]; + char** info = sepsplit(compcap[1], nul, 1, 0); + + for (int j = 0; info[j]; j += 2) { + if (!strcmp(info[j], "word")) { + word = info[j + 1]; + // unquote word + parse_subst_string(word); + remnulargs(word); + untokenize(word); + } else if (!strcmp(info[j], "group")) { + group = info[j + 1]; + } else if (!strcmp(info[j], "realdir")) { + realdir = info[j + 1]; + } + } + + // check if all the words are the same + if (i == 0) { + first_word = ftb_strcat(first_word, 1, word); + } else if (same_word && strcmp(word, first_word) != 0) { + same_word = 0; + } + + // add character and color to describe the type of the files + if (realdir) { + filepath = ftb_strcat(filepath, 2, realdir, word); + char** reply = fzf_tab_colorize(filepath); + if (reply != NULL) { + dpre = ftb_strcat(dpre, 2, reply[1], reply[0]); + if (reply[3][0] != '\0') { + dsuf = ftb_strcat(dsuf, 4, reply[1], reply[2], " -> ", reply[3]); + } else { + dsuf = ftb_strcat(dsuf, 2, reply[1], reply[2]); + } + if (dpre[0] != '\0') { + setiparam("colorful", 1); + } + freearray(reply); + } + } + + char* result = zshcalloc(256 * sizeof(char)); + + // add color to description if they have group index + if (group) { + // use strtol ? + int group_index = atoi(group); + char* color = group_index >= group_colors_len ? "" : group_colors[group_index - 1]; + // add prefix + result = ftb_strcat( + result, 11, group, bs, color, prefix, dpre, nul, group, bs, desc, nul, dsuf); + } else { + result = ftb_strcat(result, 6, default_color, dpre, nul, desc, nul, dsuf); + } + // quotedzputs(result, stdout); + // putchar('\n'); + candidates[i] = result; + + freearray(info); + freearray(compcap); + } + + setaparam("tcandidates", candidates); + setiparam("same_word", same_word); + zsfree(dpre); + zsfree(dsuf); + zsfree(filepath); + zsfree(first_word); + + return 0; +} + +static struct builtin bintab[] = { + BUILTIN("fzf-tab-compcap-generate", 0, bin_fzf_tab_compcap_generate, 0, -1, 0, "io", NULL), + BUILTIN("fzf-tab-candidates-generate", 0, bin_fzf_tab_candidates_generate, 0, -1, 0, "i", NULL), +}; + +static struct paramdef patab[] = { + STRPARAMDEF("FZF_TAB_MODULE_VERSION", &fzf_tab_module_version), +}; + +// clang-format off +static struct features module_features = { + bintab, sizeof(bintab) / sizeof(*bintab), + NULL, 0, + NULL, 0, + patab, sizeof(patab) / sizeof(*patab), + 0, +}; +// clang-format on + +int setup_(UNUSED(Module m)) { return 0; } + +int features_(Module m, char*** features) +{ + *features = featuresarray(m, &module_features); + return 0; +} + +int enables_(Module m, int** enables) { return handlefeatures(m, &module_features, enables); } + +int boot_(UNUSED(Module m)) +{ + fzf_tab_module_version = ztrdup("0.2.2"); + // different zsh version may have different value of list_type's index + // so query it dynamically + opt_list_type = optlookup("list_types"); + return 0; +} + +int cleanup_(UNUSED(Module m)) { return setfeatureenables(m, &module_features, NULL); } + +int finish_(UNUSED(Module m)) +{ + printf("fzf-tab module unloaded.\n"); + fflush(stdout); + return 0; +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/fzftab.mdd b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/fzftab.mdd new file mode 100644 index 00000000..371bb951 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/aloxaf/fzftab.mdd @@ -0,0 +1,7 @@ +name=aloxaf/fzftab +link=dynamic +load=no + +autofeatures="b:fzf-tab-colorize p:FZF_TAB_MODULE_VERSION" + +objects="fzftab.o" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/builtin.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/builtin.c new file mode 100644 index 00000000..93fa9112 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/builtin.c @@ -0,0 +1,7236 @@ +/* + * builtin.c - builtin commands + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +/* this is defined so we get the prototype for open_memstream */ +#define _GNU_SOURCE 1 + +#include "zsh.mdh" +#include "builtin.pro" + +/* Builtins in the main executable */ + +static struct builtin builtins[] = +{ + BIN_PREFIX("-", BINF_DASH), + BIN_PREFIX("builtin", BINF_BUILTIN), + BIN_PREFIX("command", BINF_COMMAND), + BIN_PREFIX("exec", BINF_EXEC), + BIN_PREFIX("noglob", BINF_NOGLOB), + BUILTIN("[", BINF_HANDLES_OPTS, bin_test, 0, -1, BIN_BRACKET, NULL, NULL), + BUILTIN(".", BINF_PSPECIAL, bin_dot, 1, -1, 0, NULL, NULL), + BUILTIN(":", BINF_PSPECIAL, bin_true, 0, -1, 0, NULL, NULL), + BUILTIN("alias", BINF_MAGICEQUALS | BINF_PLUSOPTS, bin_alias, 0, -1, 0, "Lgmrs", NULL), + BUILTIN("autoload", BINF_PLUSOPTS, bin_functions, 0, -1, 0, "dmktrRTUwWXz", "u"), + BUILTIN("bg", 0, bin_fg, 0, -1, BIN_BG, NULL, NULL), + BUILTIN("break", BINF_PSPECIAL, bin_break, 0, 1, BIN_BREAK, NULL, NULL), + BUILTIN("bye", 0, bin_break, 0, 1, BIN_EXIT, NULL, NULL), + BUILTIN("cd", BINF_SKIPINVALID | BINF_SKIPDASH | BINF_DASHDASHVALID, bin_cd, 0, 2, BIN_CD, "qsPL", NULL), + BUILTIN("chdir", BINF_SKIPINVALID | BINF_SKIPDASH | BINF_DASHDASHVALID, bin_cd, 0, 2, BIN_CD, "qsPL", NULL), + BUILTIN("continue", BINF_PSPECIAL, bin_break, 0, 1, BIN_CONTINUE, NULL, NULL), + BUILTIN("declare", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "AE:%F:%HL:%R:%TUZ:%afghi:%klmp:%rtuxz", NULL), + BUILTIN("dirs", 0, bin_dirs, 0, -1, 0, "clpv", NULL), + BUILTIN("disable", 0, bin_enable, 0, -1, BIN_DISABLE, "afmprs", NULL), + BUILTIN("disown", 0, bin_fg, 0, -1, BIN_DISOWN, NULL, NULL), + BUILTIN("echo", BINF_SKIPINVALID, bin_print, 0, -1, BIN_ECHO, "neE", "-"), + BUILTIN("emulate", 0, bin_emulate, 0, -1, 0, "lLR", NULL), + BUILTIN("enable", 0, bin_enable, 0, -1, BIN_ENABLE, "afmprs", NULL), + BUILTIN("eval", BINF_PSPECIAL, bin_eval, 0, -1, BIN_EVAL, NULL, NULL), + BUILTIN("exit", BINF_PSPECIAL, bin_break, 0, 1, BIN_EXIT, NULL, NULL), + BUILTIN("export", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "E:%F:%HL:%R:%TUZ:%afhi:%lp:%rtu", "xg"), + BUILTIN("false", 0, bin_false, 0, -1, 0, NULL, NULL), + /* + * We used to behave as if the argument to -e was optional. + * But that's actually not useful, so it's more consistent to + * cause an error. + */ + BUILTIN("fc", 0, bin_fc, 0, -1, BIN_FC, "aAdDe:EfiIlLmnpPrRt:W", NULL), + BUILTIN("fg", 0, bin_fg, 0, -1, BIN_FG, NULL, NULL), + BUILTIN("float", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "E:%F:%HL:%R:%Z:%ghlp:%rtux", "E"), + BUILTIN("functions", BINF_PLUSOPTS, bin_functions, 0, -1, 0, "kmMstTuUWx:z", NULL), + BUILTIN("getln", 0, bin_read, 0, -1, 0, "ecnAlE", "zr"), + BUILTIN("getopts", 0, bin_getopts, 2, -1, 0, NULL, NULL), + BUILTIN("hash", BINF_MAGICEQUALS, bin_hash, 0, -1, 0, "Ldfmrv", NULL), + +#ifdef ZSH_HASH_DEBUG + BUILTIN("hashinfo", 0, bin_hashinfo, 0, 0, 0, NULL, NULL), +#endif + + BUILTIN("history", 0, bin_fc, 0, -1, BIN_FC, "adDEfiLmnpPrt:", "l"), + BUILTIN("integer", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "HL:%R:%Z:%ghi:%lp:%rtux", "i"), + BUILTIN("jobs", 0, bin_fg, 0, -1, BIN_JOBS, "dlpZrs", NULL), + BUILTIN("kill", BINF_HANDLES_OPTS, bin_kill, 0, -1, 0, NULL, NULL), + BUILTIN("let", 0, bin_let, 1, -1, 0, NULL, NULL), + BUILTIN("local", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "AE:%F:%HL:%R:%TUZ:%ahi:%lp:%rtux", NULL), + BUILTIN("log", 0, bin_log, 0, 0, 0, NULL, NULL), + BUILTIN("logout", 0, bin_break, 0, 1, BIN_LOGOUT, NULL, NULL), + +#if defined(ZSH_MEM) & defined(ZSH_MEM_DEBUG) + BUILTIN("mem", 0, bin_mem, 0, 0, 0, "v", NULL), +#endif + +#if defined(ZSH_PAT_DEBUG) + BUILTIN("patdebug", 0, bin_patdebug, 1, -1, 0, "p", NULL), +#endif + + BUILTIN("popd", BINF_SKIPINVALID | BINF_SKIPDASH | BINF_DASHDASHVALID, bin_cd, 0, 1, BIN_POPD, "q", NULL), + BUILTIN("print", BINF_PRINTOPTS, bin_print, 0, -1, BIN_PRINT, "abcC:Df:ilmnNoOpPrRsSu:v:x:X:z-", NULL), + BUILTIN("printf", BINF_SKIPINVALID | BINF_SKIPDASH, bin_print, 1, -1, BIN_PRINTF, "v:", NULL), + BUILTIN("pushd", BINF_SKIPINVALID | BINF_SKIPDASH | BINF_DASHDASHVALID, bin_cd, 0, 2, BIN_PUSHD, "qsPL", NULL), + BUILTIN("pushln", 0, bin_print, 0, -1, BIN_PRINT, NULL, "-nz"), + BUILTIN("pwd", 0, bin_pwd, 0, 0, 0, "rLP", NULL), + BUILTIN("r", 0, bin_fc, 0, -1, BIN_R, "IlLnr", NULL), + BUILTIN("read", 0, bin_read, 0, -1, 0, "cd:ek:%lnpqrst:%zu:AE", NULL), + BUILTIN("readonly", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, BIN_READONLY, "AE:%F:%HL:%R:%TUZ:%afghi:%lptux", "r"), + BUILTIN("rehash", 0, bin_hash, 0, 0, 0, "df", "r"), + BUILTIN("return", BINF_PSPECIAL, bin_break, 0, 1, BIN_RETURN, NULL, NULL), + BUILTIN("set", BINF_PSPECIAL | BINF_HANDLES_OPTS, bin_set, 0, -1, 0, NULL, NULL), + BUILTIN("setopt", 0, bin_setopt, 0, -1, BIN_SETOPT, NULL, NULL), + BUILTIN("shift", BINF_PSPECIAL, bin_shift, 0, -1, 0, "p", NULL), + BUILTIN("source", BINF_PSPECIAL, bin_dot, 1, -1, 0, NULL, NULL), + BUILTIN("suspend", 0, bin_suspend, 0, 0, 0, "f", NULL), + BUILTIN("test", BINF_HANDLES_OPTS, bin_test, 0, -1, BIN_TEST, NULL, NULL), + BUILTIN("ttyctl", 0, bin_ttyctl, 0, 0, 0, "fu", NULL), + BUILTIN("times", BINF_PSPECIAL, bin_times, 0, 0, 0, NULL, NULL), + BUILTIN("trap", BINF_PSPECIAL | BINF_HANDLES_OPTS, bin_trap, 0, -1, 0, NULL, NULL), + BUILTIN("true", 0, bin_true, 0, -1, 0, NULL, NULL), + BUILTIN("type", 0, bin_whence, 0, -1, 0, "ampfsSw", "v"), + BUILTIN("typeset", BINF_PLUSOPTS | BINF_MAGICEQUALS | BINF_PSPECIAL | BINF_ASSIGN, (HandlerFunc)bin_typeset, 0, -1, 0, "AE:%F:%HL:%R:%TUZ:%afghi:%klp:%rtuxmz", NULL), + BUILTIN("umask", 0, bin_umask, 0, 1, 0, "S", NULL), + BUILTIN("unalias", 0, bin_unhash, 0, -1, BIN_UNALIAS, "ams", NULL), + BUILTIN("unfunction", 0, bin_unhash, 1, -1, BIN_UNFUNCTION, "m", "f"), + BUILTIN("unhash", 0, bin_unhash, 1, -1, BIN_UNHASH, "adfms", NULL), + BUILTIN("unset", BINF_PSPECIAL, bin_unset, 1, -1, BIN_UNSET, "fmv", NULL), + BUILTIN("unsetopt", 0, bin_setopt, 0, -1, BIN_UNSETOPT, NULL, NULL), + BUILTIN("wait", 0, bin_fg, 0, -1, BIN_WAIT, NULL, NULL), + BUILTIN("whence", 0, bin_whence, 0, -1, 0, "acmpvfsSwx:", NULL), + BUILTIN("where", 0, bin_whence, 0, -1, 0, "pmsSwx:", "ca"), + BUILTIN("which", 0, bin_whence, 0, -1, 0, "ampsSwx:", "c"), + BUILTIN("zmodload", 0, bin_zmodload, 0, -1, 0, "AFRILP:abcfdilmpsue", NULL), + BUILTIN("zcompile", 0, bin_zcompile, 0, -1, 0, "tUMRcmzka", NULL), +}; + +/****************************************/ +/* Builtin Command Hash Table Functions */ +/****************************************/ + +/* hash table containing builtin commands */ + +/**/ +mod_export HashTable builtintab; + +/**/ +void +createbuiltintable(void) +{ + builtintab = newhashtable(85, "builtintab", NULL); + + builtintab->hash = hasher; + builtintab->emptytable = NULL; + builtintab->filltable = NULL; + builtintab->cmpnodes = strcmp; + builtintab->addnode = addhashnode; + builtintab->getnode = gethashnode; + builtintab->getnode2 = gethashnode2; + builtintab->removenode = removehashnode; + builtintab->disablenode = disablehashnode; + builtintab->enablenode = enablehashnode; + builtintab->freenode = freebuiltinnode; + builtintab->printnode = printbuiltinnode; + + (void)addbuiltins("zsh", builtins, sizeof(builtins)/sizeof(*builtins)); +} + +/* Print a builtin */ + +/**/ +static void +printbuiltinnode(HashNode hn, int printflags) +{ + Builtin bn = (Builtin) hn; + + if (printflags & PRINT_WHENCE_WORD) { + printf("%s: builtin\n", bn->node.nam); + return; + } + + if (printflags & PRINT_WHENCE_CSH) { + printf("%s: shell built-in command\n", bn->node.nam); + return; + } + + if (printflags & PRINT_WHENCE_VERBOSE) { + printf("%s is a shell builtin\n", bn->node.nam); + return; + } + + /* default is name only */ + printf("%s\n", bn->node.nam); +} + +/**/ +static void +freebuiltinnode(HashNode hn) +{ + Builtin bn = (Builtin) hn; + + if(!(bn->node.flags & BINF_ADDED)) { + zsfree(bn->node.nam); + zsfree(bn->optstr); + zfree(bn, sizeof(struct builtin)); + } +} + +/**/ +void +init_builtins(void) +{ + if (!EMULATION(EMULATE_ZSH)) { + HashNode hn = reswdtab->getnode2(reswdtab, "repeat"); + if (hn) + reswdtab->disablenode(hn, 0); + } +} + +/* Make sure we have space for a new option and increment. */ + +#define OPT_ALLOC_CHUNK 16 + +/**/ +static int +new_optarg(Options ops) +{ + /* Argument index must be a non-zero 6-bit number. */ + if (ops->argscount == 63) + return 1; + if (ops->argsalloc == ops->argscount) { + char **newptr = + (char **)zhalloc((ops->argsalloc + OPT_ALLOC_CHUNK) * + sizeof(char *)); + if (ops->argsalloc) + memcpy(newptr, ops->args, ops->argsalloc * sizeof(char *)); + ops->args = newptr; + ops->argsalloc += OPT_ALLOC_CHUNK; + } + ops->argscount++; + return 0; +} + + +/* execute a builtin handler function after parsing the arguments */ + +/**/ +int +execbuiltin(LinkList args, LinkList assigns, Builtin bn) +{ + char *pp, *name, *optstr; + int flags, argc, execop, xtr = isset(XTRACE); + struct options ops; + + /* initialise options structure */ + memset(ops.ind, 0, MAX_OPS*sizeof(unsigned char)); + ops.args = NULL; + ops.argscount = ops.argsalloc = 0; + + /* initialize some local variables */ + name = (char *) ugetnode(args); + + if (!bn->handlerfunc) { + DPUTS(1, "Missing builtin detected too late"); + deletebuiltin(bn->node.nam); + return 1; + } + /* get some information about the command */ + flags = bn->node.flags; + optstr = bn->optstr; + + /* Set up the argument list. */ + /* count the arguments */ + argc = countlinknodes(args); + + { + /* + * Keep all arguments, including options, in an array. + * We don't actually need the option part of the argument + * after option processing, but it makes XTRACE output + * much simpler. + */ + VARARR(char *, argarr, argc + 1); + char **argv; + + /* + * Get the actual arguments, into argv. Remember argarr + * may be an array declaration, depending on the compiler. + */ + argv = argarr; + while ((*argv++ = (char *)ugetnode(args))); + argv = argarr; + + /* Sort out the options. */ + if (optstr) { + char *arg = *argv; + int sense; /* 1 for -x, 0 for +x */ + /* while arguments look like options ... */ + while (arg && + /* Must begin with - or maybe + */ + ((sense = (*arg == '-')) || + ((flags & BINF_PLUSOPTS) && *arg == '+'))) { + /* Digits aren't arguments unless the command says they are. */ + if (!(flags & BINF_KEEPNUM) && idigit(arg[1])) + break; + /* For cd and friends, a single dash is not an option. */ + if ((flags & BINF_SKIPDASH) && !arg[1]) + break; + if ((flags & BINF_DASHDASHVALID) && !strcmp(arg, "--")) { + /* + * Need to skip this before checking whether this is + * really an option. + */ + argv++; + break; + } + /* + * Unrecognised options to echo etc. are not really + * options. + * + * Note this flag is not smart enough to handle option + * arguments. In fact, ideally it shouldn't be added + * to any new builtins, to preserve standard option + * handling as much as possible. + */ + if (flags & BINF_SKIPINVALID) { + char *p = arg; + while (*++p && strchr(optstr, (int) *p)); + if (*p) + break; + } + /* handle -- or - (ops.ind['-']), and + + * (ops.ind['-'] and ops.ind['+']) */ + if (arg[1] == '-') + arg++; + if (!arg[1]) { + ops.ind['-'] = 1; + if (!sense) + ops.ind['+'] = 1; + } + /* save options in ops, as long as they are in bn->optstr */ + while (*++arg) { + char *optptr; + if ((optptr = strchr(optstr, execop = (int)*arg))) { + ops.ind[(int)*arg] = (sense) ? 1 : 2; + if (optptr[1] == ':') { + char *argptr = NULL; + if (optptr[2] == ':') { + if (arg[1]) + argptr = arg+1; + /* Optional argument in same word*/ + } else if (optptr[2] == '%') { + /* Optional numeric argument in same + * or next word. */ + if (arg[1] && idigit(arg[1])) + argptr = arg+1; + else if (argv[1] && idigit(*argv[1])) + argptr = arg = *++argv; + } else { + /* Mandatory argument */ + if (arg[1]) + argptr = arg+1; + else if ((arg = *++argv)) + argptr = arg; + else { + zwarnnam(name, "argument expected: -%c", + execop); + return 1; + } + } + if (argptr) { + if (new_optarg(&ops)) { + zwarnnam(name, + "too many option arguments"); + return 1; + } + ops.ind[execop] |= ops.argscount << 2; + ops.args[ops.argscount-1] = argptr; + while (arg[1]) + arg++; + } + } + } else + break; + } + /* The above loop may have exited on an invalid option. (We * + * assume that any option requiring metafication is invalid.) */ + if (*arg) { + if(*arg == Meta) + *++arg ^= 32; + zwarnnam(name, "bad option: %c%c", "+-"[sense], *arg); + return 1; + } + arg = *++argv; + /* for the "print" builtin, the options after -R are treated as + options to "echo" */ + if ((flags & BINF_PRINTOPTS) && ops.ind['R'] && + !ops.ind['f']) { + optstr = "ne"; + flags |= BINF_SKIPINVALID; + } + /* the option -- indicates the end of the options */ + if (ops.ind['-']) + break; + } + } else if (!(flags & BINF_HANDLES_OPTS) && *argv && + !strcmp(*argv, "--")) { + ops.ind['-'] = 1; + argv++; + } + + /* handle built-in options, for overloaded handler functions */ + if ((pp = bn->defopts)) { + while (*pp) { + /* only if not already set */ + if (!ops.ind[(int)*pp]) + ops.ind[(int)*pp] = 1; + pp++; + } + } + + /* Fix the argument count by subtracting option arguments */ + argc -= argv - argarr; + + if (errflag) { + errflag &= ~ERRFLAG_ERROR; + return 1; + } + + /* check that the argument count lies within the specified bounds */ + if (argc < bn->minargs || (argc > bn->maxargs && bn->maxargs != -1)) { + zwarnnam(name, (argc < bn->minargs) + ? "not enough arguments" : "too many arguments"); + return 1; + } + + /* display execution trace information, if required */ + if (xtr) { + /* Use full argument list including options for trace output */ + char **fullargv = argarr; + printprompt4(); + fprintf(xtrerr, "%s", name); + while (*fullargv) { + fputc(' ', xtrerr); + quotedzputs(*fullargv++, xtrerr); + } + if (assigns) { + LinkNode node; + for (node = firstnode(assigns); node; incnode(node)) { + Asgment asg = (Asgment)node; + fputc(' ', xtrerr); + quotedzputs(asg->name, xtrerr); + if (asg->flags & ASG_ARRAY) { + fprintf(xtrerr, "=("); + if (asg->value.array) { + if (asg->flags & ASG_KEY_VALUE) { + LinkNode keynode, valnode; + keynode = firstnode(asg->value.array); + for (;;) { + if (!keynode) + break; + valnode = nextnode(keynode); + if (!valnode) + break; + fputc('[', xtrerr); + quotedzputs((char *)getdata(keynode), + xtrerr); + fprintf(stderr, "]="); + quotedzputs((char *)getdata(valnode), + xtrerr); + keynode = nextnode(valnode); + } + } else { + LinkNode arrnode; + for (arrnode = firstnode(asg->value.array); + arrnode; + incnode(arrnode)) { + fputc(' ', xtrerr); + quotedzputs((char *)getdata(arrnode), + xtrerr); + } + } + } + fprintf(xtrerr, " )"); + } else if (asg->value.scalar) { + fputc('=', xtrerr); + quotedzputs(asg->value.scalar, xtrerr); + } + } + } + fputc('\n', xtrerr); + fflush(xtrerr); + } + /* call the handler function, and return its return value */ + if (flags & BINF_ASSIGN) + { + /* + * Takes two sets of arguments. + */ + HandlerFuncAssign assignfunc = (HandlerFuncAssign)bn->handlerfunc; + return (*(assignfunc)) (name, argv, assigns, &ops, bn->funcid); + } + else + { + return (*(bn->handlerfunc)) (name, argv, &ops, bn->funcid); + } + } +} + +/* Enable/disable an element in one of the internal hash tables. * + * With no arguments, it lists all the currently enabled/disabled * + * elements in that particular hash table. */ + +/**/ +int +bin_enable(char *name, char **argv, Options ops, int func) +{ + HashTable ht; + HashNode hn; + ScanFunc scanfunc; + Patprog pprog; + int flags1 = 0, flags2 = 0; + int match = 0, returnval = 0; + + /* Find out which hash table we are working with. */ + if (OPT_ISSET(ops,'p')) { + return pat_enables(name, argv, func == BIN_ENABLE); + } else if (OPT_ISSET(ops,'f')) + ht = shfunctab; + else if (OPT_ISSET(ops,'r')) + ht = reswdtab; + else if (OPT_ISSET(ops,'s')) + ht = sufaliastab; + else if (OPT_ISSET(ops,'a')) + ht = aliastab; + else + ht = builtintab; + + /* Do we want to enable or disable? */ + if (func == BIN_ENABLE) { + flags2 = DISABLED; + scanfunc = ht->enablenode; + } else { + flags1 = DISABLED; + scanfunc = ht->disablenode; + } + + /* Given no arguments, print the names of the enabled/disabled elements * + * in this hash table. If func == BIN_ENABLE, then scanhashtable will * + * print nodes NOT containing the DISABLED flag, else scanhashtable will * + * print nodes containing the DISABLED flag. */ + if (!*argv) { + queue_signals(); + scanhashtable(ht, 1, flags1, flags2, ht->printnode, 0); + unqueue_signals(); + return 0; + } + + /* With -m option, treat arguments as glob patterns. */ + if (OPT_ISSET(ops,'m')) { + for (; *argv; argv++) { + queue_signals(); + + /* parse pattern */ + tokenize(*argv); + if ((pprog = patcompile(*argv, PAT_STATIC, 0))) + match += scanmatchtable(ht, pprog, 0, 0, 0, scanfunc, 0); + else { + untokenize(*argv); + zwarnnam(name, "bad pattern : %s", *argv); + returnval = 1; + } + unqueue_signals(); + } + /* If we didn't match anything, we return 1. */ + if (!match) + returnval = 1; + return returnval; + } + + /* Take arguments literally -- do not glob */ + queue_signals(); + for (; *argv; argv++) { + if ((hn = ht->getnode2(ht, *argv))) { + scanfunc(hn, 0); + } else { + zwarnnam(name, "no such hash table element: %s", *argv); + returnval = 1; + } + } + unqueue_signals(); + return returnval; +} + +/* set: either set the shell options, or set the shell arguments, * + * or declare an array, or show various things */ + +/**/ +int +bin_set(char *nam, char **args, UNUSED(Options ops), UNUSED(int func)) +{ + int action, optno, array = 0, hadopt = 0, + hadplus = 0, hadend = 0, sort = 0; + char **x, *arrayname = NULL; + + /* Obsolescent sh compatibility: set - is the same as set +xv * + * and set - args is the same as set +xv -- args */ + if (!EMULATION(EMULATE_ZSH) && *args && **args == '-' && !args[0][1]) { + dosetopt(VERBOSE, 0, 0, opts); + dosetopt(XTRACE, 0, 0, opts); + if (!args[1]) + return 0; + } + + /* loop through command line options (begins with "-" or "+") */ + while (*args && (**args == '-' || **args == '+')) { + action = (**args == '-'); + hadplus |= !action; + if(!args[0][1]) + *args = "--"; + while (*++*args) { + if(**args == Meta) + *++*args ^= 32; + if(**args != '-' || action) + hadopt = 1; + /* The pseudo-option `--' signifies the end of options. */ + if (**args == '-') { + hadend = 1; + args++; + goto doneoptions; + } else if (**args == 'o') { + if (!*++*args) + args++; + if (!*args) { + printoptionstates(hadplus); + inittyptab(); + return 0; + } + if(!(optno = optlookup(*args))) + zerrnam(nam, "no such option: %s", *args); + else if(dosetopt(optno, action, 0, opts)) + zerrnam(nam, "can't change option: %s", *args); + break; + } else if(**args == 'A') { + if(!*++*args) + args++; + array = action ? 1 : -1; + arrayname = *args; + if (!arrayname) + goto doneoptions; + else if (!isset(KSHARRAYS)) + { + args++; + goto doneoptions; + } + break; + } else if (**args == 's') + sort = action ? 1 : -1; + else { + if (!(optno = optlookupc(**args))) + zerrnam(nam, "bad option: -%c", **args); + else if(dosetopt(optno, action, 0, opts)) + zerrnam(nam, "can't change option: -%c", **args); + } + } + args++; + } + if (errflag) + return 1; + doneoptions: + inittyptab(); + + /* Show the parameters, possibly with values */ + queue_signals(); + if (!arrayname) + { + if (!hadopt && !*args) + scanhashtable(paramtab, 1, 0, 0, paramtab->printnode, + hadplus ? PRINT_NAMEONLY : 0); + + if (array) { + /* display arrays */ + scanhashtable(paramtab, 1, PM_ARRAY, 0, paramtab->printnode, + hadplus ? PRINT_NAMEONLY : 0); + } + if (!*args && !hadend) { + unqueue_signals(); + return 0; + } + } + if (sort) + strmetasort(args, sort < 0 ? SORTIT_BACKWARDS : 0, NULL); + if (array) { + /* create an array with the specified elements */ + char **a = NULL, **y; + int len = arrlen(args); + + if (array < 0 && (a = getaparam(arrayname)) && arrlen_gt(a, len)) { + a += len; + len += arrlen(a); + } + for (x = y = zalloc((len + 1) * sizeof(char *)); len--;) { + if (!*args) + args = a; + *y++ = ztrdup(*args++); + } + *y++ = NULL; + setaparam(arrayname, x); + } else { + /* set shell arguments */ + freearray(pparams); + pparams = zarrdup(args); + } + unqueue_signals(); + return 0; +} + +/**** directory-handling builtins ****/ + +/**/ +int doprintdir = 0; /* set in exec.c (for autocd) */ + +/* pwd: display the name of the current directory */ + +/**/ +int +bin_pwd(UNUSED(char *name), UNUSED(char **argv), Options ops, UNUSED(int func)) +{ + if (OPT_ISSET(ops,'r') || OPT_ISSET(ops,'P') || + (isset(CHASELINKS) && !OPT_ISSET(ops,'L'))) + printf("%s\n", zgetcwd()); + else { + zputs(pwd, stdout); + putchar('\n'); + } + return 0; +} + +/* the directory stack */ + +/**/ +mod_export LinkList dirstack; + +/* dirs: list the directory stack, or replace it with a provided list */ + +/**/ +int +bin_dirs(UNUSED(char *name), char **argv, Options ops, UNUSED(int func)) +{ + LinkList l; + + queue_signals(); + /* with -v, -p or no arguments display the directory stack */ + if (!(*argv || OPT_ISSET(ops,'c')) || OPT_ISSET(ops,'v') || + OPT_ISSET(ops,'p')) { + LinkNode node; + char *fmt; + int pos = 1; + + /* with the -v option, display a numbered list, starting at zero */ + if (OPT_ISSET(ops,'v')) { + printf("0\t"); + fmt = "\n%d\t"; + /* with the -p option, display entries one per line */ + } else if (OPT_ISSET(ops,'p')) + fmt = "\n"; + else + fmt = " "; + if (OPT_ISSET(ops,'l')) + zputs(pwd, stdout); + else + fprintdir(pwd, stdout); + for (node = firstnode(dirstack); node; incnode(node)) { + printf(fmt, pos++); + if (OPT_ISSET(ops,'l')) + zputs(getdata(node), stdout); + else + fprintdir(getdata(node), stdout); + + } + unqueue_signals(); + putchar('\n'); + return 0; + } + /* replace the stack with the specified directories */ + l = znewlinklist(); + while (*argv) + zaddlinknode(l, ztrdup(*argv++)); + freelinklist(dirstack, freestr); + dirstack = l; + unqueue_signals(); + return 0; +} + +/* cd, chdir, pushd, popd */ + +/**/ +void +set_pwd_env(void) +{ + Param pm; + + /* update the PWD and OLDPWD shell parameters */ + + pm = (Param) paramtab->getnode(paramtab, "PWD"); + if (pm && PM_TYPE(pm->node.flags) != PM_SCALAR) { + pm->node.flags &= ~PM_READONLY; + unsetparam_pm(pm, 0, 1); + } + + pm = (Param) paramtab->getnode(paramtab, "OLDPWD"); + if (pm && PM_TYPE(pm->node.flags) != PM_SCALAR) { + pm->node.flags &= ~PM_READONLY; + unsetparam_pm(pm, 0, 1); + } + + assignsparam("PWD", ztrdup(pwd), 0); + assignsparam("OLDPWD", ztrdup(oldpwd), 0); + + pm = (Param) paramtab->getnode(paramtab, "PWD"); + if (!(pm->node.flags & PM_EXPORTED)) + addenv(pm, pwd); + pm = (Param) paramtab->getnode(paramtab, "OLDPWD"); + if (!(pm->node.flags & PM_EXPORTED)) + addenv(pm, oldpwd); +} + +/* set if we are resolving links to their true paths */ +static int chasinglinks; + +/* The main pwd changing function. The real work is done by other * + * functions. cd_get_dest() does the initial argument processing; * + * cd_do_chdir() actually changes directory, if possible; cd_new_pwd() * + * does the ancillary processing associated with actually changing * + * directory. */ + +/**/ +int +bin_cd(char *nam, char **argv, Options ops, int func) +{ + LinkNode dir; + struct stat st1, st2; + + if (isset(RESTRICTED)) { + zwarnnam(nam, "restricted"); + return 1; + } + doprintdir = (doprintdir == -1); + + chasinglinks = OPT_ISSET(ops,'P') || + (isset(CHASELINKS) && !OPT_ISSET(ops,'L')); + queue_signals(); + zpushnode(dirstack, ztrdup(pwd)); + if (!(dir = cd_get_dest(nam, argv, OPT_ISSET(ops,'s'), func))) { + zsfree(getlinknode(dirstack)); + unqueue_signals(); + return 1; + } + cd_new_pwd(func, dir, OPT_ISSET(ops, 'q')); + + if (stat(unmeta(pwd), &st1) < 0) { + setjobpwd(); + zsfree(pwd); + pwd = NULL; + pwd = metafy(zgetcwd(), -1, META_DUP); + } else if (stat(".", &st2) < 0) { + if (chdir(unmeta(pwd)) < 0) + zwarn("unable to chdir(%s): %e", pwd, errno); + } else if (st1.st_ino != st2.st_ino || st1.st_dev != st2.st_dev) { + if (chasinglinks) { + setjobpwd(); + zsfree(pwd); + pwd = NULL; + pwd = metafy(zgetcwd(), -1, META_DUP); + } else if (chdir(unmeta(pwd)) < 0) + zwarn("unable to chdir(%s): %e", pwd, errno); + } + unqueue_signals(); + return 0; +} + +/* Get directory to chdir to */ + +/**/ +static LinkNode +cd_get_dest(char *nam, char **argv, int hard, int func) +{ + LinkNode dir = NULL; + LinkNode target; + char *dest; + + if (!argv[0]) { + if (func == BIN_POPD && !nextnode(firstnode(dirstack))) { + zwarnnam(nam, "directory stack empty"); + return NULL; + } + if (func == BIN_PUSHD && unset(PUSHDTOHOME)) + dir = nextnode(firstnode(dirstack)); + if (dir) + zinsertlinknode(dirstack, dir, getlinknode(dirstack)); + else if (func != BIN_POPD) { + if (!home) { + zwarnnam(nam, "HOME not set"); + return NULL; + } + zpushnode(dirstack, ztrdup(home)); + } + } else if (!argv[1]) { + int dd; + char *end; + + doprintdir++; + if (argv[0][1] && (argv[0][0] == '+' || argv[0][0] == '-') + && strspn(argv[0]+1, "0123456789") == strlen(argv[0]+1)) { + dd = zstrtol(argv[0] + 1, &end, 10); + if (*end == '\0') { + if ((argv[0][0] == '+') ^ isset(PUSHDMINUS)) + for (dir = firstnode(dirstack); dir && dd; dd--, incnode(dir)); + else + for (dir = lastnode(dirstack); dir != (LinkNode) dirstack && dd; + dd--, dir = prevnode(dir)); + if (!dir || dir == (LinkNode) dirstack) { + zwarnnam(nam, "no such entry in dir stack"); + return NULL; + } + } + } + if (!dir) + zpushnode(dirstack, ztrdup(strcmp(argv[0], "-") + ? (doprintdir--, argv[0]) : oldpwd)); + } else { + char *u, *d; + int len1, len2, len3; + + if (!(u = strstr(pwd, argv[0]))) { + zwarnnam(nam, "string not in pwd: %s", argv[0]); + return NULL; + } + len1 = strlen(argv[0]); + len2 = strlen(argv[1]); + len3 = u - pwd; + d = (char *)zalloc(len3 + len2 + strlen(u + len1) + 1); + strncpy(d, pwd, len3); + strcpy(d + len3, argv[1]); + strcat(d, u + len1); + zpushnode(dirstack, d); + doprintdir++; + } + + target = dir; + if (func == BIN_POPD) { + if (!dir) { + target = dir = firstnode(dirstack); + } else if (dir != firstnode(dirstack)) { + return dir; + } + dir = nextnode(dir); + } + if (!dir) { + dir = firstnode(dirstack); + } + if (!dir || !getdata(dir)) { + DPUTS(1, "Directory not set, not detected early enough"); + return NULL; + } + if (!(dest = cd_do_chdir(nam, getdata(dir), hard))) { + if (!target) + zsfree(getlinknode(dirstack)); + if (func == BIN_POPD) + zsfree(remnode(dirstack, dir)); + return NULL; + } + if (dest != (char *)getdata(dir)) { + zsfree(getdata(dir)); + setdata(dir, dest); + } + return target ? target : dir; +} + +/* Change to given directory, if possible. This function works out * + * exactly how the directory should be interpreted, including cdpath * + * and CDABLEVARS. For each possible interpretation of the given * + * path, this calls cd_try_chdir(), which attempts to chdir to that * + * particular path. */ + +/**/ +static char * +cd_do_chdir(char *cnam, char *dest, int hard) +{ + char **pp, *ret; + int hasdot = 0, eno = ENOENT; + /* + * nocdpath indicates that cdpath should not be used. + * This is the case iff dest is a relative path + * whose first segment is . or .., but if the path is + * absolute then cdpath won't be used anyway. + */ + int nocdpath; +#ifdef __CYGWIN__ + /* + * Normalize path under Cygwin to avoid messing with + * DOS style names with drives in them + */ + static char buf[PATH_MAX+1]; +#ifdef HAVE_CYGWIN_CONV_PATH + cygwin_conv_path(CCP_WIN_A_TO_POSIX | CCP_RELATIVE, dest, buf, + PATH_MAX); +#else +#ifndef _SYS_CYGWIN_H + void cygwin_conv_to_posix_path(const char *, char *); +#endif + + cygwin_conv_to_posix_path(dest, buf); +#endif + dest = buf; +#endif + nocdpath = dest[0] == '.' && + (dest[1] == '/' || !dest[1] || (dest[1] == '.' && + (dest[2] == '/' || !dest[2]))); + + /* + * If we have an absolute path, use it as-is only + */ + if (*dest == '/') { + if ((ret = cd_try_chdir(NULL, dest, hard))) + return ret; + zwarnnam(cnam, "%e: %s", errno, dest); + return NULL; + } + + /* + * If cdpath is being used, check it for ".". + * Don't bother doing this if POSIXCD is set, we don't + * need to know (though it doesn't actually matter). + */ + if (!nocdpath && !isset(POSIXCD)) + for (pp = cdpath; *pp; pp++) + if (!(*pp)[0] || ((*pp)[0] == '.' && (*pp)[1] == '\0')) + hasdot = 1; + /* + * If + * (- there is no . in cdpath + * - or cdpath is not being used) + * - and the POSIXCD option is not set + * try the directory as-is (i.e. from .) + */ + if (!hasdot && !isset(POSIXCD)) { + if ((ret = cd_try_chdir(NULL, dest, hard))) + return ret; + if (errno != ENOENT) + eno = errno; + } + /* if cdpath is being used, try given directory relative to each element in + cdpath in turn */ + if (!nocdpath) + for (pp = cdpath; *pp; pp++) { + if ((ret = cd_try_chdir(*pp, dest, hard))) { + if (isset(POSIXCD)) { + /* + * For POSIX we need to print the directory + * any time CDPATH was used, except in the + * special case of an empty segment being + * treated as a ".". + */ + if (**pp) + doprintdir++; + } else { + if (strcmp(*pp, ".")) { + doprintdir++; + } + } + return ret; + } + if (errno != ENOENT) + eno = errno; + } + /* + * POSIX requires us to check "." after CDPATH rather than before. + */ + if (isset(POSIXCD)) { + if ((ret = cd_try_chdir(NULL, dest, hard))) + return ret; + if (errno != ENOENT) + eno = errno; + } + + /* handle the CDABLEVARS option */ + if ((ret = cd_able_vars(dest))) { + if ((ret = cd_try_chdir(NULL, ret,hard))) { + doprintdir++; + return ret; + } + if (errno != ENOENT) + eno = errno; + } + + /* If we got here, it means that we couldn't chdir to any of the + multitudinous possible paths allowed by zsh. We've run out of options! + Add more here! */ + zwarnnam(cnam, "%e: %s", eno, dest); + return NULL; +} + +/* If the CDABLEVARS option is set, return the new * + * interpretation of the given path. */ + +/**/ +char * +cd_able_vars(char *s) +{ + char *rest, save; + + if (isset(CDABLEVARS)) { + for (rest = s; *rest && *rest != '/'; rest++); + save = *rest; + *rest = 0; + s = getnameddir(s); + *rest = save; + + if (s && *rest) + s = dyncat(s, rest); + + return s; + } + return NULL; +} + +/* Attempt to change to a single given directory. The directory, * + * for the convenience of the calling function, may be provided in * + * two parts, which must be concatenated before attempting to chdir. * + * Returns NULL if the chdir fails. If the directory change is * + * possible, it is performed, and a pointer to the new full pathname * + * is returned. */ + +/**/ +static char * +cd_try_chdir(char *pfix, char *dest, int hard) +{ + char *buf; + int dlen, dochaselinks = 0; + + /* handle directory prefix */ + if (pfix && *pfix) { + if (*pfix == '/') { +#ifdef __CYGWIN__ +/* NB: Don't turn "/"+"bin" into "//"+"bin" by mistake! "//bin" may * + * not be what user really wants (probably wants "/bin"), but * + * "//bin" could be valid too (see fixdir())! This is primarily for * + * handling CDPATH correctly. Likewise for "//"+"bin" not becoming * + * "///bin" (aka "/bin"). */ + int root = pfix[1] == '\0' || (pfix[1] == '/' && pfix[2] == '\0'); + buf = tricat(pfix, ( root ? "" : "/" ), dest); +#else + buf = tricat(pfix, "/", dest); +#endif + } else { + int pfl = strlen(pfix); + dlen = strlen(pwd); + if (dlen == 1 && *pwd == '/') + dlen = 0; + buf = zalloc(dlen + pfl + strlen(dest) + 3); + if (dlen) + strcpy(buf, pwd); + buf[dlen] = '/'; + strcpy(buf + dlen + 1, pfix); + buf[dlen + 1 + pfl] = '/'; + strcpy(buf + dlen + pfl + 2, dest); + } + } else if (*dest == '/') + buf = ztrdup(dest); + else { + dlen = strlen(pwd); + if (pwd[dlen-1] == '/') + --dlen; + buf = zalloc(dlen + strlen(dest) + 2); + strcpy(buf, pwd); + buf[dlen] = '/'; + strcpy(buf + dlen + 1, dest); + } + + /* Normalise path. See the definition of fixdir() for what this means. + * We do not do this if we are chasing links. + */ + if (!chasinglinks) + dochaselinks = fixdir(buf); + else + unmetafy(buf, &dlen); + + /* We try the full path first. If that fails, try the + * argument to cd relatively. This is useful if the cwd + * or a parent directory is renamed in the interim. + */ + if (lchdir(buf, NULL, hard) && + (pfix || *dest == '/' || lchdir(unmeta(dest), NULL, hard))) { + free(buf); + return NULL; + } + /* the chdir succeeded, so decide if we should force links to be chased */ + if (dochaselinks) + chasinglinks = 1; + return metafy(buf, -1, META_NOALLOC); +} + +/* do the extra processing associated with changing directory */ + +/**/ +static void +cd_new_pwd(int func, LinkNode dir, int quiet) +{ + char *new_pwd, *s; + int dirstacksize; + + if (func == BIN_PUSHD) + rolllist(dirstack, dir); + new_pwd = remnode(dirstack, dir); + + if (func == BIN_POPD && firstnode(dirstack)) { + zsfree(new_pwd); + new_pwd = getlinknode(dirstack); + } else if (func == BIN_CD && unset(AUTOPUSHD)) + zsfree(getlinknode(dirstack)); + + if (chasinglinks) { + s = findpwd(new_pwd); + if (s) { + zsfree(new_pwd); + new_pwd = s; + } + } + if (isset(PUSHDIGNOREDUPS)) { + LinkNode n; + for (n = firstnode(dirstack); n; incnode(n)) { + if (!strcmp(new_pwd, getdata(n))) { + zsfree(remnode(dirstack, n)); + break; + } + } + } + + /* shift around the pwd variables, to make oldpwd and pwd relate to the + current (i.e. new) pwd */ + zsfree(oldpwd); + oldpwd = pwd; + setjobpwd(); + pwd = new_pwd; + set_pwd_env(); + + if (isset(INTERACTIVE) || isset(POSIXCD)) { + if (func != BIN_CD && isset(INTERACTIVE)) { + if (unset(PUSHDSILENT) && !quiet) + printdirstack(); + } else if (doprintdir) { + fprintdir(pwd, stdout); + putchar('\n'); + } + } + + /* execute the chpwd function */ + fflush(stdout); + fflush(stderr); + if (!quiet) + callhookfunc("chpwd", NULL, 1, NULL); + + dirstacksize = getiparam("DIRSTACKSIZE"); + /* handle directory stack sizes out of range */ + if (dirstacksize > 0) { + int remove = countlinknodes(dirstack) - + (dirstacksize < 2 ? 2 : dirstacksize); + while (remove-- >= 0) + zsfree(remnode(dirstack, lastnode(dirstack))); + } +} + +/* Print the directory stack */ + +/**/ +static void +printdirstack(void) +{ + LinkNode node; + + fprintdir(pwd, stdout); + for (node = firstnode(dirstack); node; incnode(node)) { + putchar(' '); + fprintdir(getdata(node), stdout); + } + putchar('\n'); +} + +/* Normalise a path. Segments consisting of ., and foo/.. * + * combinations, are removed and the path is unmetafied. + * Returns 1 if we found a ../ path which should force links to + * be chased, 0 otherwise. + */ + +/**/ +int +fixdir(char *src) +{ + char *dest = src, *d0 = dest; +#ifdef __CYGWIN__ + char *s0 = src; +#endif + /* This function is always called with n path containing at + * least one slash, either because one was input by the user or + * because the caller has prepended either pwd or a cdpath dir. + * If asked to make a relative change and pwd is set to ".", + * the current directory has been removed out from under us, + * so force links to be chased. + * + * Ordinarily we can't get here with "../" as the first component + * but handle the silly special case of ".." in cdpath. + * + * Order of comparisons here looks funny, but it short-circuits + * most rapidly in the event of a false condition. Set to 2 + * here so we still obey the (lack of) CHASEDOTS option after + * the first "../" is preserved (test chasedots > 1 below). + */ + int chasedots = (src[0] == '.' && pwd[0] == '.' && pwd[1] == '\0' && + (src[1] == '/' || (src[1] == '.' && src[2] == '/'))) * 2; + +/*** if have RFS superroot directory ***/ +#ifdef HAVE_SUPERROOT + /* allow /.. segments to remain */ + while (*src == '/' && src[1] == '.' && src[2] == '.' && + (!src[3] || src[3] == '/')) { + *dest++ = '/'; + *dest++ = '.'; + *dest++ = '.'; + src += 3; + } +#endif + + for (;;) { + /* compress multiple /es into single */ + if (*src == '/') { +#ifdef __CYGWIN__ + /* allow leading // under cygwin, but /// still becomes / */ + if (src == s0 && src[1] == '/' && src[2] != '/') + *dest++ = *src++; +#endif + *dest++ = *src++; + while (*src == '/') + src++; + } + /* if we are at the end of the input path, remove a trailing / (if it + exists), and return ct */ + if (!*src) { + while (dest > d0 + 1 && dest[-1] == '/') + dest--; + *dest = '\0'; + return chasedots; + } + if (src[0] == '.' && src[1] == '.' && + (src[2] == '\0' || src[2] == '/')) { + if (isset(CHASEDOTS) || chasedots > 1) { + chasedots = 1; + /* and treat as normal path segment */ + } else { + if (dest > d0 + 1) { + /* + * remove a foo/.. combination: + * first check foo exists, else return. + */ + struct stat st; + *dest = '\0'; + if (stat(d0, &st) < 0 || !S_ISDIR(st.st_mode)) { + char *ptrd, *ptrs; + if (dest == src) + *dest = '.'; + for (ptrs = src, ptrd = dest; *ptrs; ptrs++, ptrd++) + *ptrd = (*ptrs == Meta) ? (*++ptrs ^ 32) : *ptrs; + *ptrd = '\0'; + return 1; + } + for (dest--; dest > d0 + 1 && dest[-1] != '/'; dest--); + if (dest[-1] != '/') + dest--; + } + src++; + while (*++src == '/'); + continue; + } + } + if (src[0] == '.' && (src[1] == '/' || src[1] == '\0')) { + /* skip a . section */ + while (*++src == '/'); + } else { + /* copy a normal segment into the output */ + while (*src != '/' && *src != '\0') + if ((*dest++ = *src++) == Meta) + dest[-1] = *src++ ^ 32; + } + } + /* unreached */ +} + +/**/ +mod_export void +printqt(char *str) +{ + /* Print str, but turn any single quote into '\'' or ''. */ + for (; *str; str++) + if (*str == '\'') + printf(isset(RCQUOTES) ? "''" : "'\\''"); + else + putchar(*str); +} + +/**/ +mod_export void +printif(char *str, int c) +{ + /* If flag c has an argument, print that */ + if (str) { + printf(" -%c ", c); + quotedzputs(str, stdout); + } +} + +/**** history list functions ****/ + +/* fc, history, r */ + +/**/ +int +bin_fc(char *nam, char **argv, Options ops, int func) +{ + zlong first = -1, last = -1; + int retval; + char *s; + struct asgment *asgf = NULL, *asgl = NULL; + Patprog pprog = NULL; + + /* fc is only permitted in interactive shells */ +#ifdef FACIST_INTERACTIVE + if (!interact) { + zwarnnam(nam, "not interactive shell"); + return 1; + } +#endif + if (OPT_ISSET(ops,'p')) { + char *hf = ""; + zlong hs = DEFAULT_HISTSIZE; + zlong shs = 0; + int level = OPT_ISSET(ops,'a') ? locallevel : -1; + if (*argv) { + hf = *argv++; + if (*argv) { + char *check; + hs = zstrtol(*argv++, &check, 10); + if (*check) { + zwarnnam("fc", "HISTSIZE must be an integer"); + return 1; + } + if (*argv) { + shs = zstrtol(*argv++, &check, 10); + if (*check) { + zwarnnam("fc", "SAVEHIST must be an integer"); + return 1; + } + } else + shs = hs; + if (*argv) { + zwarnnam("fc", "too many arguments"); + return 1; + } + } else { + hs = histsiz; + shs = savehistsiz; + } + } + if (!pushhiststack(hf, hs, shs, level)) + return 1; + if (*hf) { + struct stat st; + if (stat(hf, &st) >= 0 || errno != ENOENT) + readhistfile(hf, 1, HFILE_USE_OPTIONS); + } + return 0; + } + if (OPT_ISSET(ops,'P')) { + if (*argv) { + zwarnnam("fc", "too many arguments"); + return 1; + } + return !saveandpophiststack(-1, HFILE_USE_OPTIONS); + } + /* with the -m option, the first argument is taken * + * as a pattern that history lines have to match */ + if (*argv && OPT_ISSET(ops,'m')) { + tokenize(*argv); + if (!(pprog = patcompile(*argv++, 0, NULL))) { + zwarnnam(nam, "invalid match pattern"); + return 1; + } + } + queue_signals(); + if (OPT_ISSET(ops,'R')) { + /* read history from a file */ + readhistfile(*argv, 1, OPT_ISSET(ops,'I') ? HFILE_SKIPOLD : 0); + unqueue_signals(); + return 0; + } + if (OPT_ISSET(ops,'W')) { + /* write history to a file */ + savehistfile(*argv, 1, OPT_ISSET(ops,'I') ? HFILE_SKIPOLD : 0); + unqueue_signals(); + return 0; + } + if (OPT_ISSET(ops,'A')) { + /* append history to a file */ + savehistfile(*argv, 1, HFILE_APPEND | + (OPT_ISSET(ops,'I') ? HFILE_SKIPOLD : 0)); + unqueue_signals(); + return 0; + } + + if (zleactive) { + unqueue_signals(); + zwarnnam(nam, "no interactive history within ZLE"); + return 1; + } + + /* put foo=bar type arguments into the substitution list */ + while (*argv && equalsplit(*argv, &s)) { + Asgment a = (Asgment) zhalloc(sizeof *a); + + if (!**argv) { + zwarnnam(nam, "invalid replacement pattern: =%s", s); + return 1; + } + if (!asgf) + asgf = asgl = a; + else { + asgl->node.next = &a->node; + asgl = a; + } + a->name = *argv; + a->flags = 0; + a->value.scalar = s; + a->node.next = a->node.prev = NULL; + argv++; + } + /* interpret and check first history line specifier */ + if (*argv) { + first = fcgetcomm(*argv); + if (first == -1) { + unqueue_signals(); + return 1; + } + argv++; + } + /* interpret and check second history line specifier */ + if (*argv) { + last = fcgetcomm(*argv); + if (last == -1) { + unqueue_signals(); + return 1; + } + argv++; + } + /* There is a maximum of two history specifiers. At least, there * + * will be as long as the history list is one-dimensional. */ + if (*argv) { + unqueue_signals(); + zwarnnam("fc", "too many arguments"); + return 1; + } + /* default values of first and last, and range checking */ + if (last == -1) { + if (OPT_ISSET(ops,'l') && first < curhist) { + /* + * When listing base our calculations on curhist, + * to show anything added since the edited history line. + * Also, in that case curhist will have been modified + * past the current history line; then we want to + * show everything, because the user expects to + * see the result of "print -s". Otherwise, we subtract + * -1 from the line, because the user doesn't usually expect + * to see the command line that caused history to be + * listed. + */ + last = (curline.histnum == curhist) ? addhistnum(curhist,-1,0) + : curhist; + if (last < firsthist()) + last = firsthist(); + } + else + last = first; + } + if (first == -1) { + /* + * When listing, we want to see everything that's been + * added to the history, including by print -s, so use + * curhist. + * When reexecuting, we want to restrict to the last edited + * command line to avoid giving the user a nasty turn + * if some helpful soul ran "print -s 'rm -rf /'". + */ + first = OPT_ISSET(ops,'l')? addhistnum(curhist,-16,0) + : addhistnum(curline.histnum,-1,0); + if (first < 1) + first = 1; + if (last < first) + last = first; + } + if (OPT_ISSET(ops,'l')) { + /* list the required part of the history */ + retval = fclist(stdout, ops, first, last, asgf, pprog, 0); + unqueue_signals(); + } + else { + /* edit history file, and (if successful) use the result as a new command */ + int tempfd; + FILE *out; + char *fil; + + retval = 1; + if ((tempfd = gettempfile(NULL, 1, &fil)) < 0 + || ((out = fdopen(tempfd, "w")) == NULL)) { + unqueue_signals(); + zwarnnam("fc", "can't open temp file: %e", errno); + } else { + /* + * Nasty behaviour results if we use the current history + * line here. Treat it as if it doesn't exist, unless + * that gives us an empty range. + */ + if (last >= curhist) { + last = curhist - 1; + if (first > last) { + unqueue_signals(); + zwarnnam("fc", + "current history line would recurse endlessly, aborted"); + fclose(out); + unlink(fil); + return 1; + } + } + ops->ind['n'] = 1; /* No line numbers here. */ + if (!fclist(out, ops, first, last, asgf, pprog, 1)) { + char *editor; + + if (func == BIN_R) + editor = "-"; + else if (OPT_HASARG(ops, 'e')) + editor = OPT_ARG(ops, 'e'); + else + editor = getsparam("FCEDIT"); + if (!editor) + editor = getsparam("EDITOR"); + if (!editor) + editor = DEFAULT_FCEDIT; + + unqueue_signals(); + if (fcedit(editor, fil)) { + if (stuff(fil)) + zwarnnam("fc", "%e: %s", errno, fil); + else { + loop(0,1); + retval = lastval; + } + } + } else + unqueue_signals(); + } + unlink(fil); + } + return retval; +} + +/* History handling functions: these are called by ZLE, as well as * + * the actual builtins. fcgetcomm() gets a history line, specified * + * either by number or leading string. fcsubs() performs a given * + * set of simple old=new substitutions on a given command line. * + * fclist() outputs a given range of history lines to a text file. */ + +/* get the history event associated with s */ + +/**/ +static zlong +fcgetcomm(char *s) +{ + zlong cmd; + + /* First try to match a history number. Negative * + * numbers indicate reversed numbering. */ + if ((cmd = atoi(s)) != 0 || *s == '0') { + if (cmd < 0) + cmd = addhistnum(curline.histnum,cmd,HIST_FOREIGN); + if (cmd < 0) + cmd = 0; + return cmd; + } + /* not a number, so search by string */ + cmd = hcomsearch(s); + if (cmd == -1) + zwarnnam("fc", "event not found: %s", s); + return cmd; +} + +/* Perform old=new substitutions. Uses the asgment structure from zsh.h, * + * which is essentially a linked list of string,replacement pairs. */ + +/**/ +static int +fcsubs(char **sp, struct asgment *sub) +{ + char *oldstr, *newstr, *oldpos, *newpos, *newmem, *s = *sp; + int subbed = 0; + + /* loop through the linked list */ + while (sub) { + oldstr = sub->name; + newstr = sub->value.scalar; + sub = (Asgment)sub->node.next; + oldpos = s; + /* loop over occurences of oldstr in s, replacing them with newstr */ + while ((newpos = (char *)strstr(oldpos, oldstr))) { + newmem = (char *) zhalloc(1 + (newpos - s) + + strlen(newstr) + strlen(newpos + strlen(oldstr))); + ztrncpy(newmem, s, newpos - s); + strcat(newmem, newstr); + oldpos = newmem + strlen(newmem); + strcat(newmem, newpos + strlen(oldstr)); + s = newmem; + subbed = 1; + } + } + *sp = s; + return subbed; +} + +/* Print a series of history events to a file. The file pointer is * + * given by f, and the required range of events by first and last. * + * subs is an optional list of foo=bar substitutions to perform on the * + * history lines before output. com is an optional comp structure * + * that the history lines are required to match. n, r, D and d are * + * options: n indicates that each line should be numbered. r indicates * + * that the lines should be output in reverse order (newest first). * + * D indicates that the real time taken by each command should be * + * output. d indicates that the time of execution of each command * + * should be output; d>1 means that the date should be output too; d>3 * + * means that mm/dd/yyyy form should be used for the dates, as opposed * + * to dd.mm.yyyy form; d>7 means that yyyy-mm-dd form should be used. */ + +/**/ +static int +fclist(FILE *f, Options ops, zlong first, zlong last, + struct asgment *subs, Patprog pprog, int is_command) +{ + int fclistdone = 0, xflags = 0; + zlong tmp; + char *s, *tdfmt, *timebuf; + Histent ent; + + /* reverse range if required */ + if (OPT_ISSET(ops,'r')) { + tmp = last; + last = first; + first = tmp; + } + if (is_command && first > last) { + zwarnnam("fc", "history events can't be executed backwards, aborted"); + if (f != stdout) + fclose(f); + return 1; + } + + ent = gethistent(first, first < last? GETHIST_DOWNWARD : GETHIST_UPWARD); + if (!ent || (first < last? ent->histnum > last : ent->histnum < last)) { + if (first == last) { + char buf[DIGBUFSIZE]; + convbase(buf, first, 10); + zwarnnam("fc", "no such event: %s", buf); + } else + zwarnnam("fc", "no events in that range"); + if (f != stdout) + fclose(f); + return 1; + } + + if (OPT_ISSET(ops,'d') || OPT_ISSET(ops,'f') || + OPT_ISSET(ops,'E') || OPT_ISSET(ops,'i') || + OPT_ISSET(ops,'t')) { + if (OPT_ISSET(ops,'t')) { + tdfmt = OPT_ARG(ops,'t'); + } else if (OPT_ISSET(ops,'i')) { + tdfmt = "%Y-%m-%d %H:%M"; + } else if (OPT_ISSET(ops,'E')) { + tdfmt = "%f.%-m.%Y %H:%M"; + } else if (OPT_ISSET(ops,'f')) { + tdfmt = "%-m/%f/%Y %H:%M"; + } else { + tdfmt = "%H:%M"; + } + timebuf = zhalloc(256); + } else { + tdfmt = timebuf = NULL; + } + + /* xflags exclude events */ + if (OPT_ISSET(ops,'L')) { + xflags |= HIST_FOREIGN; + } + if (OPT_ISSET(ops,'I')) { + xflags |= HIST_READ; + } + + for (;;) { + if (ent->node.flags & xflags) + s = NULL; + else + s = dupstring(ent->node.nam); + /* this if does the pattern matching, if required */ + if (s && (!pprog || pattry(pprog, s))) { + /* perform substitution */ + fclistdone |= (subs ? fcsubs(&s, subs) : 1); + + /* do numbering */ + if (!OPT_ISSET(ops,'n')) { + char buf[DIGBUFSIZE]; + convbase(buf, ent->histnum, 10); + fprintf(f, "%5s%c ", buf, + ent->node.flags & HIST_FOREIGN ? '*' : ' '); + } + /* output actual time (and possibly date) of execution of the + command, if required */ + if (tdfmt != NULL) { + struct tm *ltm; + int len; + ltm = localtime(&ent->stim); + if ((len = ztrftime(timebuf, 256, tdfmt, ltm, 0L)) >= 0) { + fwrite(timebuf, 1, len, f); + fprintf(f, " "); + } + } + /* display the time taken by the command, if required */ + if (OPT_ISSET(ops,'D')) { + long diff; + diff = (ent->ftim) ? ent->ftim - ent->stim : 0; + fprintf(f, "%ld:%02ld ", diff / 60, diff % 60); + } + + /* output the command */ + if (f == stdout) { + nicezputs(s, f); + putc('\n', f); + } else { + int len; + unmetafy(s, &len); + fwrite(s, 1, len, f); + putc('\n', f); + } + } + /* move on to the next history line, or quit the loop */ + if (first < last) { + if (!(ent = down_histent(ent)) || ent->histnum > last) + break; + } + else { + if (!(ent = up_histent(ent)) || ent->histnum < last) + break; + } + } + + /* final processing */ + if (f != stdout) + fclose(f); + if (!fclistdone) { + if (subs) + zwarnnam("fc", "no substitutions performed"); + else if (xflags || pprog) + zwarnnam("fc", "no matching events found"); + return 1; + } + return 0; +} + +/* edit a history file */ + +/**/ +static int +fcedit(char *ename, char *fn) +{ + char *s; + + if (!strcmp(ename, "-")) + return 1; + + s = tricat(ename, " ", fn); + execstring(s, 1, 0, "fc"); + zsfree(s); + + return !lastval; +} + +/**** parameter builtins ****/ + +/* Separate an argument into name=value parts, returning them in an * + * asgment structure. Because the asgment structure used is global, * + * only one of these can be active at a time. The string s gets placed * + * in this global structure, so it needs to be in permanent memory. */ + +/**/ +static Asgment +getasg(char ***argvp, LinkList assigns) +{ + char *s = **argvp; + static struct asgment asg; + + /* sanity check for valid argument */ + if (!s) { + if (assigns) { + Asgment asgp = (Asgment)firstnode(assigns); + if (!asgp) + return NULL; + (void)uremnode(assigns, &asgp->node); + return asgp; + } + return NULL; + } + + /* check if name is empty */ + if (*s == '=') { + zerr("bad assignment"); + return NULL; + } + asg.name = s; + asg.flags = 0; + + /* search for `=' */ + for (; *s && *s != '='; s++); + + /* found `=', so return with a value */ + if (*s) { + *s = '\0'; + asg.value.scalar = s + 1; + } else { + /* didn't find `=', so we only have a name */ + asg.value.scalar = NULL; + } + (*argvp)++; + return &asg; +} + +/* for new special parameters */ +enum { + NS_NONE, + NS_NORMAL, + NS_SECONDS +}; + +static const struct gsu_scalar tiedarr_gsu = +{ tiedarrgetfn, tiedarrsetfn, tiedarrunsetfn }; + +/* Install a base if we are turning on a numeric option with an argument */ + +static int +typeset_setbase(const char *name, Param pm, Options ops, int on, int always) +{ + char *arg = NULL; + + if ((on & PM_INTEGER) && OPT_HASARG(ops,'i')) + arg = OPT_ARG(ops,'i'); + else if ((on & PM_EFLOAT) && OPT_HASARG(ops,'E')) + arg = OPT_ARG(ops,'E'); + else if ((on & PM_FFLOAT) && OPT_HASARG(ops,'F')) + arg = OPT_ARG(ops,'F'); + + if (arg) { + char *eptr; + int base = (int)zstrtol(arg, &eptr, 10); + if (*eptr) { + if (on & PM_INTEGER) + zwarnnam(name, "bad base value: %s", arg); + else + zwarnnam(name, "bad precision value: %s", arg); + return 1; + } + if ((on & PM_INTEGER) && (base < 2 || base > 36)) { + zwarnnam(name, "invalid base (must be 2 to 36 inclusive): %d", + base); + return 1; + } + pm->base = base; + } else if (always) + pm->base = 0; + + return 0; +} + +/* Install a width if we are turning on a padding option with an argument */ + +static int +typeset_setwidth(const char * name, Param pm, Options ops, int on, int always) +{ + char *arg = NULL; + + if ((on & PM_LEFT) && OPT_HASARG(ops,'L')) + arg = OPT_ARG(ops,'L'); + else if ((on & PM_RIGHT_B) && OPT_HASARG(ops,'R')) + arg = OPT_ARG(ops,'R'); + else if ((on & PM_RIGHT_Z) && OPT_HASARG(ops,'Z')) + arg = OPT_ARG(ops,'Z'); + + if (arg) { + char *eptr; + pm->width = (int)zstrtol(arg, &eptr, 10); + if (*eptr) { + zwarnnam(name, "bad width value: %s", arg); + return 1; + } + } else if (always) + pm->width = 0; + + return 0; +} + +/* function to set a single parameter */ + +/**/ +static Param +typeset_single(char *cname, char *pname, Param pm, UNUSED(int func), + int on, int off, int roff, Asgment asg, Param altpm, + Options ops, int joinchar) +{ + int usepm, tc, keeplocal = 0, newspecial = NS_NONE, readonly, dont_set = 0; + char *subscript; + + /* + * Do we use the existing pm? Note that this isn't the end of the + * story, because if we try and create a new pm at the same + * locallevel as an unset one we use the pm struct anyway: that's + * handled in createparam(). Here we just avoid using it for the + * present tests if it's unset. + * + * POSIXBUILTINS horror: we need to retain the 'readonly' or 'export' + * flags of an unset parameter. + */ + usepm = pm && (!(pm->node.flags & PM_UNSET) || + (isset(POSIXBUILTINS) && + (pm->node.flags & (PM_READONLY|PM_EXPORTED)))); + + /* + * We need to compare types with an existing pm if special, + * even if that's unset + */ + if (!usepm && pm && (pm->node.flags & PM_SPECIAL)) + usepm = 2; /* indicate that we preserve the PM_UNSET flag */ + + /* + * Don't use an existing param if + * - the local level has changed, and + * - we are really locallizing the parameter + */ + if (usepm && locallevel != pm->level && (on & PM_LOCAL)) { + /* + * If the original parameter was special and we're creating + * a new one, we need to keep it special. + * + * The -h (hide) flag prevents an existing special being made + * local. It can be applied either to the special or in the + * typeset/local statement for the local variable. + */ + if ((pm->node.flags & PM_SPECIAL) + && !(on & PM_HIDE) && !(pm->node.flags & PM_HIDE & ~off)) + newspecial = NS_NORMAL; + usepm = 0; + } + + /* attempting a type conversion, or making a tied colonarray? */ + tc = 0; + if (ASG_ARRAYP(asg) && PM_TYPE(on) == PM_SCALAR && + !(usepm && (PM_TYPE(pm->node.flags) & (PM_ARRAY|PM_HASHED)))) + on |= PM_ARRAY; + if (usepm && ASG_ARRAYP(asg) && newspecial == NS_NONE && + PM_TYPE(pm->node.flags) != PM_ARRAY && + PM_TYPE(pm->node.flags) != PM_HASHED) { + if (on & (PM_EFLOAT|PM_FFLOAT|PM_INTEGER)) { + zerrnam(cname, "%s: can't assign array value to non-array", pname); + return NULL; + } + if (pm->node.flags & PM_SPECIAL) { + zerrnam(cname, "%s: can't assign array value to non-array special", pname); + return NULL; + } + tc = 1; + usepm = 0; + } + else if (usepm || newspecial != NS_NONE) { + int chflags = ((off & pm->node.flags) | (on & ~pm->node.flags)) & + (PM_INTEGER|PM_EFLOAT|PM_FFLOAT|PM_HASHED| + PM_ARRAY|PM_TIED|PM_AUTOLOAD); + /* keep the parameter if just switching between floating types */ + if ((tc = chflags && chflags != (PM_EFLOAT|PM_FFLOAT))) + usepm = 0; + } + + /* + * Extra checks if converting the type of a parameter, or if + * trying to remove readonlyness. It's dangerous doing either + * with a special or a parameter which isn't loaded yet (which + * may be special when it is loaded; we can't tell yet). + */ + if ((readonly = + ((usepm || newspecial != NS_NONE) && + (off & pm->node.flags & PM_READONLY))) || + tc) { + if (pm->node.flags & PM_SPECIAL) { + int err = 1; + if (!readonly && !strcmp(pname, "SECONDS")) + { + /* + * We allow SECONDS to change type between integer + * and floating point. If we are creating a new + * local copy we check the type here and allow + * a new special to be created with that type. + * We then need to make sure the correct type + * for the special is restored at the end of the scope. + * If we are changing the type of an existing + * parameter, we do the whole thing here. + */ + if (newspecial != NS_NONE) + { + /* + * The first test allows `typeset' to copy the + * existing type. This is the usual behaviour + * for making special parameters local. + */ + if (PM_TYPE(on) == 0 || PM_TYPE(on) == PM_INTEGER || + PM_TYPE(on) == PM_FFLOAT || PM_TYPE(on) == PM_EFLOAT) + { + newspecial = NS_SECONDS; + err = 0; /* and continue */ + tc = 0; /* but don't do a normal conversion */ + } + } else if (!setsecondstype(pm, on, off)) { + if (asg->value.scalar && + !(pm = assignsparam( + pname, ztrdup(asg->value.scalar), 0))) + return NULL; + usepm = 1; + err = 0; + } + } + if (err) + { + zerrnam(cname, "%s: can't change type of a special parameter", + pname); + return NULL; + } + } else if (pm->node.flags & PM_AUTOLOAD) { + zerrnam(cname, "%s: can't change type of autoloaded parameter", + pname); + return NULL; + } + } + else if (newspecial != NS_NONE && strcmp(pname, "SECONDS") == 0) + newspecial = NS_SECONDS; + + if (isset(POSIXBUILTINS)) { + /* + * Stricter rules about retaining readonly attribute in this case. + */ + if ((on & (PM_READONLY|PM_EXPORTED)) && + (!usepm || (pm->node.flags & PM_UNSET)) && + !ASG_VALUEP(asg)) + on |= PM_UNSET; + else if (usepm && (pm->node.flags & PM_READONLY) && + !(on & PM_READONLY)) { + zerr("read-only variable: %s", pm->node.nam); + return NULL; + } + /* This is handled by createparam(): + if (usepm && (pm->node.flags & PM_EXPORTED) && !(off & PM_EXPORTED)) + on |= PM_EXPORTED; + */ + } + + /* + * A parameter will be local if + * 1. we are re-using an existing local parameter + * or + * 2. we are not using an existing parameter, but + * i. there is already a parameter, which will be hidden + * or + * ii. we are creating a new local parameter + */ + if (usepm) { + if ((asg->flags & ASG_ARRAY) ? + !(PM_TYPE(pm->node.flags) & (PM_ARRAY|PM_HASHED)) : + (asg->value.scalar && (PM_TYPE(pm->node.flags & + (PM_ARRAY|PM_HASHED))))) { + zerrnam(cname, "%s: inconsistent type for assignment", pname); + return NULL; + } + on &= ~PM_LOCAL; + if (!on && !roff && !ASG_VALUEP(asg)) { + if (OPT_ISSET(ops,'p')) + paramtab->printnode(&pm->node, PRINT_TYPESET); + else if (!OPT_ISSET(ops,'g') && + (unset(TYPESETSILENT) || OPT_ISSET(ops,'m'))) + paramtab->printnode(&pm->node, PRINT_INCLUDEVALUE); + return pm; + } + if ((pm->node.flags & PM_RESTRICTED) && isset(RESTRICTED)) { + zerrnam(cname, "%s: restricted", pname); + return pm; + } + if ((on & PM_UNIQUE) && !(pm->node.flags & PM_READONLY & ~off)) { + Param apm; + char **x; + if (PM_TYPE(pm->node.flags) == PM_ARRAY) { + x = (*pm->gsu.a->getfn)(pm); + uniqarray(x); + if (pm->node.flags & PM_SPECIAL) { + if (zheapptr(x)) + x = zarrdup(x); + (*pm->gsu.a->setfn)(pm, x); + } else if (pm->ename && x) + arrfixenv(pm->ename, x); + } else if (PM_TYPE(pm->node.flags) == PM_SCALAR && pm->ename && + (apm = + (Param) paramtab->getnode(paramtab, pm->ename))) { + x = (*apm->gsu.a->getfn)(apm); + uniqarray(x); + if (x) + arrfixenv(pm->node.nam, x); + } + } + if (usepm == 2) /* do not change the PM_UNSET flag */ + pm->node.flags = (pm->node.flags | (on & ~PM_READONLY)) & ~off; + else { + /* + * Keep unset if using readonly in POSIX mode. + */ + if (!(on & PM_READONLY) || !isset(POSIXBUILTINS)) + off |= PM_UNSET; + pm->node.flags = (pm->node.flags | + (on & ~PM_READONLY)) & ~off; + } + if (on & (PM_LEFT | PM_RIGHT_B | PM_RIGHT_Z)) { + if (typeset_setwidth(cname, pm, ops, on, 0)) + return NULL; + } + if (on & (PM_INTEGER | PM_EFLOAT | PM_FFLOAT)) { + if (typeset_setbase(cname, pm, ops, on, 0)) + return NULL; + } + if (!(pm->node.flags & (PM_ARRAY|PM_HASHED))) { + if (pm->node.flags & PM_EXPORTED) { + if (!(pm->node.flags & PM_UNSET) && !pm->env && !ASG_VALUEP(asg)) + addenv(pm, getsparam(pname)); + } else if (pm->env && !(pm->node.flags & PM_HASHELEM)) + delenv(pm); + DPUTS(ASG_ARRAYP(asg), "BUG: typeset got array value where scalar expected"); + if (asg->value.scalar && + !(pm = assignsparam(pname, ztrdup(asg->value.scalar), 0))) + return NULL; + } else if (asg->flags & ASG_ARRAY) { + int flags = (asg->flags & ASG_KEY_VALUE) ? ASSPM_KEY_VALUE : 0; + if (!(pm = assignaparam(pname, asg->value.array ? + zlinklist2array(asg->value.array) : + mkarray(NULL), flags))) + return NULL; + } + if (errflag) + return NULL; + pm->node.flags |= (on & PM_READONLY); + if (OPT_ISSET(ops,'p')) + paramtab->printnode(&pm->node, PRINT_TYPESET); + return pm; + } + + if ((asg->flags & ASG_ARRAY) ? + !(on & (PM_ARRAY|PM_HASHED)) : + (asg->value.scalar && (on & (PM_ARRAY|PM_HASHED)))) { + zerrnam(cname, "%s: inconsistent type for assignment", pname); + return NULL; + } + + /* + * We're here either because we're creating a new parameter, + * or we're adding a parameter at a different local level, + * or we're converting the type of a parameter. In the + * last case only, we need to delete the old parameter. + */ + if (tc) { + /* Maintain existing readonly/exported status... */ + on |= ~off & (PM_READONLY|PM_EXPORTED) & pm->node.flags; + /* ...but turn off existing readonly so we can delete it */ + pm->node.flags &= ~PM_READONLY; + /* + * If we're just changing the type, we should keep the + * variable at the current level of localness. + */ + keeplocal = pm->level; + /* + * Try to carry over a value, but not when changing from, + * to, or between non-scalar types. + * + * (We can do better now, but it does have user-visible + * implications.) + */ + if (!ASG_VALUEP(asg) && !((pm->node.flags|on) & (PM_ARRAY|PM_HASHED))) { + asg->value.scalar = dupstring(getsparam(pname)); + asg->flags = 0; + } + /* pname may point to pm->nam which is about to disappear */ + pname = dupstring(pname); + unsetparam_pm(pm, 0, 1); + } + + if (newspecial != NS_NONE) { + Param tpm, pm2; + if ((pm->node.flags & PM_RESTRICTED) && isset(RESTRICTED)) { + zerrnam(cname, "%s: restricted", pname); + return pm; + } + if (pm->node.flags & PM_SINGLE) { + zerrnam(cname, "%s: can only have a single instance", pname); + return pm; + } + /* + * For specials, we keep the same struct but zero everything. + * Maybe it would be easier to create a new struct but copy + * the get/set methods. + */ + tpm = (Param) zshcalloc(sizeof *tpm); + + tpm->node.nam = pm->node.nam; + if (pm->ename && + (pm2 = (Param) paramtab->getnode(paramtab, pm->ename)) && + pm2->level == locallevel) { + /* This is getting silly, but anyway: if one of a path/PATH + * pair has already been made local at the current level, we + * have to make sure that the other one does not have its value + * saved: since that comes from an internal variable it will + * already reflect the local value, so restoring it on exit + * would be wrong. + * + * This problem is also why we make sure we have a copy + * of the environment entry in tpm->env, rather than relying + * on the restored value to provide it. + */ + tpm->node.flags = pm->node.flags | PM_NORESTORE; + } else { + copyparam(tpm, pm, 1); + } + tpm->old = pm->old; + tpm->level = pm->level; + tpm->base = pm->base; + tpm->width = pm->width; + if (pm->env) + delenv(pm); + tpm->env = NULL; + + pm->old = tpm; + /* + * The remaining on/off flags should be harmless to use, + * because we've checked for unpleasant surprises above. + */ + pm->node.flags = (PM_TYPE(pm->node.flags) | on | PM_SPECIAL) & ~off; + /* + * Readonlyness of special parameters must be preserved. + */ + pm->node.flags |= tpm->node.flags & PM_READONLY; + if (newspecial == NS_SECONDS) { + /* We save off the raw internal value of the SECONDS var */ + tpm->u.dval = getrawseconds(); + setsecondstype(pm, on, off); + } + + /* + * Final tweak: if we've turned on one of the flags with + * numbers, we should use the appropriate integer. + */ + if (on & (PM_LEFT|PM_RIGHT_B|PM_RIGHT_Z)) { + if (typeset_setwidth(cname, pm, ops, on, 1)) + return NULL; + } + if (on & (PM_INTEGER|PM_EFLOAT|PM_FFLOAT)) { + if (typeset_setbase(cname, pm, ops, on, 1)) + return NULL; + } + } else if ((subscript = strchr(pname, '['))) { + if (on & PM_READONLY) { + zerrnam(cname, + "%s: can't create readonly array elements", pname); + return NULL; + } else if ((on & PM_LOCAL) && locallevel) { + *subscript = 0; + pm = (Param) (paramtab == realparamtab ? + /* getnode2() to avoid autoloading */ + paramtab->getnode2(paramtab, pname) : + paramtab->getnode(paramtab, pname)); + *subscript = '['; + if (!pm || pm->level != locallevel) { + zerrnam(cname, + "%s: can't create local array elements", pname); + return NULL; + } + } + if (PM_TYPE(on) == PM_SCALAR && !ASG_ARRAYP(asg)) { + /* + * This will either complain about bad identifiers, or will set + * a hash element or array slice. This once worked by accident, + * creating a stray parameter along the way via createparam(), + * now called below in the isident() branch. + */ + if (!(pm = assignsparam( + pname, + ztrdup(asg->value.scalar ? asg->value.scalar : ""), 0))) + return NULL; + dont_set = 1; + asg->flags = 0; + keeplocal = 0; + on = pm->node.flags; + } else if (PM_TYPE(on) == PM_ARRAY && ASG_ARRAYP(asg)) { + int flags = (asg->flags & ASG_KEY_VALUE) ? ASSPM_KEY_VALUE : 0; + if (!(pm = assignaparam(pname, asg->value.array ? + zlinklist2array(asg->value.array) : + mkarray(NULL), flags))) + return NULL; + dont_set = 1; + keeplocal = 0; + on = pm->node.flags; + } else { + zerrnam(cname, + "%s: inconsistent array element or slice assignment", pname); + return NULL; + } + } + /* + * As we can hide existing parameters, we allow a name if + * it's not a normal identifier but is one of the special + * set found in the parameter table. The second test is + * because we can set individual positional parameters; + * however "0" is not a positional parameter and is OK. + * + * It would be neater to extend isident() and be clearer + * about where we allow various parameter types. It's + * not entirely clear to me isident() should reject + * specially named parameters given that it accepts digits. + */ + else if ((isident(pname) || paramtab->getnode(paramtab, pname)) + && (!idigit(*pname) || !strcmp(pname, "0"))) { + /* + * Create a new node for a parameter with the flags in `on' minus the + * readonly flag + */ + pm = createparam(pname, on & ~PM_READONLY); + if (!pm) { + if (on & (PM_LEFT | PM_RIGHT_B | PM_RIGHT_Z | + PM_INTEGER | PM_EFLOAT | PM_FFLOAT)) + zerrnam(cname, "can't change variable attribute: %s", pname); + return NULL; + } + if (on & (PM_LEFT | PM_RIGHT_B | PM_RIGHT_Z)) { + if (typeset_setwidth(cname, pm, ops, on, 0)) + return NULL; + } + if (on & (PM_INTEGER | PM_EFLOAT | PM_FFLOAT)) { + if (typeset_setbase(cname, pm, ops, on, 0)) + return NULL; + } + } else { + if (idigit(*pname)) + zerrnam(cname, "not an identifier: %s", pname); + else + zerrnam(cname, "not valid in this context: %s", pname); + return NULL; + } + + if (altpm && PM_TYPE(pm->node.flags) == PM_SCALAR) { + /* + * It seems safer to set this here than in createparam(), + * to make sure we only ever use the colonarr functions + * when u.data is correctly set. + */ + struct tieddata *tdp = (struct tieddata *) + zalloc(sizeof(struct tieddata)); + if (!tdp) + return NULL; + tdp->joinchar = joinchar; + tdp->arrptr = &altpm->u.arr; + + pm->gsu.s = &tiedarr_gsu; + pm->u.data = tdp; + } + + if (keeplocal) + pm->level = keeplocal; + else if (on & PM_LOCAL) + pm->level = locallevel; + if (ASG_VALUEP(asg) && !dont_set) { + Param ipm = pm; + if (pm->node.flags & (PM_ARRAY|PM_HASHED)) { + char **arrayval; + int flags = (asg->flags & ASG_KEY_VALUE) ? ASSPM_KEY_VALUE : 0; + if (!ASG_ARRAYP(asg)) { + /* + * Attempt to assign a scalar value to an array. + * This can happen if the array is special. + * We'll be lenient and guess what the user meant. + * This is how normal assigment works. + */ + if (*asg->value.scalar) { + /* Array with one value */ + arrayval = mkarray(ztrdup(asg->value.scalar)); + } else { + /* Empty array */ + arrayval = mkarray(NULL); + } + } else if (asg->value.array) + arrayval = zlinklist2array(asg->value.array); + else + arrayval = mkarray(NULL); + if (!(pm=assignaparam(pname, arrayval, flags))) + return NULL; + } else { + DPUTS(ASG_ARRAYP(asg), "BUG: inconsistent array value for scalar"); + if (!(pm = assignsparam(pname, ztrdup(asg->value.scalar), 0))) + return NULL; + } + if (pm != ipm) { + DPUTS(ipm->node.flags != pm->node.flags, + "BUG: parameter recreated with wrong flags"); + unsetparam_pm(ipm, 0, 1); + } + } else if (newspecial != NS_NONE && + !(pm->old->node.flags & (PM_NORESTORE|PM_READONLY))) { + /* + * We need to use the special setting function to re-initialise + * the special parameter to empty. + */ + switch (PM_TYPE(pm->node.flags)) { + case PM_SCALAR: + pm->gsu.s->setfn(pm, ztrdup("")); + break; + case PM_INTEGER: + /* + * Restricted integers are dangerous to initialize to 0, + * so don't do that. + */ + if (!(pm->old->node.flags & PM_RESTRICTED)) + pm->gsu.i->setfn(pm, 0); + break; + case PM_EFLOAT: + case PM_FFLOAT: + pm->gsu.f->setfn(pm, 0.0); + break; + case PM_ARRAY: + pm->gsu.a->setfn(pm, mkarray(NULL)); + break; + case PM_HASHED: + pm->gsu.h->setfn(pm, newparamtable(17, pm->node.nam)); + break; + } + } + pm->node.flags |= (on & PM_READONLY); + + if (OPT_ISSET(ops,'p')) + paramtab->printnode(&pm->node, PRINT_TYPESET); + + return pm; +} + +/* + * declare, export, float, integer, local, readonly, typeset + * + * Note the difference in interface from most builtins, covered by the + * BINF_ASSIGN builtin flag. This is only made use of by builtins + * called by reserved word, which only covers declare, local, readonly + * and typeset. Otherwise assigns is NULL. + */ + +/**/ +int +bin_typeset(char *name, char **argv, LinkList assigns, Options ops, int func) +{ + Param pm; + Asgment asg; + Patprog pprog; + char *optstr = TYPESET_OPTSTR; + int on = 0, off = 0, roff, bit = PM_ARRAY; + int i; + int returnval = 0, printflags = 0; + int hasargs; + + /* hash -f is really the builtin `functions' */ + if (OPT_ISSET(ops,'f')) + return bin_functions(name, argv, ops, func); + + /* POSIX handles "readonly" specially */ + if (func == BIN_READONLY && isset(POSIXBUILTINS) && !OPT_PLUS(ops, 'g')) + ops->ind['g'] = 1; + + /* Translate the options into PM_* flags. * + * Unfortunately, this depends on the order * + * these flags are defined in zsh.h */ + for (; *optstr; optstr++, bit <<= 1) + { + int optval = STOUC(*optstr); + if (OPT_MINUS(ops,optval)) + on |= bit; + else if (OPT_PLUS(ops,optval)) + off |= bit; + } + roff = off; + + /* Sanity checks on the options. Remove conflicting options. */ + if (on & PM_FFLOAT) { + off |= PM_UPPER | PM_ARRAY | PM_HASHED | PM_INTEGER | PM_EFLOAT; + /* Allow `float -F' to work even though float sets -E by default */ + on &= ~PM_EFLOAT; + } + if (on & PM_EFLOAT) + off |= PM_UPPER | PM_ARRAY | PM_HASHED | PM_INTEGER | PM_FFLOAT; + if (on & PM_INTEGER) + off |= PM_UPPER | PM_ARRAY | PM_HASHED | PM_EFLOAT | PM_FFLOAT; + /* + * Allowing -Z with -L is a feature: left justify, suppressing + * leading zeroes. + */ + if (on & (PM_LEFT|PM_RIGHT_Z)) + off |= PM_RIGHT_B; + if (on & PM_RIGHT_B) + off |= PM_LEFT | PM_RIGHT_Z; + if (on & PM_UPPER) + off |= PM_LOWER; + if (on & PM_LOWER) + off |= PM_UPPER; + if (on & PM_HASHED) + off |= PM_ARRAY; + if (on & PM_TIED) + off |= PM_INTEGER | PM_EFLOAT | PM_FFLOAT | PM_ARRAY | PM_HASHED; + + on &= ~off; + + queue_signals(); + + /* Given no arguments, list whatever the options specify. */ + if (OPT_ISSET(ops,'p')) { + printflags |= PRINT_TYPESET; + if (OPT_HASARG(ops,'p')) { + char *eptr; + int pflag = (int)zstrtol(OPT_ARG(ops,'p'), &eptr, 10); + if (pflag == 1 && !*eptr) + printflags |= PRINT_LINE; + else if (pflag || *eptr) { + zwarnnam(name, "bad argument to -p: %s", OPT_ARG(ops,'p')); + unqueue_signals(); + return 1; + } + /* -p0 treated as -p for consistency */ + } + } + hasargs = *argv != NULL || (assigns && firstnode(assigns)); + if (!hasargs) { + if (!OPT_ISSET(ops,'p')) { + if (!(on|roff)) + printflags |= PRINT_TYPE; + if (roff || OPT_ISSET(ops,'+')) + printflags |= PRINT_NAMEONLY; + } + scanhashtable(paramtab, 1, on|roff, 0, paramtab->printnode, printflags); + unqueue_signals(); + return 0; + } + + if (!(OPT_ISSET(ops,'g') || OPT_ISSET(ops,'x') || OPT_ISSET(ops,'m')) || + OPT_PLUS(ops,'g') || *name == 'l' || + (!isset(GLOBALEXPORT) && !OPT_ISSET(ops,'g'))) + on |= PM_LOCAL; + + if (on & PM_TIED) { + Param apm; + struct asgment asg0, asg2; + char *oldval = NULL, *joinstr; + int joinchar, nargs; + + if (OPT_ISSET(ops,'m')) { + zwarnnam(name, "incompatible options for -T"); + unqueue_signals(); + return 1; + } + on &= ~off; + nargs = arrlen(argv) + (assigns ? countlinknodes(assigns) : 0); + if (nargs < 2) { + zwarnnam(name, "-T requires names of scalar and array"); + unqueue_signals(); + return 1; + } + if (nargs > 3) { + zwarnnam(name, "too many arguments for -T"); + unqueue_signals(); + return 1; + } + + if (!(asg = getasg(&argv, assigns))) { + unqueue_signals(); + return 1; + } + asg0 = *asg; + if (ASG_ARRAYP(&asg0)) { + unqueue_signals(); + zwarnnam(name, "first argument of tie must be scalar: %s", + asg0.name); + return 1; + } + + if (!(asg = getasg(&argv, assigns))) { + unqueue_signals(); + return 1; + } + if (!ASG_ARRAYP(asg) && asg->value.scalar) { + unqueue_signals(); + zwarnnam(name, "second argument of tie must be array: %s", + asg->name); + return 1; + } + + if (!strcmp(asg0.name, asg->name)) { + unqueue_signals(); + zerrnam(name, "can't tie a variable to itself: %s", asg0.name); + return 1; + } + if (strchr(asg0.name, '[') || strchr(asg->name, '[')) { + unqueue_signals(); + zerrnam(name, "can't tie array elements: %s", asg0.name); + return 1; + } + if (ASG_VALUEP(asg) && ASG_VALUEP(&asg0)) { + unqueue_signals(); + zerrnam(name, "only one tied parameter can have value: %s", asg0.name); + return 1; + } + + /* + * Third argument, if given, is character used to join + * the elements of the array in the scalar. + */ + if (*argv) + joinstr = *argv; + else if (assigns && firstnode(assigns)) { + Asgment nextasg = (Asgment)firstnode(assigns); + if (ASG_ARRAYP(nextasg) || ASG_VALUEP(nextasg)) { + zwarnnam(name, "third argument of tie must be join character"); + unqueue_signals(); + return 1; + } + joinstr = nextasg->name; + } else + joinstr = NULL; + if (!joinstr) + joinchar = ':'; + else if (!*joinstr) + joinchar = 0; + else if (*joinstr == Meta) + joinchar = joinstr[1] ^ 32; + else + joinchar = *joinstr; + /* + * Keep the old value of the scalar. We need to do this + * here as if it is already tied to the same array it + * will be unset when we retie the array. This is all + * so that typeset -T is idempotent. + * + * We also need to remember here whether the damn thing is + * exported and pass that along. Isn't the world complicated? + */ + if ((pm = (Param) paramtab->getnode(paramtab, asg0.name)) + && !(pm->node.flags & PM_UNSET) + && (locallevel == pm->level || !(on & PM_LOCAL))) { + if (pm->node.flags & PM_TIED) { + unqueue_signals(); + if (PM_TYPE(pm->node.flags) != PM_SCALAR) { + zwarnnam(name, "already tied as non-scalar: %s", asg0.name); + } else if (!strcmp(asg->name, pm->ename)) { + /* + * Already tied in the fashion requested. + */ + struct tieddata *tdp = (struct tieddata*)pm->u.data; + int flags = (asg->flags & ASG_KEY_VALUE) ? + ASSPM_KEY_VALUE : 0; + /* Update join character */ + tdp->joinchar = joinchar; + if (asg0.value.scalar) + assignsparam(asg0.name, ztrdup(asg0.value.scalar), 0); + else if (asg->value.array) + assignaparam( + asg->name, zlinklist2array(asg->value.array),flags); + return 0; + } else { + zwarnnam(name, "can't tie already tied scalar: %s", + asg0.name); + } + return 1; + } + if (!asg0.value.scalar && !asg->value.array && + !(PM_TYPE(pm->node.flags) & (PM_ARRAY|PM_HASHED))) + oldval = ztrdup(getsparam(asg0.name)); + on |= (pm->node.flags & PM_EXPORTED); + } + /* + * Create the tied array; this is normal except that + * it has the PM_TIED flag set. Do it first because + * we need the address. + * + * Don't attempt to set it yet, it's too early + * to be exported properly. + */ + asg2.name = asg->name; + asg2.flags = 0; + asg2.value.array = (LinkList)0; + if (!(apm=typeset_single(name, asg->name, + (Param)paramtab->getnode(paramtab, + asg->name), + func, (on | PM_ARRAY) & ~PM_EXPORTED, + off, roff, &asg2, NULL, ops, 0))) { + if (oldval) + zsfree(oldval); + unqueue_signals(); + return 1; + } + /* + * Create the tied colonarray. We make it as a normal scalar + * and fix up the oddities later. + */ + if (!(pm=typeset_single(name, asg0.name, + (Param)paramtab->getnode(paramtab, + asg0.name), + func, on, off, roff, &asg0, apm, + ops, joinchar))) { + if (oldval) + zsfree(oldval); + unsetparam_pm(apm, 1, 1); + unqueue_signals(); + return 1; + } + + /* + * pm->ename is only deleted when the struct is, so + * we need to free it here if it already exists. + */ + if (pm->ename) + zsfree(pm->ename); + pm->ename = ztrdup(asg->name); + if (apm->ename) + zsfree(apm->ename); + apm->ename = ztrdup(asg0.name); + if (asg->value.array) { + int flags = (asg->flags & ASG_KEY_VALUE) ? ASSPM_KEY_VALUE : 0; + assignaparam(asg->name, zlinklist2array(asg->value.array), flags); + } else if (oldval) + assignsparam(asg0.name, oldval, 0); + unqueue_signals(); + + return 0; + } + if (off & PM_TIED) { + unqueue_signals(); + zerrnam(name, "use unset to remove tied variables"); + return 1; + } + + /* With the -m option, treat arguments as glob patterns */ + if (OPT_ISSET(ops,'m')) { + if (!OPT_ISSET(ops,'p')) { + if (!(on|roff)) + printflags |= PRINT_TYPE; + if (!on) + printflags |= PRINT_NAMEONLY; + } + + while ((asg = getasg(&argv, assigns))) { + LinkList pmlist = newlinklist(); + LinkNode pmnode; + + tokenize(asg->name); /* expand argument */ + if (!(pprog = patcompile(asg->name, 0, NULL))) { + untokenize(asg->name); + zwarnnam(name, "bad pattern : %s", asg->name); + returnval = 1; + continue; + } + if (OPT_PLUS(ops,'m') && !ASG_VALUEP(asg)) { + scanmatchtable(paramtab, pprog, 1, on|roff, 0, + paramtab->printnode, printflags); + continue; + } + /* + * Search through the parameter table and change all parameters + * matching the glob pattern to have these flags and/or value. + * Bad news: if the parameter gets altered, e.g. by + * a type conversion, then paramtab can be shifted around, + * so we need to store the parameters to alter on a separate + * list for later use. + */ + for (i = 0; i < paramtab->hsize; i++) { + for (pm = (Param) paramtab->nodes[i]; pm; + pm = (Param) pm->node.next) { + if (((pm->node.flags & PM_RESTRICTED) && isset(RESTRICTED)) || + (pm->node.flags & PM_UNSET)) + continue; + if (pattry(pprog, pm->node.nam)) + addlinknode(pmlist, pm); + } + } + for (pmnode = firstnode(pmlist); pmnode; incnode(pmnode)) { + pm = (Param) getdata(pmnode); + if (!typeset_single(name, pm->node.nam, pm, func, on, off, roff, + asg, NULL, ops, 0)) + returnval = 1; + } + } + unqueue_signals(); + return returnval; + } + + /* Take arguments literally. Don't glob */ + while ((asg = getasg(&argv, assigns))) { + HashNode hn = (paramtab == realparamtab ? + /* getnode2() to avoid autoloading */ + paramtab->getnode2(paramtab, asg->name) : + paramtab->getnode(paramtab, asg->name)); + if (OPT_ISSET(ops,'p')) { + if (hn) + paramtab->printnode(hn, printflags); + else { + zwarnnam(name, "no such variable: %s", asg->name); + returnval = 1; + } + continue; + } + if (!typeset_single(name, asg->name, (Param)hn, + func, on, off, roff, asg, NULL, + ops, 0)) + returnval = 1; + } + unqueue_signals(); + return returnval; +} + +/* Helper for bin_functions() when run as "autoload -X" */ + +/**/ +int +eval_autoload(Shfunc shf, char *name, Options ops, int func) +{ + if (!(shf->node.flags & PM_UNDEFINED)) + return 1; + + if (shf->funcdef) { + freeeprog(shf->funcdef); + shf->funcdef = &dummy_eprog; + } + if (OPT_MINUS(ops,'X')) { + char *fargv[3]; + fargv[0] = name; + fargv[1] = "\"$@\""; + fargv[2] = 0; + shf->funcdef = mkautofn(shf); + return bin_eval(name, fargv, ops, func); + } + + return !loadautofn(shf, (OPT_ISSET(ops,'k') ? 2 : + (OPT_ISSET(ops,'z') ? 0 : 1)), 1, + OPT_ISSET(ops,'d')); +} + +/* Helper for bin_functions() for -X and -r options */ + +/**/ +static int +check_autoload(Shfunc shf, char *name, Options ops, int func) +{ + if (OPT_ISSET(ops,'X')) + { + return eval_autoload(shf, name, ops, func); + } + if ((OPT_ISSET(ops,'r') || OPT_ISSET(ops,'R')) && + (shf->node.flags & PM_UNDEFINED)) + { + char *dir_path; + if (shf->filename && (shf->node.flags & PM_LOADDIR)) { + char *spec_path[2]; + spec_path[0] = shf->filename; + spec_path[1] = NULL; + if (getfpfunc(shf->node.nam, NULL, &dir_path, spec_path, 1)) { + /* shf->filename is already correct. */ + return 0; + } + if (!OPT_ISSET(ops,'d')) { + if (OPT_ISSET(ops,'R')) { + zerr("%s: function definition file not found", + shf->node.nam); + return 1; + } + return 0; + } + } + if (getfpfunc(shf->node.nam, NULL, &dir_path, NULL, 1)) { + dircache_set(&shf->filename, NULL); + if (*dir_path != '/') { + dir_path = zhtricat(metafy(zgetcwd(), -1, META_HEAPDUP), + "/", dir_path); + dir_path = xsymlink(dir_path, 1); + } + dircache_set(&shf->filename, dir_path); + shf->node.flags |= PM_LOADDIR; + return 0; + } + if (OPT_ISSET(ops,'R')) { + zerr("%s: function definition file not found", + shf->node.nam); + return 1; + } + /* with -r, we don't flag an error, just let it be found later. */ + } + return 0; +} + +/* List a user-defined math function. */ +static void +listusermathfunc(MathFunc p) +{ + int showargs; + + if (p->module) + showargs = 3; + else if (p->maxargs != (p->minargs ? p->minargs : -1)) + showargs = 2; + else if (p->minargs) + showargs = 1; + else + showargs = 0; + + printf("functions -M%s %s", (p->flags & MFF_STR) ? "s" : "", p->name); + if (showargs) { + printf(" %d", p->minargs); + showargs--; + } + if (showargs) { + printf(" %d", p->maxargs); + showargs--; + } + if (showargs) { + /* + * function names are not required to consist of ident characters + */ + putchar(' '); + quotedzputs(p->module, stdout); + showargs--; + } + putchar('\n'); +} + + +static void +add_autoload_function(Shfunc shf, char *funcname) +{ + char *nam; + if (*funcname == '/' && funcname[1] && + (nam = strrchr(funcname, '/')) && nam[1] && + (shf->node.flags & PM_UNDEFINED)) { + char *dir; + nam = strrchr(funcname, '/'); + if (nam == funcname) { + dir = "/"; + } else { + *nam++ = '\0'; + dir = funcname; + } + dircache_set(&shf->filename, NULL); + dircache_set(&shf->filename, dir); + shf->node.flags |= PM_LOADDIR; + shf->node.flags |= PM_ABSPATH_USED; + shfunctab->addnode(shfunctab, ztrdup(nam), shf); + } else { + Shfunc shf2; + Funcstack fs; + const char *calling_f = NULL; + char buf[PATH_MAX+1]; + + /* Find calling function */ + for (fs = funcstack; fs; fs = fs->prev) { + if (fs->tp == FS_FUNC && fs->name && (!shf->node.nam || 0 != strcmp(fs->name,shf->node.nam))) { + calling_f = fs->name; + break; + } + } + + /* Get its directory */ + if (calling_f) { + /* Should contain load directory, and be loaded via absolute path */ + if ((shf2 = (Shfunc) shfunctab->getnode2(shfunctab, calling_f)) + && (shf2->node.flags & PM_LOADDIR) && (shf2->node.flags & PM_ABSPATH_USED) + && shf2->filename) + { + if (strlen(shf2->filename) + strlen(funcname) + 1 < PATH_MAX) + { + sprintf(buf, "%s/%s", shf2->filename, funcname); + /* Set containing directory if the function file + * exists (do normal FPATH processing otherwise) */ + if (!access(buf, R_OK)) { + dircache_set(&shf->filename, NULL); + dircache_set(&shf->filename, shf2->filename); + shf->node.flags |= PM_LOADDIR; + shf->node.flags |= PM_ABSPATH_USED; + } + } + } + } + + shfunctab->addnode(shfunctab, ztrdup(funcname), shf); + } +} + +/* Display or change the attributes of shell functions. * + * If called as autoload, it will define a new autoloaded * + * (undefined) shell function. */ + +/**/ +int +bin_functions(char *name, char **argv, Options ops, int func) +{ + Patprog pprog; + Shfunc shf; + int i, returnval = 0; + int on = 0, off = 0, pflags = 0, roff, expand = 0; + + /* Do we have any flags defined? */ + if (OPT_PLUS(ops,'u')) + off |= PM_UNDEFINED; + else if (OPT_MINUS(ops,'u') || OPT_ISSET(ops,'X')) + on |= PM_UNDEFINED; + if (OPT_MINUS(ops,'U')) + on |= PM_UNALIASED|PM_UNDEFINED; + else if (OPT_PLUS(ops,'U')) + off |= PM_UNALIASED; + if (OPT_MINUS(ops,'t')) + on |= PM_TAGGED; + else if (OPT_PLUS(ops,'t')) + off |= PM_TAGGED; + if (OPT_MINUS(ops,'T')) + on |= PM_TAGGED_LOCAL; + else if (OPT_PLUS(ops,'T')) + off |= PM_TAGGED_LOCAL; + if (OPT_MINUS(ops,'W')) + on |= PM_WARNNESTED; + else if (OPT_PLUS(ops,'W')) + off |= PM_WARNNESTED; + roff = off; + if (OPT_MINUS(ops,'z')) { + on |= PM_ZSHSTORED; + off |= PM_KSHSTORED; + } else if (OPT_PLUS(ops,'z')) { + off |= PM_ZSHSTORED; + roff |= PM_ZSHSTORED; + } + if (OPT_MINUS(ops,'k')) { + on |= PM_KSHSTORED; + off |= PM_ZSHSTORED; + } else if (OPT_PLUS(ops,'k')) { + off |= PM_KSHSTORED; + roff |= PM_KSHSTORED; + } + if (OPT_MINUS(ops,'d')) { + on |= PM_CUR_FPATH; + off |= PM_CUR_FPATH; + } else if (OPT_PLUS(ops,'d')) { + off |= PM_CUR_FPATH; + roff |= PM_CUR_FPATH; + } + + if ((off & PM_UNDEFINED) || (OPT_ISSET(ops,'k') && OPT_ISSET(ops,'z')) || + (OPT_ISSET(ops,'x') && !OPT_HASARG(ops,'x')) || + (OPT_MINUS(ops,'X') && (OPT_ISSET(ops,'m') || !scriptname))) { + zwarnnam(name, "invalid option(s)"); + return 1; + } + + if (OPT_ISSET(ops,'x')) { + char *eptr; + expand = (int)zstrtol(OPT_ARG(ops,'x'), &eptr, 10); + if (*eptr) { + zwarnnam(name, "number expected after -x"); + return 1; + } + if (expand == 0) /* no indentation at all */ + expand = -1; + } + + if (OPT_PLUS(ops,'f') || roff || OPT_ISSET(ops,'+')) + pflags |= PRINT_NAMEONLY; + + if (OPT_MINUS(ops,'M') || OPT_PLUS(ops,'M')) { + MathFunc p, q, prev; + /* + * Add/remove/list function as mathematical. + */ + if (on || off || pflags || OPT_ISSET(ops,'X') || OPT_ISSET(ops,'u') + || OPT_ISSET(ops,'U') || OPT_ISSET(ops,'w')) { + zwarnnam(name, "invalid option(s)"); + return 1; + } + if (!*argv) { + /* List functions. */ + queue_signals(); + for (p = mathfuncs; p; p = p->next) + if (p->flags & MFF_USERFUNC) + listusermathfunc(p); + unqueue_signals(); + } else if (OPT_ISSET(ops,'m')) { + /* List matching functions. */ + for (; *argv; argv++) { + queue_signals(); + tokenize(*argv); + if ((pprog = patcompile(*argv, PAT_STATIC, 0))) { + for (p = mathfuncs, q = NULL; p; q = p) { + MathFunc next; + do { + next = NULL; + if ((p->flags & MFF_USERFUNC) && + pattry(pprog, p->name)) { + if (OPT_PLUS(ops,'M')) { + next = p->next; + removemathfunc(q, p); + p = next; + } else + listusermathfunc(p); + } + /* if we deleted one, retry with the new p */ + } while (next); + if (p) + p = p->next; + } + } else { + untokenize(*argv); + zwarnnam(name, "bad pattern : %s", *argv); + returnval = 1; + } + unqueue_signals(); + } + } else if (OPT_PLUS(ops,'M')) { + /* Delete functions. -m is allowed but is handled above. */ + for (; *argv; argv++) { + queue_signals(); + for (p = mathfuncs, q = NULL; p; q = p, p = p->next) { + if (!strcmp(p->name, *argv)) { + if (!(p->flags & MFF_USERFUNC)) { + zwarnnam(name, "+M %s: is a library function", + *argv); + returnval = 1; + break; + } + removemathfunc(q, p); + break; + } + } + unqueue_signals(); + } + } else { + /* Add a function */ + int minargs, maxargs; + char *funcname = *argv++; + char *modname = NULL; + char *ptr; + + if (OPT_ISSET(ops,'s')) { + minargs = maxargs = 1; + } else { + minargs = 0; + maxargs = -1; + } + + ptr = itype_end(funcname, IIDENT, 0); + if (idigit(*funcname) || funcname == ptr || *ptr) { + zwarnnam(name, "-M %s: bad math function name", funcname); + return 1; + } + + if (*argv) { + minargs = (int)zstrtol(*argv, &ptr, 0); + if (minargs < 0 || *ptr) { + zwarnnam(name, "-M: invalid min number of arguments: %s", + *argv); + return 1; + } + if (OPT_ISSET(ops,'s') && minargs != 1) { + zwarnnam(name, "-Ms: must take a single string argument"); + return 1; + } + maxargs = minargs; + argv++; + } + if (*argv) { + maxargs = (int)zstrtol(*argv, &ptr, 0); + if (maxargs < -1 || + (maxargs != -1 && maxargs < minargs) || + *ptr) { + zwarnnam(name, + "-M: invalid max number of arguments: %s", + *argv); + return 1; + } + if (OPT_ISSET(ops,'s') && maxargs != 1) { + zwarnnam(name, "-Ms: must take a single string argument"); + return 1; + } + argv++; + } + if (*argv) + modname = *argv++; + if (*argv) { + zwarnnam(name, "-M: too many arguments"); + return 1; + } + + p = (MathFunc)zshcalloc(sizeof(struct mathfunc)); + p->name = ztrdup(funcname); + p->flags = MFF_USERFUNC; + if (OPT_ISSET(ops,'s')) + p->flags |= MFF_STR; + p->module = modname ? ztrdup(modname) : NULL; + p->minargs = minargs; + p->maxargs = maxargs; + + queue_signals(); + for (q = mathfuncs, prev = NULL; q; prev = q, q = q->next) { + if (!strcmp(q->name, funcname)) { + removemathfunc(prev, q); + break; + } + } + + p->next = mathfuncs; + mathfuncs = p; + unqueue_signals(); + } + + return returnval; + } + + if (OPT_MINUS(ops,'X')) { + Funcstack fs; + char *funcname = NULL; + int ret; + if (*argv && argv[1]) { + zwarnnam(name, "-X: too many arguments"); + return 1; + } + queue_signals(); + for (fs = funcstack; fs; fs = fs->prev) { + if (fs->tp == FS_FUNC) { + /* + * dupstring here is paranoia but unlikely to be + * problematic + */ + funcname = dupstring(fs->name); + break; + } + } + if (!funcname) + { + zerrnam(name, "bad autoload"); + ret = 1; + } else { + if ((shf = (Shfunc) shfunctab->getnode(shfunctab, funcname))) { + DPUTS(!shf->funcdef, + "BUG: Calling autoload from empty function"); + } else { + shf = (Shfunc) zshcalloc(sizeof *shf); + shfunctab->addnode(shfunctab, ztrdup(funcname), shf); + } + if (*argv) { + dircache_set(&shf->filename, NULL); + dircache_set(&shf->filename, *argv); + on |= PM_LOADDIR; + } + shf->node.flags = on; + ret = eval_autoload(shf, funcname, ops, func); + } + unqueue_signals(); + return ret; + } else if (!*argv) { + /* If no arguments given, we will print functions. If flags * + * are given, we will print only functions containing these * + * flags, else we'll print them all. */ + int ret = 0; + + queue_signals(); + if (OPT_ISSET(ops,'U') && !OPT_ISSET(ops,'u')) + on &= ~PM_UNDEFINED; + scanshfunc(1, on|off, DISABLED, shfunctab->printnode, + pflags, expand); + unqueue_signals(); + return ret; + } + + /* With the -m option, treat arguments as glob patterns */ + if (OPT_ISSET(ops,'m')) { + on &= ~PM_UNDEFINED; + for (; *argv; argv++) { + queue_signals(); + /* expand argument */ + tokenize(*argv); + if ((pprog = patcompile(*argv, PAT_STATIC, 0))) { + /* with no options, just print all functions matching the glob pattern */ + if (!(on|off) && !OPT_ISSET(ops,'X')) { + scanmatchshfunc(pprog, 1, 0, DISABLED, + shfunctab->printnode, pflags, expand); + } else { + /* apply the options to all functions matching the glob pattern */ + for (i = 0; i < shfunctab->hsize; i++) { + for (shf = (Shfunc) shfunctab->nodes[i]; shf; + shf = (Shfunc) shf->node.next) + if (pattry(pprog, shf->node.nam) && + !(shf->node.flags & DISABLED)) { + shf->node.flags = (shf->node.flags | + (on & ~PM_UNDEFINED)) & ~off; + if (check_autoload(shf, shf->node.nam, + ops, func)) { + returnval = 1; + } + } + } + } + } else { + untokenize(*argv); + zwarnnam(name, "bad pattern : %s", *argv); + returnval = 1; + } + unqueue_signals(); + } + return returnval; + } + + /* Take the arguments literally -- do not glob */ + queue_signals(); + for (; *argv; argv++) { + if (OPT_ISSET(ops,'w')) + returnval = dump_autoload(name, *argv, on, ops, func); + else if ((shf = (Shfunc) shfunctab->getnode(shfunctab, *argv))) { + /* if any flag was given */ + if (on|off) { + /* turn on/off the given flags */ + shf->node.flags = (shf->node.flags | (on & ~PM_UNDEFINED)) & ~off; + if (check_autoload(shf, shf->node.nam, ops, func)) + returnval = 1; + } else + /* no flags, so just print */ + printshfuncexpand(&shf->node, pflags, expand); + } else if (on & PM_UNDEFINED) { + int signum = -1, ok = 1; + + if (!strncmp(*argv, "TRAP", 4) && + (signum = getsignum(*argv + 4)) != -1) { + /* + * Because of the possibility of alternative names, + * we must remove the trap explicitly. + */ + removetrapnode(signum); + } + + if (**argv == '/') { + char *base = strrchr(*argv, '/') + 1; + if (*base && + (shf = (Shfunc) shfunctab->getnode(shfunctab, base))) { + char *dir; + /* turn on/off the given flags */ + shf->node.flags = + (shf->node.flags | (on & ~PM_UNDEFINED)) & ~off; + if (shf->node.flags & PM_UNDEFINED) { + /* update path if not yet loaded */ + if (base == *argv + 1) + dir = "/"; + else { + dir = *argv; + base[-1] = '\0'; + } + dircache_set(&shf->filename, NULL); + dircache_set(&shf->filename, dir); + } + if (check_autoload(shf, shf->node.nam, ops, func)) + returnval = 1; + continue; + } + } + + /* Add a new undefined (autoloaded) function to the * + * hash table with the corresponding flags set. */ + shf = (Shfunc) zshcalloc(sizeof *shf); + shf->node.flags = on; + shf->funcdef = mkautofn(shf); + shfunc_set_sticky(shf); + add_autoload_function(shf, *argv); + + if (signum != -1) { + if (settrap(signum, NULL, ZSIG_FUNC)) { + shfunctab->removenode(shfunctab, *argv); + shfunctab->freenode(&shf->node); + returnval = 1; + ok = 0; + } + } + + if (ok && check_autoload(shf, shf->node.nam, ops, func)) + returnval = 1; + } else + returnval = 1; + } + unqueue_signals(); + return returnval; +} + +/**/ +Eprog +mkautofn(Shfunc shf) +{ + Eprog p; + + p = (Eprog) zalloc(sizeof(*p)); + p->len = 5 * sizeof(wordcode); + p->prog = (Wordcode) zalloc(p->len); + p->strs = NULL; + p->shf = shf; + p->npats = 0; + p->nref = 1; /* allocated from permanent storage */ + p->pats = (Patprog *) p->prog; + p->flags = EF_REAL; + p->dump = NULL; + + p->prog[0] = WCB_LIST((Z_SYNC | Z_END), 0); + p->prog[1] = WCB_SUBLIST(WC_SUBLIST_END, 0, 3); + p->prog[2] = WCB_PIPE(WC_PIPE_END, 0); + p->prog[3] = WCB_AUTOFN(); + p->prog[4] = WCB_END(); + + return p; +} + +/* unset: unset parameters */ + +/**/ +int +bin_unset(char *name, char **argv, Options ops, int func) +{ + Param pm, next; + Patprog pprog; + char *s; + int match = 0, returnval = 0; + int i; + + /* unset -f is the same as unfunction */ + if (OPT_ISSET(ops,'f')) + return bin_unhash(name, argv, ops, func); + + /* with -m option, treat arguments as glob patterns */ + if (OPT_ISSET(ops,'m')) { + while ((s = *argv++)) { + queue_signals(); + /* expand */ + tokenize(s); + if ((pprog = patcompile(s, PAT_STATIC, NULL))) { + /* Go through the parameter table, and unset any matches */ + for (i = 0; i < paramtab->hsize; i++) { + for (pm = (Param) paramtab->nodes[i]; pm; pm = next) { + /* record pointer to next, since we may free this one */ + next = (Param) pm->node.next; + if ((!(pm->node.flags & PM_RESTRICTED) || + unset(RESTRICTED)) && + pattry(pprog, pm->node.nam)) { + unsetparam_pm(pm, 0, 1); + match++; + } + } + } + } else { + untokenize(s); + zwarnnam(name, "bad pattern : %s", s); + returnval = 1; + } + unqueue_signals(); + } + /* If we didn't match anything, we return 1. */ + if (!match) + returnval = 1; + return returnval; + } + + /* do not glob -- unset the given parameter */ + queue_signals(); + while ((s = *argv++)) { + char *ss = strchr(s, '['), *subscript = 0; + if (ss) { + char *sse; + *ss = 0; + if ((sse = parse_subscript(ss+1, 1, ']'))) { + *sse = 0; + subscript = dupstring(ss+1); + *sse = ']'; + remnulargs(subscript); + untokenize(subscript); + } + } + if ((ss && !subscript) || !isident(s)) { + if (ss) + *ss = '['; + zerrnam(name, "%s: invalid parameter name", s); + returnval = 1; + continue; + } + pm = (Param) (paramtab == realparamtab ? + /* getnode2() to avoid autoloading */ + paramtab->getnode2(paramtab, s) : + paramtab->getnode(paramtab, s)); + /* + * Unsetting an unset variable is not an error. + * This appears to be reasonably standard behaviour. + */ + if (!pm) + continue; + else if ((pm->node.flags & PM_RESTRICTED) && isset(RESTRICTED)) { + zerrnam(name, "%s: restricted", pm->node.nam); + returnval = 1; + } else if (ss) { + if (PM_TYPE(pm->node.flags) == PM_HASHED) { + HashTable tht = paramtab; + if ((paramtab = pm->gsu.h->getfn(pm))) + unsetparam(subscript); + paramtab = tht; + } else if (PM_TYPE(pm->node.flags) == PM_SCALAR || + PM_TYPE(pm->node.flags) == PM_ARRAY) { + struct value vbuf; + vbuf.isarr = (PM_TYPE(pm->node.flags) == PM_ARRAY ? + SCANPM_ARRONLY : 0); + vbuf.pm = pm; + vbuf.flags = 0; + vbuf.start = 0; + vbuf.end = -1; + vbuf.arr = 0; + *ss = '['; + if (getindex(&ss, &vbuf, SCANPM_ASSIGNING) == 0 && + vbuf.pm && !(vbuf.pm->node.flags & PM_UNSET)) { + if (PM_TYPE(pm->node.flags) == PM_SCALAR) { + setstrvalue(&vbuf, ztrdup("")); + } else { + /* start is after the element for reverse index */ + int start = vbuf.start - !!(vbuf.flags & VALFLAG_INV); + if (arrlen_gt(vbuf.pm->u.arr, start)) { + char *arr[2]; + arr[0] = ""; + arr[1] = 0; + setarrvalue(&vbuf, zarrdup(arr)); + } + } + } + returnval = errflag; + errflag &= ~ERRFLAG_ERROR; + } else { + zerrnam(name, "%s: invalid element for unset", s); + returnval = 1; + } + } else { + if (unsetparam_pm(pm, 0, 1)) + returnval = 1; + } + if (ss) + *ss = '['; + } + unqueue_signals(); + return returnval; +} + +/* type, whence, which, command */ + +static LinkList matchednodes; + +static void +fetchcmdnamnode(HashNode hn, UNUSED(int printflags)) +{ + Cmdnam cn = (Cmdnam) hn; + addlinknode(matchednodes, cn->node.nam); +} + +/**/ +int +bin_whence(char *nam, char **argv, Options ops, int func) +{ + HashNode hn; + Patprog pprog; + int returnval = 0; + int printflags = 0; + int aliasflags; + int csh, all, v, wd; + int informed = 0; + int expand = 0; + char *cnam, **allmatched = 0; + + /* Check some option information */ + csh = OPT_ISSET(ops,'c'); + v = OPT_ISSET(ops,'v'); + all = OPT_ISSET(ops,'a'); + wd = OPT_ISSET(ops,'w'); + + if (OPT_ISSET(ops,'x')) { + char *eptr; + expand = (int)zstrtol(OPT_ARG(ops,'x'), &eptr, 10); + if (*eptr) { + zwarnnam(nam, "number expected after -x"); + return 1; + } + if (expand == 0) /* no indentation at all */ + expand = -1; + } + + if (OPT_ISSET(ops,'w')) + printflags |= PRINT_WHENCE_WORD; + else if (OPT_ISSET(ops,'c')) + printflags |= PRINT_WHENCE_CSH; + else if (OPT_ISSET(ops,'v')) + printflags |= PRINT_WHENCE_VERBOSE; + else + printflags |= PRINT_WHENCE_SIMPLE; + if (OPT_ISSET(ops,'f')) + printflags |= PRINT_WHENCE_FUNCDEF; + + if (func == BIN_COMMAND) + if (OPT_ISSET(ops,'V')) { + printflags = aliasflags = PRINT_WHENCE_VERBOSE; + v = 1; + } else { + aliasflags = PRINT_LIST; + printflags = PRINT_WHENCE_SIMPLE; + v = 0; + } + else + aliasflags = printflags; + + /* With -m option -- treat arguments as a glob patterns */ + if (OPT_ISSET(ops,'m')) { + cmdnamtab->filltable(cmdnamtab); + if (all) { + pushheap(); + matchednodes = newlinklist(); + } + queue_signals(); + for (; *argv; argv++) { + /* parse the pattern */ + tokenize(*argv); + if (!(pprog = patcompile(*argv, PAT_STATIC, NULL))) { + untokenize(*argv); + zwarnnam(nam, "bad pattern : %s", *argv); + returnval = 1; + continue; + } + if (!OPT_ISSET(ops,'p')) { + /* -p option is for path search only. * + * We're not using it, so search for ... */ + + /* aliases ... */ + informed += + scanmatchtable(aliastab, pprog, 1, 0, DISABLED, + aliastab->printnode, printflags); + + /* and reserved words ... */ + informed += + scanmatchtable(reswdtab, pprog, 1, 0, DISABLED, + reswdtab->printnode, printflags); + + /* and shell functions... */ + informed += + scanmatchshfunc(pprog, 1, 0, DISABLED, + shfunctab->printnode, printflags, expand); + + /* and builtins. */ + informed += + scanmatchtable(builtintab, pprog, 1, 0, DISABLED, + builtintab->printnode, printflags); + } + /* Done search for `internal' commands, if the -p option * + * was not used. Now search the path. */ + informed += + scanmatchtable(cmdnamtab, pprog, 1, 0, 0, + (all ? fetchcmdnamnode : cmdnamtab->printnode), + printflags); + run_queued_signals(); + } + unqueue_signals(); + if (all) { + allmatched = argv = zlinklist2array(matchednodes); + matchednodes = NULL; + popheap(); + } else + return returnval || !informed; + } + + /* Take arguments literally -- do not glob */ + queue_signals(); + for (; *argv; argv++) { + if (!OPT_ISSET(ops,'p') && !allmatched) { + char *suf; + + /* Look for alias */ + if ((hn = aliastab->getnode(aliastab, *argv))) { + aliastab->printnode(hn, aliasflags); + informed = 1; + if (!all) + continue; + } + /* Look for suffix alias */ + if ((suf = strrchr(*argv, '.')) && suf[1] && + suf > *argv && suf[-1] != Meta && + (hn = sufaliastab->getnode(sufaliastab, suf+1))) { + sufaliastab->printnode(hn, printflags); + informed = 1; + if (!all) + continue; + } + /* Look for reserved word */ + if ((hn = reswdtab->getnode(reswdtab, *argv))) { + reswdtab->printnode(hn, printflags); + informed = 1; + if (!all) + continue; + } + /* Look for shell function */ + if ((hn = shfunctab->getnode(shfunctab, *argv))) { + printshfuncexpand(hn, printflags, expand); + informed = 1; + if (!all) + continue; + } + /* Look for builtin command */ + if ((hn = builtintab->getnode(builtintab, *argv))) { + builtintab->printnode(hn, printflags); + informed = 1; + if (!all) + continue; + } + /* Look for commands that have been added to the * + * cmdnamtab with the builtin `hash foo=bar'. */ + if ((hn = cmdnamtab->getnode(cmdnamtab, *argv)) && (hn->flags & HASHED)) { + cmdnamtab->printnode(hn, printflags); + informed = 1; + if (!all) + continue; + } + } + + /* Option -a is to search the entire path, * + * rather than just looking for one match. */ + if (all && **argv != '/') { + char **pp, *buf; + + pushheap(); + for (pp = path; *pp; pp++) { + if (**pp) { + buf = zhtricat(*pp, "/", *argv); + } else buf = dupstring(*argv); + + if (iscom(buf)) { + if (wd) { + printf("%s: command\n", *argv); + } else { + if (v && !csh) { + zputs(*argv, stdout), fputs(" is ", stdout); + quotedzputs(buf, stdout); + } else + zputs(buf, stdout); + if (OPT_ISSET(ops,'s') || OPT_ISSET(ops, 'S')) + print_if_link(buf, OPT_ISSET(ops, 'S')); + fputc('\n', stdout); + } + informed = 1; + } + } + if (!informed && (wd || v || csh)) { + /* this is information and not an error so, as in csh, use stdout */ + zputs(*argv, stdout); + puts(wd ? ": none" : " not found"); + returnval = 1; + } + popheap(); + } else if (func == BIN_COMMAND && OPT_ISSET(ops,'p') && + (hn = builtintab->getnode(builtintab, *argv))) { + /* + * Special case for "command -p[vV]" which needs to + * show a builtin in preference to an external command. + */ + builtintab->printnode(hn, printflags); + informed = 1; + } else if ((cnam = findcmd(*argv, 1, + func == BIN_COMMAND && + OPT_ISSET(ops,'p')))) { + /* Found external command. */ + if (wd) { + printf("%s: command\n", *argv); + } else { + if (v && !csh) { + zputs(*argv, stdout), fputs(" is ", stdout); + quotedzputs(cnam, stdout); + } else + zputs(cnam, stdout); + if (OPT_ISSET(ops,'s') || OPT_ISSET(ops,'S')) + print_if_link(cnam, OPT_ISSET(ops,'S')); + fputc('\n', stdout); + } + informed = 1; + } else { + /* Not found at all. That's not an error as such so this goes to stdout */ + if (v || csh || wd) + zputs(*argv, stdout), puts(wd ? ": none" : " not found"); + returnval = 1; + } + } + if (allmatched) + freearray(allmatched); + + unqueue_signals(); + return returnval || !informed; +} + +/**** command & named directory hash table builtins ****/ + +/***************************************************************** + * hash -- explicitly hash a command. * + * 1) Given no arguments, list the hash table. * + * 2) The -m option prints out commands in the hash table that * + * match a given glob pattern. * + * 3) The -f option causes the entire path to be added to the * + * hash table (cannot be combined with any arguments). * + * 4) The -r option causes the entire hash table to be discarded * + * (cannot be combined with any arguments). * + * 5) Given argument of the form foo=bar, add element to command * + * hash table, so that when `foo' is entered, then `bar' is * + * executed. * + * 6) Given arguments not of the previous form, add it to the * + * command hash table as if it were being executed. * + * 7) The -d option causes analogous things to be done using * + * the named directory hash table. * + *****************************************************************/ + +/**/ +int +bin_hash(char *name, char **argv, Options ops, UNUSED(int func)) +{ + HashTable ht; + Patprog pprog; + Asgment asg; + int returnval = 0; + int printflags = 0; + + if (OPT_ISSET(ops,'d')) + ht = nameddirtab; + else + ht = cmdnamtab; + + if (OPT_ISSET(ops,'r') || OPT_ISSET(ops,'f')) { + /* -f and -r can't be used with any arguments */ + if (*argv) { + zwarnnam("hash", "too many arguments"); + return 1; + } + + /* empty the hash table */ + if (OPT_ISSET(ops,'r')) + ht->emptytable(ht); + + /* fill the hash table in a standard way */ + if (OPT_ISSET(ops,'f')) + ht->filltable(ht); + + return 0; + } + + if (OPT_ISSET(ops,'L')) printflags |= PRINT_LIST; + + /* Given no arguments, display current hash table. */ + if (!*argv) { + queue_signals(); + scanhashtable(ht, 1, 0, 0, ht->printnode, printflags); + unqueue_signals(); + return 0; + } + + queue_signals(); + while (*argv) { + void *hn; + if (OPT_ISSET(ops,'m')) { + /* with the -m option, treat the argument as a glob pattern */ + tokenize(*argv); /* expand */ + if ((pprog = patcompile(*argv, PAT_STATIC, NULL))) { + /* display matching hash table elements */ + scanmatchtable(ht, pprog, 1, 0, 0, ht->printnode, printflags); + } else { + untokenize(*argv); + zwarnnam(name, "bad pattern : %s", *argv); + returnval = 1; + } + argv++; + continue; + } + if (!(asg = getasg(&argv, NULL))) { + zwarnnam(name, "bad assignment"); + returnval = 1; + break; + } else if (ASG_VALUEP(asg)) { + if(isset(RESTRICTED)) { + zwarnnam(name, "restricted: %s", asg->value.scalar); + returnval = 1; + } else { + /* The argument is of the form foo=bar, * + * so define an entry for the table. */ + if(OPT_ISSET(ops,'d')) { + /* shouldn't return NULL if asg->name is not NULL */ + if (*itype_end(asg->name, IUSER, 0)) { + zwarnnam(name, + "invalid character in directory name: %s", + asg->name); + returnval = 1; + continue; + } else { + Nameddir nd = hn = zshcalloc(sizeof *nd); + nd->node.flags = 0; + nd->dir = ztrdup(asg->value.scalar); + } + } else { + Cmdnam cn = hn = zshcalloc(sizeof *cn); + cn->node.flags = HASHED; + cn->u.cmd = ztrdup(asg->value.scalar); + } + ht->addnode(ht, ztrdup(asg->name), hn); + if(OPT_ISSET(ops,'v')) + ht->printnode(hn, 0); + } + } else if (!(hn = ht->getnode2(ht, asg->name))) { + /* With no `=value' part to the argument, * + * work out what it ought to be. */ + if(OPT_ISSET(ops,'d')) { + if(!getnameddir(asg->name)) { + zwarnnam(name, "no such directory name: %s", asg->name); + returnval = 1; + } + } else { + if (!hashcmd(asg->name, path)) { + zwarnnam(name, "no such command: %s", asg->name); + returnval = 1; + } + } + if(OPT_ISSET(ops,'v') && (hn = ht->getnode2(ht, asg->name))) + ht->printnode(hn, 0); + } else if(OPT_ISSET(ops,'v')) + ht->printnode(hn, 0); + } + unqueue_signals(); + return returnval; +} + +/* unhash: remove specified elements from a hash table */ + +/**/ +int +bin_unhash(char *name, char **argv, Options ops, int func) +{ + HashTable ht; + HashNode hn, nhn; + Patprog pprog; + int match = 0, returnval = 0, all = 0; + int i; + + /* Check which hash table we are working with. */ + if (func == BIN_UNALIAS) { + if (OPT_ISSET(ops,'s')) + ht = sufaliastab; /* suffix aliases */ + else + ht = aliastab; /* aliases */ + if (OPT_ISSET(ops, 'a')) { + if (*argv) { + zwarnnam(name, "-a: too many arguments"); + return 1; + } + all = 1; + } else if (!*argv) { + zwarnnam(name, "not enough arguments"); + return 1; + } + } else if (OPT_ISSET(ops,'d')) + ht = nameddirtab; /* named directories */ + else if (OPT_ISSET(ops,'f')) + ht = shfunctab; /* shell functions */ + else if (OPT_ISSET(ops,'s')) + ht = sufaliastab; /* suffix aliases, must precede aliases */ + else if (func == BIN_UNHASH && (OPT_ISSET(ops,'a'))) + ht = aliastab; /* aliases */ + else + ht = cmdnamtab; /* external commands */ + + if (all) { + queue_signals(); + for (i = 0; i < ht->hsize; i++) { + for (hn = ht->nodes[i]; hn; hn = nhn) { + /* record pointer to next, since we may free this one */ + nhn = hn->next; + ht->freenode(ht->removenode(ht, hn->nam)); + } + } + unqueue_signals(); + return 0; + } + + /* With -m option, treat arguments as glob patterns. * + * "unhash -m '*'" is legal, but not recommended. */ + if (OPT_ISSET(ops,'m')) { + for (; *argv; argv++) { + queue_signals(); + /* expand argument */ + tokenize(*argv); + if ((pprog = patcompile(*argv, PAT_STATIC, NULL))) { + /* remove all nodes matching glob pattern */ + for (i = 0; i < ht->hsize; i++) { + for (hn = ht->nodes[i]; hn; hn = nhn) { + /* record pointer to next, since we may free this one */ + nhn = hn->next; + if (pattry(pprog, hn->nam)) { + ht->freenode(ht->removenode(ht, hn->nam)); + match++; + } + } + } + } else { + untokenize(*argv); + zwarnnam(name, "bad pattern : %s", *argv); + returnval = 1; + } + unqueue_signals(); + } + /* If we didn't match anything, we return 1. */ + if (!match) + returnval = 1; + return returnval; + } + + /* Take arguments literally -- do not glob */ + queue_signals(); + for (; *argv; argv++) { + if ((hn = ht->removenode(ht, *argv))) { + ht->freenode(hn); + } else if (func == BIN_UNSET && isset(POSIXBUILTINS)) { + /* POSIX: unset: "Unsetting a variable or function that was * + * not previously set shall not be considered an error." */ + returnval = 0; + } else { + zwarnnam(name, "no such hash table element: %s", *argv); + returnval = 1; + } + } + unqueue_signals(); + return returnval; +} + +/**** alias builtins ****/ + +/* alias: display or create aliases. */ + +/**/ +int +bin_alias(char *name, char **argv, Options ops, UNUSED(int func)) +{ + Alias a; + Patprog pprog; + Asgment asg; + int returnval = 0; + int flags1 = 0, flags2 = DISABLED; + int printflags = 0; + int type_opts; + HashTable ht = aliastab; + + /* Did we specify the type of alias? */ + type_opts = OPT_ISSET(ops, 'r') + OPT_ISSET(ops, 'g') + + OPT_ISSET(ops, 's'); + if (type_opts) { + if (type_opts > 1) { + zwarnnam(name, "illegal combination of options"); + return 1; + } + if (OPT_ISSET(ops,'g')) + flags1 |= ALIAS_GLOBAL; + else + flags2 |= ALIAS_GLOBAL; + if (OPT_ISSET(ops, 's')) { + /* + * Although we keep suffix aliases in a different table, + * it is useful to be able to distinguish Alias structures + * without reference to the table, so we have a separate + * flag, too. + */ + flags1 |= ALIAS_SUFFIX; + ht = sufaliastab; + } else + flags2 |= ALIAS_SUFFIX; + } + + if (OPT_ISSET(ops,'L')) + printflags |= PRINT_LIST; + else if (OPT_PLUS(ops,'g') || OPT_PLUS(ops,'r') || OPT_PLUS(ops,'s') || + OPT_PLUS(ops,'m') || OPT_ISSET(ops,'+')) + printflags |= PRINT_NAMEONLY; + + /* In the absence of arguments, list all aliases. If a command * + * line flag is specified, list only those of that type. */ + if (!*argv) { + queue_signals(); + scanhashtable(ht, 1, flags1, flags2, ht->printnode, printflags); + unqueue_signals(); + return 0; + } + + /* With the -m option, treat the arguments as * + * glob patterns of aliases to display. */ + if (OPT_ISSET(ops,'m')) { + for (; *argv; argv++) { + queue_signals(); + tokenize(*argv); /* expand argument */ + if ((pprog = patcompile(*argv, PAT_STATIC, NULL))) { + /* display the matching aliases */ + scanmatchtable(ht, pprog, 1, flags1, flags2, + ht->printnode, printflags); + } else { + untokenize(*argv); + zwarnnam(name, "bad pattern : %s", *argv); + returnval = 1; + } + unqueue_signals(); + } + return returnval; + } + + /* Take arguments literally. Don't glob */ + queue_signals(); + while ((asg = getasg(&argv, NULL))) { + if (asg->value.scalar && !OPT_ISSET(ops,'L')) { + /* The argument is of the form foo=bar and we are not * + * forcing a listing with -L, so define an alias */ + ht->addnode(ht, ztrdup(asg->name), + createaliasnode(ztrdup(asg->value.scalar), flags1)); + } else if ((a = (Alias) ht->getnode(ht, asg->name))) { + /* display alias if appropriate */ + if (!type_opts || ht == sufaliastab || + (OPT_ISSET(ops,'r') && + !(a->node.flags & (ALIAS_GLOBAL|ALIAS_SUFFIX))) || + (OPT_ISSET(ops,'g') && (a->node.flags & ALIAS_GLOBAL))) + ht->printnode(&a->node, printflags); + } else + returnval = 1; + } + unqueue_signals(); + return returnval; +} + + +/**** miscellaneous builtins ****/ + +/* true, : (colon) */ + +/**/ +int +bin_true(UNUSED(char *name), UNUSED(char **argv), UNUSED(Options ops), UNUSED(int func)) +{ + return 0; +} + +/* false builtin */ + +/**/ +int +bin_false(UNUSED(char *name), UNUSED(char **argv), UNUSED(Options ops), UNUSED(int func)) +{ + return 1; +} + +/* the zle buffer stack */ + +/**/ +mod_export LinkList bufstack; + +/* echo, print, printf, pushln */ + +#define print_val(VAL) \ + if (prec >= 0) \ + count += fprintf(fout, spec, width, prec, VAL); \ + else \ + count += fprintf(fout, spec, width, VAL); + +/* + * Because of the use of getkeystring() to interpret the arguments, + * the elements of args spend a large part of the function unmetafied + * with the lengths in len. This may have seemed a good idea once. + * As we are stuck with this for now, we need to be very careful + * deciding what state args is in. + */ + +/**/ +int +bin_print(char *name, char **args, Options ops, int func) +{ + int flen, width, prec, type, argc, n, narg, curlen = 0; + int nnl = 0, fmttrunc = 0, ret = 0, maxarg = 0, nc = 0; + int flags[6], *len, visarr = 0; + char *start, *endptr, *c, *d, *flag, *buf = NULL, spec[14], *fmt = NULL; + char **first, **argp, *curarg, *flagch = "'0+- #", save = '\0', nullstr = '\0'; + size_t rcount = 0, count = 0; + size_t *cursplit = 0, *splits = 0; + FILE *fout = stdout; +#ifdef HAVE_OPEN_MEMSTREAM + size_t mcount; +#define ASSIGN_MSTREAM(BUF,FOUT) \ + do { \ + if ((FOUT = open_memstream(&BUF, &mcount)) == NULL) { \ + zwarnnam(name, "open_memstream failed"); \ + return 1; \ + } \ + } while (0) + /* + * Some implementations of open_memstream() have a bug such that, + * if fflush() is followed by fclose(), another NUL byte is written + * to the buffer at the wrong position. Therefore we must fclose() + * before reading. + */ +#define READ_MSTREAM(BUF,FOUT) \ + ((fclose(FOUT) == 0) ? mcount : (size_t)-1) +#define CLOSE_MSTREAM(FOUT) 0 + +#else /* simulate HAVE_OPEN_MEMSTREAM */ + +#define ASSIGN_MSTREAM(BUF,FOUT) \ + do { \ + int tempfd; \ + char *tmpf; \ + if ((tempfd = gettempfile(NULL, 1, &tmpf)) < 0) { \ + zwarnnam(name, "can't open temp file: %e", errno); \ + return 1; \ + } \ + unlink(tmpf); \ + if ((FOUT = fdopen(tempfd, "w+")) == NULL) { \ + close(tempfd); \ + zwarnnam(name, "can't open temp file: %e", errno); \ + return 1; \ + } \ + } while (0) +#define READ_MSTREAM(BUF,FOUT) \ + ((((count = ftell(FOUT)), (BUF = (char *)zalloc(count + 1))) && \ + ((fseek(FOUT, 0L, SEEK_SET) == 0) && !(BUF[count] = '\0')) && \ + (fread(BUF, 1, count, FOUT) == count)) ? count : (size_t)-1) +#define CLOSE_MSTREAM(FOUT) fclose(FOUT) + +#endif + +#define IS_MSTREAM(FOUT) \ + (FOUT != stdout && \ + (OPT_ISSET(ops,'z') || OPT_ISSET(ops,'s') || OPT_ISSET(ops,'v'))) + + /* Testing EBADF special-cases >&- redirections */ +#define CLOSE_CLEANLY(FOUT) \ + (IS_MSTREAM(FOUT) ? CLOSE_MSTREAM(FOUT) == 0 : \ + ((FOUT == stdout) ? (fflush(FOUT) == 0 || errno == EBADF) : \ + (fclose(FOUT) == 0))) /* implies error for -u on a closed fd */ + + Histent ent; + mnumber mnumval; + double doubleval; + int intval; + zlong zlongval; + zulong zulongval; + char *stringval; + + /* Error check option combinations and option arguments */ + + if (OPT_ISSET(ops, 'z') + + OPT_ISSET(ops, 's') + OPT_ISSET(ops, 'S') + + OPT_ISSET(ops, 'v') > 1) { + zwarnnam(name, "only one of -s, -S, -v, or -z allowed"); + return 1; + } + if ((OPT_ISSET(ops, 'z') | OPT_ISSET(ops, 's') | OPT_ISSET(ops, 'S')) + + (OPT_ISSET(ops, 'c') | OPT_ISSET(ops, 'C')) > 1) { + zwarnnam(name, "-c or -C not allowed with -s, -S, or -z"); + return 1; + } + if ((OPT_ISSET(ops, 'z') | OPT_ISSET(ops, 'v') | + OPT_ISSET(ops, 's') | OPT_ISSET(ops, 'S')) + + (OPT_ISSET(ops, 'p') | OPT_ISSET(ops, 'u')) > 1) { + zwarnnam(name, "-p or -u not allowed with -s, -S, -v, or -z"); + return 1; + } + /* + if (OPT_ISSET(ops, 'f') && + (OPT_ISSET(ops, 'S') || OPT_ISSET(ops, 'c') || OPT_ISSET(ops, 'C'))) { + zwarnnam(name, "-f not allowed with -c, -C, or -S"); + return 1; + } + */ + + /* -C -- number of columns */ + if (!fmt && OPT_ISSET(ops,'C')) { + char *eptr, *argptr = OPT_ARG(ops,'C'); + nc = (int)zstrtol(argptr, &eptr, 10); + if (*eptr) { + zwarnnam(name, "number expected after -%c: %s", 'C', argptr); + return 1; + } + if (nc <= 0) { + zwarnnam(name, "invalid number of columns: %s", argptr); + return 1; + } + } + + if (func == BIN_PRINTF) { + if (!strcmp(*args, "--") && !*++args) { + zwarnnam(name, "not enough arguments"); + return 1; + } + fmt = *args++; + } else if (func == BIN_ECHO && isset(BSDECHO)) + ops->ind['E'] = 1; + else if (OPT_HASARG(ops,'f')) + fmt = OPT_ARG(ops,'f'); + if (fmt) + fmt = getkeystring(fmt, &flen, OPT_ISSET(ops,'b') ? GETKEYS_BINDKEY : + GETKEYS_PRINTF_FMT, &fmttrunc); + + first = args; + + /* -m option -- treat the first argument as a pattern and remove + * arguments not matching */ + if (OPT_ISSET(ops,'m')) { + Patprog pprog; + char **t, **p; + + if (!*args) { + zwarnnam(name, "no pattern specified"); + return 1; + } + queue_signals(); + tokenize(*args); + if (!(pprog = patcompile(*args, PAT_STATIC, NULL))) { + untokenize(*args); + zwarnnam(name, "bad pattern: %s", *args); + unqueue_signals(); + return 1; + } + for (t = p = ++args; *p; p++) + if (pattry(pprog, *p)) + *t++ = *p; + *t = NULL; + first = args; + unqueue_signals(); + if (fmt && !*args) return 0; + } + /* compute lengths, and interpret according to -P, -D, -e, etc. */ + argc = arrlen(args); + len = (int *) hcalloc(argc * sizeof(int)); + for (n = 0; n < argc; n++) { + /* first \ sequences */ + if (fmt || + (!OPT_ISSET(ops,'e') && + (OPT_ISSET(ops,'R') || OPT_ISSET(ops,'r') || OPT_ISSET(ops,'E')))) + unmetafy(args[n], &len[n]); + else { + int escape_how; + if (OPT_ISSET(ops,'b')) + escape_how = GETKEYS_BINDKEY; + else if (func != BIN_ECHO && !OPT_ISSET(ops,'e')) + escape_how = GETKEYS_PRINT; + else + escape_how = GETKEYS_ECHO; + args[n] = getkeystring(args[n], &len[n], escape_how, &nnl); + if (nnl) { + /* If there was a \c escape, make this the last arg. */ + argc = n + 1; + args[argc] = NULL; + } + } + /* -P option -- interpret as a prompt sequence */ + if (OPT_ISSET(ops,'P')) { + /* + * promptexpand uses permanent storage: to avoid + * messy memory management, stick it on the heap + * instead. + */ + char *str = unmetafy( + promptexpand(metafy(args[n], len[n], META_NOALLOC), + 0, NULL, NULL, NULL), + &len[n]); + args[n] = dupstrpfx(str, len[n]); + free(str); + } + /* -D option -- interpret as a directory, and use ~ */ + if (OPT_ISSET(ops,'D')) { + Nameddir d; + + queue_signals(); + /* TODO: finddir takes a metafied file */ + d = finddir(args[n]); + if (d) { + int dirlen = strlen(d->dir); + char *arg = zhalloc(len[n] - dirlen + strlen(d->node.nam) + 2); + sprintf(arg, "~%s%s", d->node.nam, args[n] + dirlen); + args[n] = arg; + len[n] = strlen(args[n]); + } + unqueue_signals(); + } + } + + /* -o and -O -- sort the arguments */ + if (OPT_ISSET(ops,'o') || OPT_ISSET(ops,'O')) { + int flags; + + if (fmt && !*args) + return 0; + flags = OPT_ISSET(ops,'i') ? SORTIT_IGNORING_CASE : 0; + if (OPT_ISSET(ops,'O')) + flags |= SORTIT_BACKWARDS; + strmetasort(args, flags, len); + } + + /* -u and -p -- output to other than standard output */ + if ((OPT_HASARG(ops,'u') || OPT_ISSET(ops,'p')) && + /* rule out conflicting options -- historical precedence */ + ((!fmt && (OPT_ISSET(ops,'c') || OPT_ISSET(ops,'C'))) || + !(OPT_ISSET(ops, 'z') || OPT_ISSET(ops, 'v') || + OPT_ISSET(ops, 's') || OPT_ISSET(ops, 'S')))) { + int fdarg, fd; + + if (OPT_ISSET(ops, 'p')) { + fdarg = coprocout; + if (fdarg < 0) { + zwarnnam(name, "-p: no coprocess"); + return 1; + } + } else { + char *argptr = OPT_ARG(ops,'u'), *eptr; + /* Handle undocumented feature that -up worked */ + if (!strcmp(argptr, "p")) { + fdarg = coprocout; + if (fdarg < 0) { + zwarnnam(name, "-p: no coprocess"); + return 1; + } + } else { + fdarg = (int)zstrtol(argptr, &eptr, 10); + if (*eptr) { + zwarnnam(name, "number expected after -u: %s", argptr); + return 1; + } + } + } + + if ((fd = dup(fdarg)) < 0) { + zwarnnam(name, "bad file number: %d", fdarg); + return 1; + } + if ((fout = fdopen(fd, "w")) == 0) { + close(fd); + zwarnnam(name, "bad mode on fd %d", fd); + return 1; + } + } + + if (OPT_ISSET(ops, 'v') || + (fmt && (OPT_ISSET(ops,'z') || OPT_ISSET(ops,'s')))) + ASSIGN_MSTREAM(buf,fout); + + /* -c -- output in columns */ + if (!fmt && (OPT_ISSET(ops,'c') || OPT_ISSET(ops,'C'))) { + int l, nr, sc, n, t, i; +#ifdef MULTIBYTE_SUPPORT + int *widths; + + if (isset(MULTIBYTE)) { + int *wptr; + + /* + * We need the character widths to align output in + * columns. + */ + wptr = widths = (int *) zhalloc(argc * sizeof(int)); + for (i = 0; i < argc && args[i]; i++, wptr++) { + int l = len[i], width = 0; + char *aptr = args[i]; + mbstate_t mbs; + + memset(&mbs, 0, sizeof(mbstate_t)); + while (l > 0) { + wchar_t wc; + size_t cnt; + int wcw; + + /* + * Prevent misaligned columns due to escape sequences by + * skipping over them. Octals \033 and \233 are the + * possible escape characters recognized by ANSI. + * + * It ought to be possible to do this in the case + * of prompt expansion by propagating the information + * about escape sequences (currently we strip this + * out). + */ + if (*aptr == '\033' || *aptr == '\233') { + for (aptr++, l--; + l && !isalpha(STOUC(*aptr)); + aptr++, l--) + ; + aptr++; + l--; + continue; + } + + cnt = mbrtowc(&wc, aptr, l, &mbs); + + if (cnt == MB_INCOMPLETE || cnt == MB_INVALID) + { + /* treat as ordinary string */ + width += l; + break; + } + wcw = WCWIDTH(wc); + /* treat unprintable as 0 */ + if (wcw > 0) + width += wcw; + /* skip over NUL normally */ + if (cnt == 0) + cnt = 1; + aptr += cnt; + l -= cnt; + } + widths[i] = width; + } + } + else + widths = len; +#else + int *widths = len; +#endif + + if (OPT_ISSET(ops,'C')) { + /* + * n: number of elements + * nc: number of columns (above) + * nr: number of rows + */ + n = arrlen(args); + nr = (n + nc - 1) / nc; + + /* + * i: loop counter + * l: maximum length seen + * + * Ignore lengths in last column since they don't affect + * the separation. + */ + for (i = l = 0; i < argc; i++) { + if (OPT_ISSET(ops, 'a')) { + if ((i % nc) == nc - 1) + continue; + } else { + if (i >= nr * (nc - 1)) + break; + } + if (l < widths[i]) + l = widths[i]; + } + sc = l + 2; + } + else + { + /* + * n: loop counter + * l: maximum length seen + */ + for (n = l = 0; n < argc; n++) + if (l < widths[n]) + l = widths[n]; + + /* + * sc: column width + * nc: number of columns (at least one) + */ + sc = l + 2; + nc = (zterm_columns + 1) / sc; + if (!nc) + nc = 1; + nr = (n + nc - 1) / nc; + } + + if (OPT_ISSET(ops,'a')) /* print across, i.e. columns first */ + n = 0; + for (i = 0; i < nr; i++) { + if (OPT_ISSET(ops,'a')) + { + int ic; + for (ic = 0; ic < nc && n < argc; ic++, n++) + { + fwrite(args[n], len[n], 1, fout); + l = widths[n]; + if (n < argc) + for (; l < sc; l++) + fputc(' ', fout); + } + } + else + { + n = i; + do { + fwrite(args[n], len[n], 1, fout); + l = widths[n]; + for (t = nr; t && n < argc; t--, n++); + if (n < argc) + for (; l < sc; l++) + fputc(' ', fout); + } while (n < argc); + } + fputc(OPT_ISSET(ops,'N') ? '\0' : '\n', fout); + } + if (IS_MSTREAM(fout) && (rcount = READ_MSTREAM(buf,fout)) == -1) + ret = 1; + if (!CLOSE_CLEANLY(fout) || ret) { + zwarnnam(name, "write error: %e", errno); + ret = 1; + } + if (buf) { + /* assert: we must be doing -v at this point */ + queue_signals(); + if (ret) + free(buf); + else + setsparam(OPT_ARG(ops, 'v'), + metafy(buf, rcount, META_REALLOC)); + unqueue_signals(); + } + return ret; + } + + /* normal output */ + if (!fmt) { + if (OPT_ISSET(ops, 'z') || OPT_ISSET(ops, 'v') || + OPT_ISSET(ops, 's') || OPT_ISSET(ops, 'S')) { + /* + * We don't want the arguments unmetafied after all. + */ + for (n = 0; n < argc; n++) + metafy(args[n], len[n], META_NOALLOC); + } + + /* -z option -- push the arguments onto the editing buffer stack */ + if (OPT_ISSET(ops,'z')) { + queue_signals(); + zpushnode(bufstack, sepjoin(args, NULL, 0)); + unqueue_signals(); + return 0; + } + /* -s option -- add the arguments to the history list */ + if (OPT_ISSET(ops,'s') || OPT_ISSET(ops,'S')) { + int nwords = 0, nlen, iwords; + char **pargs = args; + + queue_signals(); + while (*pargs++) + nwords++; + if (nwords) { + if (OPT_ISSET(ops,'S')) { + int wordsize; + short *words; + if (nwords > 1) { + zwarnnam(name, "option -S takes a single argument"); + unqueue_signals(); + return 1; + } + words = NULL; + wordsize = 0; + histsplitwords(*args, &words, &wordsize, &nwords, 1); + ent = prepnexthistent(); + ent->words = (short *)zalloc(nwords*sizeof(short)); + memcpy(ent->words, words, nwords*sizeof(short)); + free(words); + ent->nwords = nwords/2; + } else { + ent = prepnexthistent(); + ent->words = (short *)zalloc(nwords*2*sizeof(short)); + ent->nwords = nwords; + nlen = iwords = 0; + for (pargs = args; *pargs; pargs++) { + ent->words[iwords++] = nlen; + nlen += strlen(*pargs); + ent->words[iwords++] = nlen; + nlen++; + } + } + } else { + ent = prepnexthistent(); + ent->words = (short *)NULL; + } + ent->node.nam = zjoin(args, ' ', 0); + ent->stim = ent->ftim = time(NULL); + ent->node.flags = 0; + addhistnode(histtab, ent->node.nam, ent); + unqueue_signals(); + return 0; + } + + if (OPT_HASARG(ops, 'x') || OPT_HASARG(ops, 'X')) { + char *eptr; + int expand, startpos = 0; + int all = OPT_HASARG(ops, 'X'); + char *xarg = all ? OPT_ARG(ops, 'X') : OPT_ARG(ops, 'x'); + + expand = (int)zstrtol(xarg, &eptr, 10); + if (*eptr || expand <= 0) { + zwarnnam(name, "positive integer expected after -%c: %s", 'x', + xarg); + return 1; + } + for (; *args; args++, len++) { + startpos = zexpandtabs(*args, *len, expand, startpos, fout, + all); + if (args[1]) { + if (OPT_ISSET(ops, 'l')) { + fputc('\n', fout); + startpos = 0; + } else if (OPT_ISSET(ops,'N')) { + fputc('\0', fout); + } else { + fputc(' ', fout); + startpos++; + } + } + } + } else { + for (; *args; args++, len++) { + fwrite(*args, *len, 1, fout); + if (args[1]) + fputc(OPT_ISSET(ops,'l') ? '\n' : + OPT_ISSET(ops,'N') ? '\0' : ' ', fout); + } + } + if (!(OPT_ISSET(ops,'n') || nnl || + (OPT_ISSET(ops, 'v') && !OPT_ISSET(ops, 'l')))) + fputc(OPT_ISSET(ops,'N') ? '\0' : '\n', fout); + if (IS_MSTREAM(fout) && (rcount = READ_MSTREAM(buf,fout)) == -1) + ret = 1; + if (!CLOSE_CLEANLY(fout) || ret) { + zwarnnam(name, "write error: %e", errno); + ret = 1; + } + if (buf) { + /* assert: we must be doing -v at this point */ + queue_signals(); + if (ret) + free(buf); + else + setsparam(OPT_ARG(ops, 'v'), + metafy(buf, rcount, META_REALLOC)); + unqueue_signals(); + } + return ret; + } + + /* + * All the remaining code in this function is for printf-style + * output (printf itself, or print -f). We still have to handle + * special cases of printing to a ZLE buffer or the history, however. + */ + + if (OPT_ISSET(ops,'v')) { + struct value vbuf; + char* s = OPT_ARG(ops,'v'); + Value v = getvalue(&vbuf, &s, 0); + visarr = v && PM_TYPE(v->pm->node.flags) == PM_ARRAY; + } + /* printf style output */ + *spec = '%'; + argp = args; + do { + rcount = count; + if (argp > args && visarr) { /* reusing format string */ + if (!splits) + cursplit = splits = (size_t *)zhalloc(sizeof(size_t) * + (arrlen(args) / (argp - args) + 1)); + *cursplit++ = count; + } + if (maxarg) { + first += maxarg; + argc -= maxarg; + maxarg = 0; + } + for (c = fmt; c-fmt < flen; c++) { + if (*c != '%') { + putc(*c, fout); + ++count; + continue; + } + + start = c++; + if (*c == '%') { + putc('%', fout); + ++count; + continue; + } + + type = prec = -1; + width = 0; + curarg = NULL; + d = spec + 1; + + if (*c >= '1' && *c <= '9') { + narg = strtoul(c, &endptr, 0); + if (*endptr == '$') { + c = endptr + 1; + DPUTS(narg <= 0, "specified zero or negative arg"); + if (narg > argc) { + zwarnnam(name, "%d: argument specifier out of range", + narg); + if (fout != stdout) + fclose(fout); +#ifdef HAVE_OPEN_MEMSTREAM + if (buf) + free(buf); +#endif + return 1; + } else { + if (narg > maxarg) maxarg = narg; + curarg = *(first + narg - 1); + curlen = len[first - args + narg - 1]; + } + } + } + + /* copy only one of each flag as spec has finite size */ + memset(flags, 0, sizeof(flags)); + while (*c && (flag = strchr(flagch, *c))) { + if (!flags[flag - flagch]) { + flags[flag - flagch] = 1; + *d++ = *c; + } + c++; + } + + if (idigit(*c)) { + width = strtoul(c, &endptr, 0); + c = endptr; + } else if (*c == '*') { + if (idigit(*++c)) { + narg = strtoul(c, &endptr, 0); + if (*endptr == '$') { + c = endptr + 1; + if (narg > argc || narg <= 0) { + zwarnnam(name, + "%d: argument specifier out of range", + narg); + if (fout != stdout) + fclose(fout); +#ifdef HAVE_OPEN_MEMSTREAM + if (buf) + free(buf); +#endif + return 1; + } else { + if (narg > maxarg) maxarg = narg; + argp = first + narg - 1; + } + } + } + if (*argp) { + width = (int)mathevali(*argp++); + if (errflag) { + errflag &= ~ERRFLAG_ERROR; + ret = 1; + } + } + } + *d++ = '*'; + + if (*c == '.') { + if (*++c == '*') { + if (idigit(*++c)) { + narg = strtoul(c, &endptr, 0); + if (*endptr == '$') { + c = endptr + 1; + if (narg > argc || narg <= 0) { + zwarnnam(name, + "%d: argument specifier out of range", + narg); + if (fout != stdout) + fclose(fout); +#ifdef HAVE_OPEN_MEMSTREAM + if (buf) + free(buf); +#endif + return 1; + } else { + if (narg > maxarg) maxarg = narg; + argp = first + narg - 1; + } + } + } + + if (*argp) { + prec = (int)mathevali(*argp++); + if (errflag) { + errflag &= ~ERRFLAG_ERROR; + ret = 1; + } + } + } else if (idigit(*c)) { + prec = strtoul(c, &endptr, 0); + c = endptr; + } else + prec = 0; + if (prec >= 0) *d++ = '.', *d++ = '*'; + } + + /* ignore any size modifier */ + if (*c == 'l' || *c == 'L' || *c == 'h') c++; + + if (!curarg && *argp) { + curarg = *argp; + curlen = len[argp++ - args]; + } + d[1] = '\0'; + switch (*d = *c) { + case 'c': + if (curarg) + intval = *curarg; + else + intval = 0; + print_val(intval); + break; + case 's': + case 'b': + if (curarg) { + char *b, *ptr; + int lbytes, lchars, lleft; +#ifdef MULTIBYTE_SUPPORT + mbstate_t mbs; +#endif + + if (*c == 'b') { + b = getkeystring(metafy(curarg, curlen, META_USEHEAP), + &lbytes, + OPT_ISSET(ops,'b') ? GETKEYS_BINDKEY : + GETKEYS_PRINTF_ARG, &nnl); + } else { + b = curarg; + lbytes = curlen; + } + /* + * Handle width/precision here and use fwrite so that + * nul characters can be output. + * + * First, examine width of string given that it + * may contain multibyte characters. The output + * widths are for characters, so we need to count + * (in lchars). However, if we need to truncate + * the string we need the width in bytes (in lbytes). + */ + ptr = b; +#ifdef MULTIBYTE_SUPPORT + memset(&mbs, 0, sizeof(mbs)); +#endif + + for (lchars = 0, lleft = lbytes; lleft > 0; lchars++) { + int chars; + + if (lchars == prec) { + /* Truncate at this point. */ + lbytes = ptr - b; + break; + } +#ifdef MULTIBYTE_SUPPORT + if (isset(MULTIBYTE)) { + chars = mbrlen(ptr, lleft, &mbs); + if (chars < 0) { + /* + * Invalid/incomplete character at this + * point. Assume all the rest are a + * single byte. That's about the best we + * can do. + */ + lchars += lleft; + lbytes = (ptr - b) + lleft; + break; + } else if (chars == 0) { + /* NUL, handle as real character */ + chars = 1; + } + } + else /* use the non-multibyte code below */ +#endif + chars = 1; /* compiler can optimise this...*/ + lleft -= chars; + ptr += chars; + } + if (width > 0 && flags[3]) width = -width; + if (width > 0 && lchars < width) + count += fprintf(fout, "%*c", width - lchars, ' '); + count += fwrite(b, 1, lbytes, fout); + if (width < 0 && lchars < -width) + count += fprintf(fout, "%*c", -width - lchars, ' '); + if (nnl) { + /* If the %b arg had a \c escape, truncate the fmt. */ + flen = c - fmt + 1; + fmttrunc = 1; + } + } else if (width) + count += fprintf(fout, "%*c", width, ' '); + break; + case 'q': + stringval = curarg ? + quotestring(metafy(curarg, curlen, META_USEHEAP), + QT_BACKSLASH_SHOWNULL) : &nullstr; + *d = 's'; + print_val(unmetafy(stringval, &curlen)); + break; + case 'd': + case 'i': + type=1; + break; + case 'e': + case 'E': + case 'f': + case 'g': + case 'G': + type=2; + break; + case 'o': + case 'u': + case 'x': + case 'X': + type=3; + break; + case 'n': + if (curarg) setiparam(curarg, count - rcount); + break; + default: + if (*c) { + save = c[1]; + c[1] = '\0'; + } + zwarnnam(name, "%s: invalid directive", start); + if (*c) c[1] = save; + /* Why do we care about a clean close here? */ + if (!CLOSE_CLEANLY(fout)) + zwarnnam(name, "write error: %e", errno); +#ifdef HAVE_OPEN_MEMSTREAM + if (buf) + free(buf); +#endif + return 1; + } + + if (type > 0) { + if (curarg && (*curarg == '\'' || *curarg == '"' )) { + convchar_t cc; +#ifdef MULTIBYTE_SUPPORT + if (isset(MULTIBYTE)) { + mb_charinit(); + (void)mb_metacharlenconv(metafy(curarg+1, curlen-1, + META_USEHEAP), &cc); + } + else + cc = WEOF; + if (cc == WEOF) + cc = (curlen > 1) ? STOUC(curarg[1]) : 0; +#else + cc = (curlen > 1) ? STOUC(curarg[1]) : 0; +#endif + if (type == 2) { + doubleval = cc; + print_val(doubleval); + } else { + intval = cc; + print_val(intval); + } + } else { + switch (type) { + case 1: +#ifdef ZSH_64_BIT_TYPE + *d++ = 'l'; +#endif + *d++ = 'l', *d++ = *c, *d = '\0'; + zlongval = (curarg) ? mathevali(curarg) : 0; + if (errflag) { + zlongval = 0; + errflag &= ~ERRFLAG_ERROR; + ret = 1; + } + print_val(zlongval) + break; + case 2: + if (curarg) { + char *eptr; + /* + * First attempt to parse as a floating + * point constant. If we go through + * a math evaluation, we can lose + * mostly unimportant information + * that people in standards organizations + * worry about. + */ + doubleval = strtod(curarg, &eptr); + /* + * If it didn't parse as a constant, + * parse it as an expression. + */ + if (*eptr != '\0') { + mnumval = matheval(curarg); + doubleval = (mnumval.type & MN_FLOAT) ? + mnumval.u.d : (double)mnumval.u.l; + } + } else doubleval = 0; + if (errflag) { + doubleval = 0; + errflag &= ~ERRFLAG_ERROR; + ret = 1; + } + /* force consistent form for Inf/NaN output */ + if (isnan(doubleval)) + count += fputs("nan", fout); + else if (isinf(doubleval)) + count += fputs((doubleval < 0.0) ? "-inf" : "inf", fout); + else + print_val(doubleval) + break; + case 3: +#ifdef ZSH_64_BIT_UTYPE + *d++ = 'l'; +#endif + *d++ = 'l', *d++ = *c, *d = '\0'; + if (!curarg) + zulongval = (zulong)0; + else if (!zstrtoul_underscore(curarg, &zulongval)) + zulongval = mathevali(curarg); + if (errflag) { + zulongval = 0; + errflag &= ~ERRFLAG_ERROR; + ret = 1; + } + print_val(zulongval) + } + } + } + if (maxarg && (argp - first > maxarg)) + maxarg = argp - first; + } + + if (maxarg) argp = first + maxarg; + /* if there are remaining args, reuse format string */ + } while (*argp && argp != first && !fmttrunc && !OPT_ISSET(ops,'r')); + + if (IS_MSTREAM(fout)) { + queue_signals(); + if ((rcount = READ_MSTREAM(buf,fout)) == -1) { + zwarnnam(name, "i/o error: %e", errno); + if (buf) + free(buf); + } else { + if (visarr && splits) { + char **arrayval = zshcalloc((cursplit - splits + 2) * sizeof(char *)); + for (;cursplit >= splits; cursplit--) { + int start = cursplit == splits ? 0 : cursplit[-1]; + arrayval[cursplit - splits] = + metafy(buf + start, count - start, META_DUP); + count = start; + } + setaparam(OPT_ARG(ops, 'v'), arrayval); + free(buf); + } else { + stringval = metafy(buf, rcount, META_REALLOC); + if (OPT_ISSET(ops,'z')) { + zpushnode(bufstack, stringval); + } else if (OPT_ISSET(ops,'v')) { + setsparam(OPT_ARG(ops, 'v'), stringval); + } else { + ent = prepnexthistent(); + ent->node.nam = stringval; + ent->stim = ent->ftim = time(NULL); + ent->node.flags = 0; + ent->words = (short *)NULL; + addhistnode(histtab, ent->node.nam, ent); + } + } + } + unqueue_signals(); + } + + if (!CLOSE_CLEANLY(fout)) + { + zwarnnam(name, "write error: %e", errno); + ret = 1; + } + return ret; +} + +/* shift builtin */ + +/**/ +int +bin_shift(char *name, char **argv, Options ops, UNUSED(int func)) +{ + int num = 1, l, ret = 0; + char **s; + + /* optional argument can be either numeric or an array */ + queue_signals(); + if (*argv && !getaparam(*argv)) { + num = mathevali(*argv++); + if (errflag) { + unqueue_signals(); + return 1; + } + } + + if (num < 0) { + unqueue_signals(); + zwarnnam(name, "argument to shift must be non-negative"); + return 1; + } + + if (*argv) { + for (; *argv; argv++) + if ((s = getaparam(*argv))) { + if (arrlen_lt(s, num)) { + zwarnnam(name, "shift count must be <= $#"); + ret++; + continue; + } + if (OPT_ISSET(ops,'p')) { + char **s2, **src, **dst; + int count; + l = arrlen(s); + src = s; + dst = s2 = (char **)zalloc((l - num + 1) * sizeof(char *)); + for (count = l - num; count; count--) + *dst++ = ztrdup(*src++); + *dst = NULL; + s = s2; + } else { + s = zarrdup(s + num); + } + setaparam(*argv, s); + } + } else { + if (num > (l = arrlen(pparams))) { + zwarnnam(name, "shift count must be <= $#"); + ret = 1; + } else { + s = zalloc((l - num + 1) * sizeof(char *)); + if (OPT_ISSET(ops,'p')) { + memcpy(s, pparams, (l - num) * sizeof(char *)); + s[l-num] = NULL; + while (num--) + zsfree(pparams[l-1-num]); + } else { + memcpy(s, pparams + num, (l - num + 1) * sizeof(char *)); + while (num--) + zsfree(pparams[num]); + } + zfree(pparams, (l + 1) * sizeof(char *)); + pparams = s; + } + } + unqueue_signals(); + return ret; +} + +/* + * Position of getopts option within OPTIND argument with multiple options. + */ + +/**/ +int optcind; + +/* getopts: automagical option handling for shell scripts */ + +/**/ +int +bin_getopts(UNUSED(char *name), char **argv, UNUSED(Options ops), UNUSED(int func)) +{ + int lenstr, lenoptstr, quiet, lenoptbuf; + char *optstr = unmetafy(*argv++, &lenoptstr), *var = *argv++; + char **args = (*argv) ? argv : pparams; + char *str, optbuf[2] = " ", *p, opch; + + /* zoptind keeps count of the current argument number. The * + * user can set it to zero to start a new option parse. */ + if (zoptind < 1) { + /* first call */ + zoptind = 1; + optcind = 0; + } + if (arrlen_lt(args, zoptind)) + /* no more options */ + return 1; + + /* leading ':' in optstr means don't print an error message */ + quiet = *optstr == ':'; + optstr += quiet; + lenoptstr -= quiet; + + /* find place in relevant argument */ + str = unmetafy(dupstring(args[zoptind - 1]), &lenstr); + if (!lenstr) /* Definitely not an option. */ + return 1; + if(optcind >= lenstr) { + optcind = 0; + if(!args[zoptind++]) + return 1; + str = unmetafy(dupstring(args[zoptind - 1]), &lenstr); + } + if(!optcind) { + if(lenstr < 2 || (*str != '-' && *str != '+')) + return 1; + if(lenstr == 2 && str[0] == '-' && str[1] == '-') { + zoptind++; + return 1; + } + optcind++; + } + opch = str[optcind++]; + if(str[0] == '+') { + optbuf[0] = '+'; + lenoptbuf = 2; + } else + lenoptbuf = 1; + optbuf[lenoptbuf - 1] = opch; + + /* check for legality */ + if(opch == ':' || !(p = memchr(optstr, opch, lenoptstr))) { + p = "?"; + err: + zsfree(zoptarg); + setsparam(var, ztrdup(p)); + if(quiet) { + zoptarg = metafy(optbuf, lenoptbuf, META_DUP); + } else { + zwarn(*p == '?' ? "bad option: %c%c" : + "argument expected after %c%c option", + "?-+"[lenoptbuf], opch); + zoptarg=ztrdup(""); + } + return 0; + } + + /* check for required argument */ + if(p[1] == ':') { + if(optcind == lenstr) { + if(!args[zoptind]) { + p = ":"; + goto err; + } + p = ztrdup(args[zoptind++]); + } else + p = metafy(str+optcind, lenstr-optcind, META_DUP); + /* + * Careful: I've just changed the following two lines from + * optcind = ztrlen(args[zoptind - 1]); + * and it's a rigorous theorem that every change in getopts breaks + * something. See zsh-workers/9095 for the bug fixed here. + * PWS 2000/05/02 + */ + optcind = 0; + zoptind++; + zsfree(zoptarg); + zoptarg = p; + } else { + zsfree(zoptarg); + zoptarg = ztrdup(""); + } + + setsparam(var, metafy(optbuf, lenoptbuf, META_DUP)); + return 0; +} + +/* Flag that we should exit the shell as soon as all functions return. */ +/**/ +mod_export int +exit_pending; + +/* Shell level at which we exit if exit_pending */ +/**/ +mod_export int +exit_level; + +/* break, bye, continue, exit, logout, return -- most of these take * + * one numeric argument, and the other (logout) is related to return. * + * (return is treated as a logout when in a login shell.) */ + +/**/ +int +bin_break(char *name, char **argv, UNUSED(Options ops), int func) +{ + int num = lastval, nump = 0, implicit; + + /* handle one optional numeric argument */ + implicit = !*argv; + if (*argv) { + num = mathevali(*argv++); + nump = 1; + } + + if (nump > 0 && (func == BIN_CONTINUE || func == BIN_BREAK) && num <= 0) { + zerrnam(name, "argument is not positive: %d", num); + return 1; + } + + switch (func) { + case BIN_CONTINUE: + if (!loops) { /* continue is only permitted in loops */ + zerrnam(name, "not in while, until, select, or repeat loop"); + return 1; + } + contflag = 1; /* FALLTHROUGH */ + case BIN_BREAK: + if (!loops) { /* break is only permitted in loops */ + zerrnam(name, "not in while, until, select, or repeat loop"); + return 1; + } + breaks = nump ? minimum(num,loops) : 1; + break; + case BIN_RETURN: + if ((isset(INTERACTIVE) && isset(SHINSTDIN)) + || locallevel || sourcelevel) { + retflag = 1; + breaks = loops; + lastval = num; + if (trap_state == TRAP_STATE_PRIMED && trap_return == -2 + /* + * With POSIX, "return" on its own in a trap doesn't + * update $? --- we keep the status from before the + * trap. + */ + && !(isset(POSIXTRAPS) && implicit)) { + trap_state = TRAP_STATE_FORCE_RETURN; + trap_return = lastval; + } + return lastval; + } + zexit(num, 0); /* else treat return as logout/exit */ + break; + case BIN_LOGOUT: + if (unset(LOGINSHELL)) { + zerrnam(name, "not login shell"); + return 1; + } + /*FALLTHROUGH*/ + case BIN_EXIT: + if (locallevel > forklevel && shell_exiting != -1) { + /* + * We don't exit directly from functions to allow tidying + * up, in particular EXIT traps. We still need to perform + * the usual interactive tests to see if we can exit at + * all, however. + * + * If we are forked, we exit the shell at the function depth + * at which we became a subshell, hence the comparison. + * + * If we are already exiting... give this all up as + * a bad job. + */ + if (stopmsg || (zexit(0,2), !stopmsg)) { + retflag = 1; + breaks = loops; + exit_pending = (num << 1) | 1; + exit_level = locallevel; + } + } else + zexit(num, 0); + break; + } + return 0; +} + +/* we have printed a 'you have stopped (running) jobs.' message */ + +/**/ +mod_export int stopmsg; + +/* check to see if user has jobs running/stopped */ + +/**/ +static void +checkjobs(void) +{ + int i; + + for (i = 1; i <= maxjob; i++) + if (i != thisjob && (jobtab[i].stat & STAT_LOCKED) && + !(jobtab[i].stat & STAT_NOPRINT) && + (isset(CHECKRUNNINGJOBS) || jobtab[i].stat & STAT_STOPPED)) + break; + if (i <= maxjob) { + if (jobtab[i].stat & STAT_STOPPED) { + +#ifdef USE_SUSPENDED + zerr("you have suspended jobs."); +#else + zerr("you have stopped jobs."); +#endif + + } else + zerr("you have running jobs."); + stopmsg = 1; + } +} + +/* + * -1 if the shell is already committed to exit. + * positive if zexit() was already called. + */ + +/**/ +int shell_exiting; + +/* exit the shell. val is the return value of the shell. * + * from_where is + * 1 if zexit is called because of a signal + * 2 if we can't actually exit yet (e.g. functions need + * terminating) but should perform the usual interactive tests. + */ + +/**/ +mod_export void +zexit(int val, int from_where) +{ + /* Don't do anything recursively: see below */ + if (shell_exiting == -1) + return; + + if (isset(MONITOR) && !stopmsg && from_where != 1) { + scanjobs(); /* check if jobs need printing */ + if (isset(CHECKJOBS)) + checkjobs(); /* check if any jobs are running/stopped */ + if (stopmsg) { + stopmsg = 2; + return; + } + } + /* Positive in_exit means we have been here before */ + if (from_where == 2 || (shell_exiting++ && from_where)) + return; + + /* + * We're now committed to exiting. Set shell_exiting to -1 to + * indicate we shouldn't do any recursive processing. + */ + shell_exiting = -1; + /* + * We want to do all remaining processing regardless of preceding + * errors, even user interrupts. + */ + errflag = 0; + + if (isset(MONITOR)) { + /* send SIGHUP to any jobs left running */ + killrunjobs(from_where == 1); + } + if (isset(RCS) && interact) { + if (!nohistsave) { + int writeflags = HFILE_USE_OPTIONS; + if (from_where == 1) + writeflags |= HFILE_NO_REWRITE; + saveandpophiststack(1, writeflags); + savehistfile(NULL, 1, writeflags); + } + if (islogin && !subsh) { + sourcehome(".zlogout"); +#ifdef GLOBAL_ZLOGOUT + if (isset(RCS) && isset(GLOBALRCS)) + source(GLOBAL_ZLOGOUT); +#endif + } + } + lastval = val; + /* + * Now we are committed to exiting any previous state + * is irrelevant. Ensure trap can run. + */ + errflag = intrap = 0; + if (sigtrapped[SIGEXIT]) + dotrap(SIGEXIT); + callhookfunc("zshexit", NULL, 1, NULL); + runhookdef(EXITHOOK, NULL); + if (opts[MONITOR] && interact && (SHTTY != -1)) { + release_pgrp(); + } + if (mypid != getpid()) + _exit(val); + else + exit(val); +} + +/* . (dot), source */ + +/**/ +int +bin_dot(char *name, char **argv, UNUSED(Options ops), UNUSED(int func)) +{ + char **old, *old0 = NULL; + int diddot = 0, dotdot = 0; + char *s, **t, *enam, *arg0, *buf; + struct stat st; + enum source_return ret; + + if (!*argv) + return 0; + old = pparams; + /* get arguments for the script */ + if (argv[1]) + pparams = zarrdup(argv + 1); + + enam = arg0 = ztrdup(*argv); + if (isset(FUNCTIONARGZERO)) { + old0 = argzero; + argzero = ztrdup(arg0); + } + s = unmeta(enam); + errno = ENOENT; + ret = SOURCE_NOT_FOUND; + /* for source only, check in current directory first */ + if (*name != '.' && access(s, F_OK) == 0 + && stat(s, &st) >= 0 && !S_ISDIR(st.st_mode)) { + diddot = 1; + ret = source(enam); + } + if (ret == SOURCE_NOT_FOUND) { + /* use a path with / in it */ + for (s = arg0; *s; s++) + if (*s == '/') { + if (*arg0 == '.') { + if (arg0 + 1 == s) + ++diddot; + else if (arg0[1] == '.' && arg0 + 2 == s) + ++dotdot; + } + ret = source(arg0); + break; + } + if (!*s || (ret == SOURCE_NOT_FOUND && + isset(PATHDIRS) && diddot < 2 && dotdot == 0)) { + pushheap(); + /* search path for script */ + for (t = path; *t; t++) { + if (!(*t)[0] || ((*t)[0] == '.' && !(*t)[1])) { + if (diddot) + continue; + diddot = 1; + buf = dupstring(arg0); + } else + buf = zhtricat(*t, "/", arg0); + + s = unmeta(buf); + if (access(s, F_OK) == 0 && stat(s, &st) >= 0 + && !S_ISDIR(st.st_mode)) { + ret = source(enam = buf); + break; + } + } + popheap(); + } + } + /* clean up and return */ + if (argv[1]) { + freearray(pparams); + pparams = old; + } + if (ret == SOURCE_NOT_FOUND) { + if (isset(POSIXBUILTINS)) { + /* hard error in POSIX (we'll exit later) */ + zerrnam(name, "%e: %s", errno, enam); + } else { + zwarnnam(name, "%e: %s", errno, enam); + } + } + zsfree(arg0); + if (old0) { + zsfree(argzero); + argzero = old0; + } + return ret == SOURCE_OK ? lastval : 128 - ret; +} + +/* + * common for bin_emulate and bin_eval + */ + +static int +eval(char **argv) +{ + Eprog prog; + char *oscriptname = scriptname; + int oineval = ineval, fpushed; + struct funcstack fstack; + + /* + * If EVALLINENO is not set, we use the line number of the + * environment and must flag this up to exec.c. Otherwise, + * we use a special script name to indicate the special line number. + */ + ineval = !isset(EVALLINENO); + if (!ineval) { + scriptname = "(eval)"; + fstack.prev = funcstack; + fstack.name = scriptname; + fstack.caller = funcstack ? funcstack->name : dupstring(argzero); + fstack.lineno = lineno; + fstack.tp = FS_EVAL; + + /* + * To get file line numbers, we need to know if parent is + * the original script/shell or a sourced file, in which + * case we use the line number raw, or a function or eval, + * in which case we need to deduce where that came from. + * + * This replicates the logic for working out the information + * for $funcfiletrace---eval is similar to an inlined function + * call from a tracing perspective. + */ + if (!funcstack || funcstack->tp == FS_SOURCE) { + fstack.flineno = fstack.lineno; + fstack.filename = fstack.caller; + } else { + fstack.flineno = funcstack->flineno + lineno; + /* + * Line numbers in eval start from 1, not zero, + * so offset by one to get line in file. + */ + if (funcstack->tp == FS_EVAL) + fstack.flineno--; + fstack.filename = funcstack->filename; + if (!fstack.filename) + fstack.filename = ""; + } + funcstack = &fstack; + + fpushed = 1; + } else + fpushed = 0; + + prog = parse_string(zjoin(argv, ' ', 1), 1); + if (prog) { + if (wc_code(*prog->prog) != WC_LIST) { + /* No code to execute */ + lastval = 0; + } else { + execode(prog, 1, 0, "eval"); + + if (errflag && !lastval) + lastval = errflag; + } + } else { + lastval = 1; + } + + if (fpushed) + funcstack = funcstack->prev; + + errflag &= ~ERRFLAG_ERROR; + scriptname = oscriptname; + ineval = oineval; + + return lastval; +} + +/* emulate: set emulation mode and optionally evaluate shell code */ + +/**/ +int +bin_emulate(char *nam, char **argv, Options ops, UNUSED(int func)) +{ + int opt_L = OPT_ISSET(ops, 'L'); + int opt_R = OPT_ISSET(ops, 'R'); + int opt_l = OPT_ISSET(ops, 'l'); + int saveemulation, savehackchar; + int ret = 1, new_emulation; + unsigned int savepatterns; + char saveopts[OPT_SIZE], new_opts[OPT_SIZE]; + char *cmd = 0; + const char *shname = *argv; + LinkList optlist; + LinkNode optnode; + Emulation_options save_sticky; + OptIndex *on_ptr, *off_ptr; + + /* without arguments just print current emulation */ + if (!shname) { + if (opt_L || opt_R) { + zwarnnam(nam, "not enough arguments"); + return 1; + } + + switch(SHELL_EMULATION()) { + case EMULATE_CSH: + shname = "csh"; + break; + + case EMULATE_KSH: + shname = "ksh"; + break; + + case EMULATE_SH: + shname = "sh"; + break; + + default: + shname = "zsh"; + break; + } + + printf("%s\n", shname); + return 0; + } + + /* with single argument set current emulation */ + if (!argv[1]) { + char *cmdopts; + if (opt_l) { + cmdopts = (char *)zhalloc(OPT_SIZE); + memcpy(cmdopts, opts, OPT_SIZE); + } else + cmdopts = opts; + emulate(shname, opt_R, &emulation, cmdopts); + if (opt_L) + cmdopts[LOCALOPTIONS] = cmdopts[LOCALTRAPS] = + cmdopts[LOCALPATTERNS] = 1; + if (opt_l) { + list_emulate_options(cmdopts, opt_R); + return 0; + } + clearpatterndisables(); + return 0; + } + + if (opt_l) { + zwarnnam(nam, "too many arguments for -l"); + return 1; + } + + argv++; + memcpy(saveopts, opts, sizeof(opts)); + memcpy(new_opts, opts, sizeof(opts)); + savehackchar = keyboardhackchar; + emulate(shname, opt_R, &new_emulation, new_opts); + optlist = newlinklist(); + if (parseopts(nam, &argv, new_opts, &cmd, optlist, 0)) { + ret = 1; + goto restore; + } + + /* parseopts() has consumed anything that looks like an option */ + if (*argv) { + zwarnnam(nam, "unknown argument %s", *argv); + goto restore; + } + + savepatterns = savepatterndisables(); + /* + * All emulations start with an empty set of pattern disables, + * hence no special "sticky" behaviour is required. + */ + clearpatterndisables(); + + saveemulation = emulation; + emulation = new_emulation; + memcpy(opts, new_opts, sizeof(opts)); + /* If "-c command" is given, evaluate command using specified + * emulation mode. + */ + if (cmd) { + if (opt_L) { + zwarnnam(nam, "option -L incompatible with -c"); + goto restore2; + } + *--argv = cmd; /* on stack, never free()d, see execbuiltin() */ + } else { + if (opt_L) + opts[LOCALOPTIONS] = opts[LOCALTRAPS] = opts[LOCALPATTERNS] = 1; + return 0; + } + + save_sticky = sticky; + sticky = hcalloc(sizeof(*sticky)); + sticky->emulation = emulation; + for (optnode = firstnode(optlist); optnode; incnode(optnode)) { + /* Data is index into new_opts */ + char *optptr = (char *)getdata(optnode); + if (*optptr) + sticky->n_on_opts++; + else + sticky->n_off_opts++; + } + if (sticky->n_on_opts) + on_ptr = sticky->on_opts = + zhalloc(sticky->n_on_opts * sizeof(*sticky->on_opts)); + else + on_ptr = NULL; + if (sticky->n_off_opts) + off_ptr = sticky->off_opts = zhalloc(sticky->n_off_opts * + sizeof(*sticky->off_opts)); + else + off_ptr = NULL; + for (optnode = firstnode(optlist); optnode; incnode(optnode)) { + /* Data is index into new_opts */ + char *optptr = (char *)getdata(optnode); + int optno = optptr - new_opts; + if (*optptr) + *on_ptr++ = optno; + else + *off_ptr++ = optno; + } + ret = eval(argv); + sticky = save_sticky; +restore2: + emulation = saveemulation; + memcpy(opts, saveopts, sizeof(opts)); + restorepatterndisables(savepatterns); +restore: + keyboardhackchar = savehackchar; + inittyptab(); /* restore banghist */ + return ret; +} + +/* eval: simple evaluation */ + +/**/ +mod_export int ineval; + +/**/ +int +bin_eval(UNUSED(char *nam), char **argv, UNUSED(Options ops), UNUSED(int func)) +{ + return eval(argv); +} + +static char *zbuf; +static int readfd; + +/* Read a character from readfd, or from the buffer zbuf. Return EOF on end of +file/buffer. */ + +/* read: get a line of input, or (for compctl functions) return some * + * useful data about the state of the editing line. The -E and -e * + * options mean that the result should be sent to stdout. -e means, * + * in addition, that the result should not actually be assigned to * + * the specified parameters. */ + +/**/ +int +bin_read(char *name, char **args, Options ops, UNUSED(int func)) +{ + char *reply, *readpmpt; + int bsiz, c = 0, gotnl = 0, al = 0, first, nchars = 1, bslash, keys = 0; + int haso = 0; /* true if /dev/tty has been opened specially */ + int isem = !strcmp(term, "emacs"), izle = zleactive; + char *buf, *bptr, *firstarg, *zbuforig; + LinkList readll = newlinklist(); + FILE *oshout = NULL; + int readchar = -1, val, resettty = 0; + struct ttyinfo saveti; + char d; + long izle_timeout = 0; +#ifdef MULTIBYTE_SUPPORT + wchar_t delim = L'\n', wc; + mbstate_t mbs; + char *laststart; + size_t ret; +#else + char delim = '\n'; +#endif + + if (OPT_HASARG(ops,c='k')) { + char *eptr, *optarg = OPT_ARG(ops,c); + nchars = (int)zstrtol(optarg, &eptr, 10); + if (*eptr) { + zwarnnam(name, "number expected after -%c: %s", c, optarg); + return 1; + } + } + /* This `*args++ : *args' looks a bit weird, but it works around a bug + * in gcc-2.8.1 under DU 4.0. */ + firstarg = (*args && **args == '?' ? *args++ : *args); + reply = *args ? *args++ : OPT_ISSET(ops,'A') ? "reply" : "REPLY"; + + if (OPT_ISSET(ops,'A') && *args) { + zwarnnam(name, "only one array argument allowed"); + return 1; + } + + /* handle compctl case */ + if(OPT_ISSET(ops,'l') || OPT_ISSET(ops,'c')) + return compctlreadptr(name, args, ops, reply); + + if ((OPT_ISSET(ops,'k') || OPT_ISSET(ops,'q')) && + !OPT_ISSET(ops,'u') && !OPT_ISSET(ops,'p')) { + if (!zleactive) { + if (SHTTY == -1) { + /* need to open /dev/tty specially */ + if ((SHTTY = open("/dev/tty", O_RDWR|O_NOCTTY)) != -1) { + haso = 1; + oshout = shout; + init_shout(); + } + } else if (!shout) { + /* We need an output FILE* on the tty */ + init_shout(); + } + /* We should have a SHTTY opened by now. */ + if (SHTTY == -1) { + /* Unfortunately, we didn't. */ + fprintf(stderr, "not interactive and can't open terminal\n"); + fflush(stderr); + return 1; + } + if (unset(INTERACTIVE)) + gettyinfo(&shttyinfo); + /* attach to the tty */ + attachtty(mypgrp); + if (!isem) + setcbreak(); + readfd = SHTTY; + } + keys = 1; + } else if (OPT_HASARG(ops,'u') && !OPT_ISSET(ops,'p')) { + /* -u means take input from the specified file descriptor. */ + char *eptr, *argptr = OPT_ARG(ops,'u'); + /* The old code handled -up, but that was never documented. Still...*/ + if (!strcmp(argptr, "p")) { + readfd = coprocin; + if (readfd < 0) { + zwarnnam(name, "-p: no coprocess"); + return 1; + } + } else { + readfd = (int)zstrtol(argptr, &eptr, 10); + if (*eptr) { + zwarnnam(name, "number expected after -%c: %s", 'u', argptr); + return 1; + } + } +#if 0 + /* This code is left as a warning to future generations --- pws. */ + for (readfd = 9; readfd && !OPT_ISSET(ops,readfd + '0'); --readfd); +#endif + izle = 0; + } else if (OPT_ISSET(ops,'p')) { + readfd = coprocin; + if (readfd < 0) { + zwarnnam(name, "-p: no coprocess"); + return 1; + } + izle = 0; + } else + readfd = izle = 0; + + if (OPT_ISSET(ops,'s') && SHTTY != -1) { + struct ttyinfo ti; + gettyinfo(&ti); + saveti = ti; + resettty = 1; +#ifdef HAS_TIO + ti.tio.c_lflag &= ~ECHO; +#else + ti.sgttyb.sg_flags &= ~ECHO; +#endif + settyinfo(&ti); + } + + /* handle prompt */ + if (firstarg) { + for (readpmpt = firstarg; + *readpmpt && *readpmpt != '?'; readpmpt++); + if (*readpmpt++) { + if (keys || isatty(0)) { + zputs(readpmpt, (shout ? shout : stderr)); + fflush(shout ? shout : stderr); + } + readpmpt[-1] = '\0'; + } + } + + if (OPT_ISSET(ops,'d')) { + char *delimstr = OPT_ARG(ops,'d'); +#ifdef MULTIBYTE_SUPPORT + wint_t wi; + + if (isset(MULTIBYTE)) { + mb_charinit(); + (void)mb_metacharlenconv(delimstr, &wi); + } + else + wi = WEOF; + if (wi != WEOF) + delim = (wchar_t)wi; + else + delim = (wchar_t)((delimstr[0] == Meta) ? + delimstr[1] ^ 32 : delimstr[0]); +#else + delim = (delimstr[0] == Meta) ? delimstr[1] ^ 32 : delimstr[0]; +#endif + if (SHTTY != -1) { + struct ttyinfo ti; + gettyinfo(&ti); + if (! resettty) { + saveti = ti; + resettty = 1; + } +#ifdef HAS_TIO + ti.tio.c_lflag &= ~ICANON; + ti.tio.c_cc[VMIN] = 1; + ti.tio.c_cc[VTIME] = 0; +#else + ti.sgttyb.sg_flags |= CBREAK; +#endif + settyinfo(&ti); + } + } + if (OPT_ISSET(ops,'t')) { + zlong timeout = 0; + if (OPT_HASARG(ops,'t')) { + mnumber mn = zero_mnumber; + mn = matheval(OPT_ARG(ops,'t')); + if (errflag) + return 1; + if (mn.type == MN_FLOAT) { + mn.u.d *= 1e6; + timeout = (zlong)mn.u.d; + } else { + timeout = (zlong)mn.u.l * (zlong)1000000; + } + } + if (izle) { + /* + * Timeout is in 100ths of a second rather than us. + * See calc_timeout() in zle_main for format of this. + */ + timeout = -(timeout/(zlong)10000 + 1L); + izle_timeout = (long)timeout; +#ifdef LONG_MAX + /* saturate if range exceeded */ + if ((zlong)izle_timeout != timeout) + izle_timeout = LONG_MAX; +#endif + } else { + if (readfd == -1 || + !read_poll(readfd, &readchar, keys && !zleactive, + timeout)) { + if (keys && !zleactive && !isem) + settyinfo(&shttyinfo); + else if (resettty && SHTTY != -1) + settyinfo(&saveti); + if (haso) { + fclose(shout); + shout = oshout; + SHTTY = -1; + } + return OPT_ISSET(ops,'q') ? 2 : 1; + } + } + } + +#ifdef MULTIBYTE_SUPPORT + memset(&mbs, 0, sizeof(mbs)); +#endif + + /* + * option -k means read only a given number of characters (default 1) + * option -q means get one character, and interpret it as a Y or N + */ + if (OPT_ISSET(ops,'k') || OPT_ISSET(ops,'q')) { + int eof = 0; + /* allocate buffer space for result */ +#ifdef MULTIBYTE_SUPPORT + bptr = buf = (char *)zalloc(nchars*MB_CUR_MAX+1); +#else + bptr = buf = (char *)zalloc(nchars+1); +#endif + + do { + if (izle) { + zleentry(ZLE_CMD_GET_KEY, izle_timeout, NULL, &val); + if (val < 0) { + eof = 1; + break; + } + *bptr = (char) val; +#ifdef MULTIBYTE_SUPPORT + if (isset(MULTIBYTE)) { + ret = mbrlen(bptr++, 1, &mbs); + if (ret == MB_INVALID) + memset(&mbs, 0, sizeof(mbs)); + /* treat invalid as single character */ + if (ret != MB_INCOMPLETE) + nchars--; + continue; + } else { + bptr++; + nchars--; + } +#else + bptr++; + nchars--; +#endif + } else { + /* If read returns 0, is end of file */ + if (readchar >= 0) { + *bptr = readchar; + val = 1; + readchar = -1; + } else { + while ((val = read(readfd, bptr, nchars)) < 0) { + if (errno != EINTR || + errflag || retflag || breaks || contflag) + break; + } + if (val <= 0) { + eof = 1; + break; + } + } + +#ifdef MULTIBYTE_SUPPORT + if (isset(MULTIBYTE)) { + while (val > 0) { + ret = mbrlen(bptr, val, &mbs); + if (ret == MB_INCOMPLETE) { + bptr += val; + break; + } else { + if (ret == MB_INVALID) { + memset(&mbs, 0, sizeof(mbs)); + /* treat as single byte */ + ret = 1; + } + else if (ret == 0) /* handle null as normal char */ + ret = 1; + else if (ret > (size_t)val) { + /* Some mbrlen()s return the full char len */ + ret = val; + } + nchars--; + val -= ret; + bptr += ret; + } + } + continue; + } +#endif + /* decrement number of characters read from number required */ + nchars -= val; + + /* increment pointer past read characters */ + bptr += val; + } + } while (nchars > 0); + + if (!izle && !OPT_ISSET(ops,'u') && !OPT_ISSET(ops,'p')) { + /* dispose of result appropriately, etc. */ + if (isem) + while (val > 0 && read(SHTTY, &d, 1) == 1 && d != '\n'); + else { + settyinfo(&shttyinfo); + resettty = 0; + } + if (haso) { + fclose(shout); /* close(SHTTY) */ + shout = oshout; + SHTTY = -1; + } + } + + if (OPT_ISSET(ops,'q')) + { + /* + * Keep eof as status but status is now whether we read + * 'y' or 'Y'. If we timed out, status is 2. + */ + if (eof) + eof = 2; + else + eof = (bptr - buf != 1 || (buf[0] != 'y' && buf[0] != 'Y')); + buf[0] = eof ? 'n' : 'y'; + bptr = buf + 1; + } + if (OPT_ISSET(ops,'e') || OPT_ISSET(ops,'E')) + fwrite(buf, bptr - buf, 1, stdout); + if (!OPT_ISSET(ops,'e')) + setsparam(reply, metafy(buf, bptr - buf, META_REALLOC)); + else + zfree(buf, bptr - buf + 1); + if (resettty && SHTTY != -1) + settyinfo(&saveti); + return eof; + } + + /* All possible special types of input have been exhausted. Take one line, + and assign words to the parameters until they run out. Leftover words go + onto the last parameter. If an array is specified, all the words become + separate elements of the array. */ + + zbuforig = zbuf = (!OPT_ISSET(ops,'z')) ? NULL : + (nonempty(bufstack)) ? (char *) getlinknode(bufstack) : ztrdup(""); + first = 1; + bslash = 0; + while (*args || (OPT_ISSET(ops,'A') && !gotnl)) { + sigset_t s = child_unblock(); + buf = bptr = (char *)zalloc(bsiz = 64); +#ifdef MULTIBYTE_SUPPORT + laststart = buf; + ret = MB_INCOMPLETE; +#endif + /* get input, a character at a time */ + while (!gotnl) { + c = zread(izle, &readchar, izle_timeout); + /* \ at the end of a line indicates a continuation * + * line, except in raw mode (-r option) */ +#ifdef MULTIBYTE_SUPPORT + if (c == EOF) { + /* not waiting to be completed any more */ + ret = 0; + break; + } + *bptr = (char)c; + if (isset(MULTIBYTE)) { + ret = mbrtowc(&wc, bptr, 1, &mbs); + if (!ret) /* NULL */ + ret = 1; + } else { + ret = 1; + wc = (wchar_t)c; + } + if (ret != MB_INCOMPLETE) { + if (ret == MB_INVALID) { + memset(&mbs, 0, sizeof(mbs)); + /* Treat this as a single character */ + wc = (wchar_t)c; + laststart = bptr; + } + if (bslash && wc == delim) { + bslash = 0; + continue; + } + if (wc == delim) + break; + /* + * `first' is non-zero if any separator we encounter is a + * non-whitespace separator, which means that anything + * (even an empty string) between, before or after separators + * is significant. If it is zero, we have a whitespace + * separator, which shouldn't cause extra empty strings to + * be emitted. Hence the test for (*buf || first) when + * we assign the result of reading a word. + */ + if (!bslash && wcsitype(wc, ISEP)) { + if (bptr != buf || + (!(c < 128 && iwsep(c)) && first)) { + first |= !(c < 128 && iwsep(c)); + break; + } + first |= !(c < 128 && iwsep(c)); + continue; + } + bslash = (wc == L'\\' && !bslash && !OPT_ISSET(ops,'r')); + if (bslash) + continue; + first = 0; + } + if (imeta(STOUC(*bptr))) { + bptr[1] = bptr[0] ^ 32; + bptr[0] = Meta; + bptr += 2; + } + else + bptr++; + if (ret != MB_INCOMPLETE) + laststart = bptr; +#else + if (c == EOF) + break; + if (bslash && c == delim) { + bslash = 0; + continue; + } + if (c == delim) + break; + /* + * `first' is non-zero if any separator we encounter is a + * non-whitespace separator, which means that anything + * (even an empty string) between, before or after separators + * is significant. If it is zero, we have a whitespace + * separator, which shouldn't cause extra empty strings to + * be emitted. Hence the test for (*buf || first) when + * we assign the result of reading a word. + */ + if (!bslash && isep(c)) { + if (bptr != buf || (!iwsep(c) && first)) { + first |= !iwsep(c); + break; + } + first |= !iwsep(c); + continue; + } + bslash = c == '\\' && !bslash && !OPT_ISSET(ops,'r'); + if (bslash) + continue; + first = 0; + if (imeta(c)) { + *bptr++ = Meta; + *bptr++ = c ^ 32; + } else + *bptr++ = c; +#endif + /* increase the buffer size, if necessary */ + if (bptr >= buf + bsiz - 1) { + int blen = bptr - buf; +#ifdef MULTIBYTE_SUPPORT + int llen = laststart - buf; +#endif + + buf = realloc(buf, bsiz *= 2); + bptr = buf + blen; +#ifdef MULTIBYTE_SUPPORT + laststart = buf + llen; +#endif + } + } + signal_setmask(s); +#ifdef MULTIBYTE_SUPPORT + if (c == EOF) { + gotnl = 1; + *bptr = '\0'; /* see below */ + } else if (ret == MB_INCOMPLETE) { + /* + * We can only get here if there is an EOF in the + * middle of a character... safest to keep the debris, + * I suppose. + */ + *bptr = '\0'; + } else { + if (wc == delim) + gotnl = 1; + *laststart = '\0'; + } +#else + if (c == delim || c == EOF) + gotnl = 1; + *bptr = '\0'; +#endif + /* dispose of word appropriately */ + if (OPT_ISSET(ops,'e') || + /* + * When we're doing an array assignment, we'll + * handle echoing at that point. In all other + * cases (including -A with no assignment) + * we'll do it here. + */ + (OPT_ISSET(ops,'E') && !OPT_ISSET(ops,'A'))) { + zputs(buf, stdout); + putchar('\n'); + } + if (!OPT_ISSET(ops,'e') && (*buf || first || gotnl)) { + if (OPT_ISSET(ops,'A')) { + addlinknode(readll, buf); + al++; + } else + setsparam(reply, buf); + } else + free(buf); + if (!OPT_ISSET(ops,'A')) + reply = *args++; + } + /* handle EOF */ + if (c == EOF) { + if (readfd == coprocin) { + close(coprocin); + close(coprocout); + coprocin = coprocout = -1; + } + } + /* final assignment (and display) of array parameter */ + if (OPT_ISSET(ops,'A')) { + char **pp, **p = NULL; + LinkNode n; + + p = (OPT_ISSET(ops,'e') ? (char **)NULL + : (char **)zalloc((al + 1) * sizeof(char *))); + + for (pp = p, n = firstnode(readll); n; incnode(n)) { + if (OPT_ISSET(ops,'E')) { + zputs((char *) getdata(n), stdout); + putchar('\n'); + } + if (p) + *pp++ = (char *)getdata(n); + else + zsfree(getdata(n)); + } + if (p) { + *pp++ = NULL; + setaparam(reply, p); + } + if (resettty && SHTTY != -1) + settyinfo(&saveti); + return c == EOF; + } + buf = bptr = (char *)zalloc(bsiz = 64); +#ifdef MULTIBYTE_SUPPORT + laststart = buf; + ret = MB_INCOMPLETE; +#endif + /* any remaining part of the line goes into one parameter */ + bslash = 0; + if (!gotnl) { + sigset_t s = child_unblock(); + for (;;) { + c = zread(izle, &readchar, izle_timeout); +#ifdef MULTIBYTE_SUPPORT + if (c == EOF) { + /* not waiting to be completed any more */ + ret = 0; + break; + } + *bptr = (char)c; + if (isset(MULTIBYTE)) { + ret = mbrtowc(&wc, bptr, 1, &mbs); + if (!ret) /* NULL */ + ret = 1; + } else { + ret = 1; + wc = (wchar_t)c; + } + if (ret != MB_INCOMPLETE) { + if (ret == MB_INVALID) { + memset(&mbs, 0, sizeof(mbs)); + /* Treat this as a single character */ + wc = (wchar_t)c; + laststart = bptr; + } + /* + * \ at the end of a line introduces a continuation line, + * except in raw mode (-r option) + */ + if (bslash && wc == delim) { + bslash = 0; + continue; + } + if (wc == delim && !zbuf) + break; + if (!bslash && bptr == buf && wcsitype(wc, ISEP)) { + if (c < 128 && iwsep(c)) + continue; + else if (!first) { + first = 1; + continue; + } + } + bslash = (wc == L'\\' && !bslash && !OPT_ISSET(ops,'r')); + if (bslash) + continue; + } + if (imeta(STOUC(*bptr))) { + bptr[1] = bptr[0] ^ 32; + bptr[0] = Meta; + bptr += 2; + } + else + bptr++; + if (ret != MB_INCOMPLETE) + laststart = bptr; +#else + /* \ at the end of a line introduces a continuation line, except in + raw mode (-r option) */ + if (bslash && c == delim) { + bslash = 0; + continue; + } + if (c == EOF || (c == delim && !zbuf)) + break; + if (!bslash && isep(c) && bptr == buf) { + if (iwsep(c)) + continue; + else if (!first) { + first = 1; + continue; + } + } + bslash = c == '\\' && !bslash && !OPT_ISSET(ops,'r'); + if (bslash) + continue; + if (imeta(c)) { + *bptr++ = Meta; + *bptr++ = c ^ 32; + } else + *bptr++ = c; +#endif + /* increase the buffer size, if necessary */ + if (bptr >= buf + bsiz - 1) { + int blen = bptr - buf; +#ifdef MULTIBYTE_SUPPORT + int llen = laststart - buf; +#endif + + buf = realloc(buf, bsiz *= 2); + bptr = buf + blen; +#ifdef MULTIBYTE_SUPPORT + laststart = buf + llen; +#endif + } + } + signal_setmask(s); + } +#ifdef MULTIBYTE_SUPPORT + if (ret != MB_INCOMPLETE) + bptr = laststart; +#endif + /* + * Strip trailing IFS whitespace. + * iwsep can only be certain single-byte ASCII bytes, but we + * must check the byte isn't metafied. + */ + while (bptr > buf) { + if (bptr > buf + 1 && bptr[-2] == Meta) { + /* non-ASCII, can't be IWSEP */ + break; + } else if (iwsep(bptr[-1])) + bptr--; + else + break; + } + *bptr = '\0'; + if (resettty && SHTTY != -1) + settyinfo(&saveti); + /* final assignment of reply, etc. */ + if (OPT_ISSET(ops,'e') || OPT_ISSET(ops,'E')) { + zputs(buf, stdout); + putchar('\n'); + } + if (!OPT_ISSET(ops,'e')) + setsparam(reply, buf); + else + zsfree(buf); + if (zbuforig) { + char first = *zbuforig; + + zsfree(zbuforig); + if (!first) + return 1; + } else if (c == EOF) { + if (readfd == coprocin) { + close(coprocin); + close(coprocout); + coprocin = coprocout = -1; + } + return 1; + } + /* + * The following is to ensure a failure to set the parameter + * causes a non-zero status return. There are arguments for + * turning a non-zero status into errflag more widely. + */ + return errflag; +} + +/**/ +static int +zread(int izle, int *readchar, long izle_timeout) +{ + char cc, retry = 0; + int ret; + + if (izle) { + int c; + zleentry(ZLE_CMD_GET_KEY, izle_timeout, NULL, &c); + + return (c < 0 ? EOF : c); + } + /* use zbuf if possible */ + if (zbuf) { + /* If zbuf points to anything, it points to the next character in the + buffer. This may be a null byte to indicate EOF. If reading from the + buffer, move on the buffer pointer. */ + if (*zbuf == Meta) + return zbuf++, STOUC(*zbuf++ ^ 32); + else + return (*zbuf) ? STOUC(*zbuf++) : EOF; + } + if (*readchar >= 0) { + cc = *readchar; + *readchar = -1; + return STOUC(cc); + } + for (;;) { + /* read a character from readfd */ + ret = read(readfd, &cc, 1); + switch (ret) { + case 1: + /* return the character read */ + return STOUC(cc); + case -1: +#if defined(EAGAIN) || defined(EWOULDBLOCK) + if (!retry && readfd == 0 && ( +# ifdef EAGAIN + errno == EAGAIN +# ifdef EWOULDBLOCK + || +# endif /* EWOULDBLOCK */ +# endif /* EAGAIN */ +# ifdef EWOULDBLOCK + errno == EWOULDBLOCK +# endif /* EWOULDBLOCK */ + ) && setblock_stdin()) { + retry = 1; + continue; + } else +#endif /* EAGAIN || EWOULDBLOCK */ + if (errno == EINTR && !(errflag || retflag || breaks || contflag)) + continue; + break; + } + return EOF; + } +} + +/* holds arguments for testlex() */ +/**/ +char **testargs, **curtestarg; + +/* test, [: the old-style general purpose logical expression builtin */ + +/**/ +void +testlex(void) +{ + if (tok == LEXERR) + return; + + tokstr = *(curtestarg = testargs); + if (!*testargs) { + /* if tok is already zero, reading past the end: error */ + tok = tok ? NULLTOK : LEXERR; + return; + } else if (!strcmp(*testargs, "-o")) + tok = DBAR; + else if (!strcmp(*testargs, "-a")) + tok = DAMPER; + else if (!strcmp(*testargs, "!")) + tok = BANG; + else if (!strcmp(*testargs, "(")) + tok = INPAR; + else if (!strcmp(*testargs, ")")) + tok = OUTPAR; + else + tok = STRING; + testargs++; +} + +/**/ +int +bin_test(char *name, char **argv, UNUSED(Options ops), int func) +{ + char **s; + Eprog prog; + struct estate state; + int nargs, sense = 0, ret; + + /* if "test" was invoked as "[", it needs a matching "]" * + * which is subsequently ignored */ + if (func == BIN_BRACKET) { + for (s = argv; *s; s++); + if (s == argv || strcmp(s[-1], "]")) { + zwarnnam(name, "']' expected"); + return 2; + } + s[-1] = NULL; + } + /* an empty argument list evaluates to false (1) */ + if (!*argv) + return 1; + + /* + * Implement some XSI extensions to POSIX here. + * See + * http://pubs.opengroup.org/onlinepubs/9699919799/utilities/test.html + */ + nargs = arrlen(argv); + if (nargs == 3 || nargs == 4) + { + /* + * As parentheses are an extension, we need to be careful --- + * if this is a three-argument expression that could + * be a binary operator, prefer that. + */ + if (!strcmp(argv[0], "(") && !strcmp(argv[nargs-1],")") && + (nargs != 3 || !is_cond_binary_op(argv[1]))) { + argv[nargs-1] = NULL; + argv++; + } + if (nargs == 4 && !strcmp("!", argv[0])) { + sense = 1; + argv++; + } + } + + zcontext_save(); + testargs = argv; + tok = NULLTOK; + condlex = testlex; + testlex(); + prog = parse_cond(); + condlex = zshlex; + + if (errflag) { + errflag &= ~ERRFLAG_ERROR; + zcontext_restore(); + return 2; + } + + if (!prog || tok == LEXERR) { + zwarnnam(name, tokstr ? "parse error" : "argument expected"); + zcontext_restore(); + return 2; + } + zcontext_restore(); + + if (*curtestarg) { + zwarnnam(name, "too many arguments"); + return 2; + } + + /* syntax is OK, so evaluate */ + + state.prog = prog; + state.pc = prog->prog; + state.strs = prog->strs; + + ret = evalcond(&state, name); + if (ret < 2 && sense) + ret = ! ret; + + return ret; +} + +/* display a time, provided in units of 1/60s, as minutes and seconds */ +#define pttime(X) printf("%ldm%ld.%02lds",((long) (X))/(60 * clktck),\ + ((long) (X))/clktck%clktck,\ + ((long) (X))*100/clktck%100) + +/* times: display, in a two-line format, the times provided by times(3) */ + +/**/ +int +bin_times(UNUSED(char *name), UNUSED(char **argv), UNUSED(Options ops), UNUSED(int func)) +{ + struct tms buf; + long clktck = get_clktck(); + + /* get time accounting information */ + if (times(&buf) == -1) + return 1; + pttime(buf.tms_utime); /* user time */ + putchar(' '); + pttime(buf.tms_stime); /* system time */ + putchar('\n'); + pttime(buf.tms_cutime); /* user time, children */ + putchar(' '); + pttime(buf.tms_cstime); /* system time, children */ + putchar('\n'); + return 0; +} + +/* trap: set/unset signal traps */ + +/**/ +int +bin_trap(char *name, char **argv, UNUSED(Options ops), UNUSED(int func)) +{ + Eprog prog; + char *arg, *s; + int sig; + + if (*argv && !strcmp(*argv, "--")) + argv++; + + /* If given no arguments, list all currently-set traps */ + if (!*argv) { + queue_signals(); + for (sig = 0; sig < VSIGCOUNT; sig++) { + if (sigtrapped[sig] & ZSIG_FUNC) { + HashNode hn; + + if ((hn = gettrapnode(sig, 0))) + shfunctab->printnode(hn, 0); + DPUTS(!hn, "BUG: I did not find any trap functions!"); + } else if (sigtrapped[sig]) { + const char *name = getsigname(sig); + if (!siglists[sig]) + printf("trap -- '' %s\n", name); + else { + s = getpermtext(siglists[sig], NULL, 0); + printf("trap -- "); + quotedzputs(s, stdout); + printf(" %s\n", name); + zsfree(s); + } + } + } + unqueue_signals(); + return 0; + } + + /* If we have a signal number, unset the specified * + * signals. With only -, remove all traps. */ + if ((getsignum(*argv) != -1) || (!strcmp(*argv, "-") && argv++)) { + if (!*argv) { + for (sig = 0; sig < VSIGCOUNT; sig++) + unsettrap(sig); + } else { + for (; *argv; argv++) { + sig = getsignum(*argv); + if (sig == -1) { + zwarnnam(name, "undefined signal: %s", *argv); + break; + } + unsettrap(sig); + } + } + return *argv != NULL; + } + + /* Sort out the command to execute on trap */ + arg = *argv++; + if (!*arg) + prog = &dummy_eprog; + else if (!(prog = parse_string(arg, 1))) { + zwarnnam(name, "couldn't parse trap command"); + return 1; + } + + /* set traps */ + for (; *argv; argv++) { + Eprog t; + int flags; + + sig = getsignum(*argv); + if (sig == -1) { + zwarnnam(name, "undefined signal: %s", *argv); + break; + } + if (idigit(**argv) || + !strcmp(sigs[sig], *argv) || + (!strncmp("SIG", *argv, 3) && !strcmp(sigs[sig], *argv+3))) { + /* The signal was specified by number or by canonical name (with + * or without SIG prefix). + */ + flags = 0; + } + else { + /* + * Record that the signal is used under an assumed name. + * If we ever have more than one alias per signal this + * will need improving. + */ + flags = ZSIG_ALIAS; + } + t = dupeprog(prog, 0); + if (settrap(sig, t, flags)) + freeeprog(t); + } + return *argv != NULL; +} + +/**/ +int +bin_ttyctl(UNUSED(char *name), UNUSED(char **argv), Options ops, UNUSED(int func)) +{ + if (OPT_ISSET(ops,'f')) + ttyfrozen = 1; + else if (OPT_ISSET(ops,'u')) + ttyfrozen = 0; + else + printf("tty is %sfrozen\n", ttyfrozen ? "" : "not "); + return 0; +} + +/* let -- mathematical evaluation */ + +/**/ +int +bin_let(UNUSED(char *name), char **argv, UNUSED(Options ops), UNUSED(int func)) +{ + mnumber val = zero_mnumber; + + while (*argv) + val = matheval(*argv++); + /* Errors in math evaluation in let are non-fatal. */ + errflag &= ~ERRFLAG_ERROR; + /* should test for fabs(val.u.d) < epsilon? */ + return (val.type == MN_INTEGER) ? val.u.l == 0 : val.u.d == 0.0; +} + +/* umask command. umask may be specified as octal digits, or in the * + * symbolic form that chmod(1) uses. Well, a subset of it. Remember * + * that only the bottom nine bits of umask are used, so there's no * + * point allowing the set{u,g}id and sticky bits to be specified. */ + +/**/ +int +bin_umask(char *nam, char **args, Options ops, UNUSED(int func)) +{ + mode_t um; + char *s = *args; + + /* Get the current umask. */ + um = umask(0); + umask(um); + /* No arguments means to display the current setting. */ + if (!s) { + if (OPT_ISSET(ops,'S')) { + char *who = "ugo"; + + while (*who) { + char *what = "rwx"; + printf("%c=", *who++); + while (*what) { + if (!(um & 0400)) + putchar(*what); + um <<= 1; + what++; + } + putchar(*who ? ',' : '\n'); + } + } else { + if (um & 0700) + putchar('0'); + printf("%03o\n", (unsigned)um); + } + return 0; + } + + if (idigit(*s)) { + /* Simple digital umask. */ + um = zstrtol(s, &s, 8); + if (*s) { + zwarnnam(nam, "bad umask"); + return 1; + } + } else { + /* Symbolic notation -- slightly complicated. */ + int whomask, umaskop, mask; + + /* More than one symbolic argument may be used at once, each separated + by commas. */ + for (;;) { + /* First part of the argument -- who does this apply to? + u=owner, g=group, o=other. */ + whomask = 0; + while (*s == 'u' || *s == 'g' || *s == 'o' || *s == 'a') + if (*s == 'u') + s++, whomask |= 0700; + else if (*s == 'g') + s++, whomask |= 0070; + else if (*s == 'o') + s++, whomask |= 0007; + else if (*s == 'a') + s++, whomask |= 0777; + /* Default whomask is everyone. */ + if (!whomask) + whomask = 0777; + /* Operation may be +, - or =. */ + umaskop = (int)*s; + if (!(umaskop == '+' || umaskop == '-' || umaskop == '=')) { + if (umaskop) + zwarnnam(nam, "bad symbolic mode operator: %c", umaskop); + else + zwarnnam(nam, "bad umask"); + return 1; + } + /* Permissions mask -- r=read, w=write, x=execute. */ + mask = 0; + while (*++s && *s != ',') + if (*s == 'r') + mask |= 0444 & whomask; + else if (*s == 'w') + mask |= 0222 & whomask; + else if (*s == 'x') + mask |= 0111 & whomask; + else { + zwarnnam(nam, "bad symbolic mode permission: %c", *s); + return 1; + } + /* Apply parsed argument to um. */ + if (umaskop == '+') + um &= ~mask; + else if (umaskop == '-') + um |= mask; + else /* umaskop == '=' */ + um = (um | (whomask)) & ~mask; + if (*s == ',') + s++; + else + break; + } + if (*s) { + zwarnnam(nam, "bad character in symbolic mode: %c", *s); + return 1; + } + } + + /* Finally, set the new umask. */ + umask(um); + return 0; +} + +/* Generic builtin for facilities not available on this OS */ + +/**/ +mod_export int +bin_notavail(char *nam, UNUSED(char **argv), UNUSED(Options ops), UNUSED(int func)) +{ + zwarnnam(nam, "not available on this system"); + return 1; +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/compat.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/compat.c new file mode 100644 index 00000000..7b5c4411 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/compat.c @@ -0,0 +1,742 @@ +/* + * compat.c - compatibility routines for the deprived + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "compat.pro" + +/* Return pointer to first occurence of string t * + * in string s. Return NULL if not present. */ + +/**/ +#ifndef HAVE_STRSTR + +/**/ +char * +strstr(const char *s, const char *t) +{ + const char *p1, *p2; + + for (; *s; s++) { + for (p1 = s, p2 = t; *p2; p1++, p2++) + if (*p1 != *p2) + break; + if (!*p2) + return (char *)s; + } + return NULL; +} + +/**/ +#endif + + +/**/ +#ifndef HAVE_GETHOSTNAME + +/**/ +int +gethostname(char *name, size_t namelen) +{ + struct utsname uts; + + uname(&uts); + if(strlen(uts.nodename) >= namelen) { + errno = EINVAL; + return -1; + } + strcpy(name, uts.nodename); + return 0; +} + +/**/ +#endif + + +/**/ +#ifndef HAVE_GETTIMEOFDAY + +/**/ +int +gettimeofday(struct timeval *tv, struct timezone *tz) +{ + tv->tv_usec = 0; + tv->tv_sec = (long)time((time_t) 0); + return 0; +} + +/**/ +#endif + + +/* Provide clock time with nanoseconds */ + +/**/ +mod_export int +zgettime(struct timespec *ts) +{ + int ret = -1; + +#ifdef HAVE_CLOCK_GETTIME + struct timespec dts; + if (clock_gettime(CLOCK_REALTIME, &dts) < 0) { + zwarn("unable to retrieve time: %e", errno); + ret--; + } else { + ret++; + ts->tv_sec = (time_t) dts.tv_sec; + ts->tv_nsec = (long) dts.tv_nsec; + } +#endif + + if (ret) { + struct timeval dtv; + struct timezone dtz; + gettimeofday(&dtv, &dtz); + ret++; + ts->tv_sec = (time_t) dtv.tv_sec; + ts->tv_nsec = (long) dtv.tv_usec * 1000; + } + + return ret; +} + + +/* compute the difference between two calendar times */ + +/**/ +#ifndef HAVE_DIFFTIME + +/**/ +double +difftime(time_t t2, time_t t1) +{ + return ((double)t2 - (double)t1); +} + +/**/ +#endif + + +/**/ +#ifndef HAVE_STRERROR +extern char *sys_errlist[]; + +/* Get error message string associated with a particular * + * error number, and returns a pointer to that string. * + * This is not a particularly robust version of strerror. */ + +/**/ +char * +strerror(int errnum) +{ + return (sys_errlist[errnum]); +} + +/**/ +#endif + + +#if 0 +/* pathconf(_PC_PATH_MAX) is not currently useful to zsh. The value * + * returned varies depending on a number of factors, e.g. the amount * + * of memory available to the operating system at a given time; thus * + * it can't be used for buffer allocation, or even as an indication * + * of whether an attempt to use or create a given pathname may fail * + * at any future time. * + * * + * The call is also permitted to fail if the argument path is not an * + * existing directory, so even to make sense of that one must search * + * for a valid directory somewhere in the path and adjust. Even if * + * it succeeds, the return value is relative to the input directory, * + * and therefore potentially relative to the length of the shortest * + * path either to that directory or to our working directory. * + * * + * Finally, see the note below for glibc; detection of pathconf() is * + * not by itself an indication that it works reliably. */ + +/* The documentation for pathconf() says something like: * + * The limit is returned, if one exists. If the system does * + * not have a limit for the requested resource, -1 is * + * returned, and errno is unchanged. If there is an error, * + * -1 is returned, and errno is set to reflect the nature of * + * the error. * + * * + * System calls are not permitted to set errno to 0; but we must (or * + * some other flag value) in order to determine that the resource is * + * unlimited. What use is leaving errno unchanged? Instead, define * + * a wrapper that resets errno to 0 and returns 0 for "the system * + * does not have a limit," so that -1 always means a real error. */ + +/**/ +mod_export long +zpathmax(char *dir) +{ +#ifdef HAVE_PATHCONF + long pathmax; + + errno = 0; + if ((pathmax = pathconf(dir, _PC_PATH_MAX)) >= 0) { + /* Some versions of glibc pathconf return a hardwired value! */ + return pathmax; + } else if (errno == EINVAL || errno == ENOENT || errno == ENOTDIR) { + /* Work backward to find a directory, until we run out of path. */ + char *tail = strrchr(dir, '/'); + while (tail > dir && tail[-1] == '/') + --tail; + if (tail > dir) { + *tail = 0; + pathmax = zpathmax(dir); + *tail = '/'; + } else { + errno = 0; + if (tail) + pathmax = pathconf("/", _PC_PATH_MAX); + else + pathmax = pathconf(".", _PC_PATH_MAX); + } + if (pathmax > 0) { + long taillen = (tail ? strlen(tail) : (strlen(dir) + 1)); + if (taillen < pathmax) + return pathmax - taillen; + else + errno = ENAMETOOLONG; + } + } + if (errno) + return -1; + else + return 0; /* pathmax should be considered unlimited */ +#else + long dirlen = strlen(dir); + + /* The following is wrong if dir is not an absolute path. */ + return ((long) ((dirlen >= PATH_MAX) ? + ((errno = ENAMETOOLONG), -1) : + ((errno = 0), PATH_MAX - dirlen))); +#endif +} +#endif /* 0 */ + +/**/ +#ifdef HAVE_SYSCONF +/* + * This is replaced by a macro from system.h if not HAVE_SYSCONF. + * 0 is returned by sysconf if _SC_OPEN_MAX is unavailable; + * -1 is returned on error + * + * Neither of these should happen, but resort to OPEN_MAX rather + * than return 0 or -1 just in case. + * + * We'll limit the open maximum to ZSH_INITIAL_OPEN_MAX to + * avoid probing ridiculous numbers of file descriptors. + */ + +/**/ +mod_export long +zopenmax(void) +{ + long openmax; + + if ((openmax = sysconf(_SC_OPEN_MAX)) < 1) { + openmax = OPEN_MAX; + } else if (openmax > OPEN_MAX) { + /* On some systems, "limit descriptors unlimited" or the * + * equivalent will set openmax to a huge number. Unless * + * there actually is a file descriptor > OPEN_MAX already * + * open, nothing in zsh requires the true maximum, and in * + * fact it causes inefficiency elsewhere if we report it. * + * So, report the maximum of OPEN_MAX or the largest open * + * descriptor (is there a better way to find that?). */ + long i, j = OPEN_MAX; + if (openmax > ZSH_INITIAL_OPEN_MAX) + openmax = ZSH_INITIAL_OPEN_MAX; + for (i = j; i < openmax; i += (errno != EINTR)) { + errno = 0; + if (fcntl(i, F_GETFL, 0) < 0 && + (errno == EBADF || errno == EINTR)) + continue; + j = i; + } + openmax = j; + } + + return (max_zsh_fd > openmax) ? max_zsh_fd : openmax; +} + +/**/ +#endif + +/* + * Rationalise the current directory, returning the string. + * + * If "d" is not NULL, it is used to store information about the + * directory. The returned name is also present in d->dirname and is in + * permanently allocated memory. The handling of this case depends on + * whether the fchdir() system call is available; if it is, it is assumed + * the caller is able to restore the current directory. On successfully + * identifying the directory the function returns immediately rather + * than ascending the hierarchy. + * + * If "d" is NULL, no assumption about the caller's behaviour is + * made. The returned string is in heap memory. This case is + * always handled by changing directory up the hierarchy. + * + * On Cygwin or other systems where USE_GETCWD is defined (at the + * time of writing only QNX), we skip all the above and use the + * getcwd() system call. + */ + +/**/ +mod_export char * +zgetdir(struct dirsav *d) +{ + char nbuf[PATH_MAX+3]; + char *buf; + int bufsiz, pos; + struct stat sbuf; + ino_t pino; + dev_t pdev; +#if !defined(__CYGWIN__) && !defined(USE_GETCWD) + struct dirent *de; + DIR *dir; + dev_t dev; + ino_t ino; + int len; +#endif + + buf = zhalloc(bufsiz = PATH_MAX+1); + pos = bufsiz - 1; + buf[pos] = '\0'; + strcpy(nbuf, "../"); + if (stat(".", &sbuf) < 0) { + return NULL; + } + + /* Record the initial inode and device */ + pino = sbuf.st_ino; + pdev = sbuf.st_dev; + if (d) + d->ino = pino, d->dev = pdev; +#if !defined(__CYGWIN__) && !defined(USE_GETCWD) +#ifdef HAVE_FCHDIR + else +#endif + holdintr(); + + for (;;) { + /* Examine the parent of the current directory. */ + if (stat("..", &sbuf) < 0) + break; + + /* Inode and device of curtent directory */ + ino = pino; + dev = pdev; + /* Inode and device of current directory's parent */ + pino = sbuf.st_ino; + pdev = sbuf.st_dev; + + /* If they're the same, we've reached the root directory. */ + if (ino == pino && dev == pdev) { + if (!buf[pos]) + buf[--pos] = '/'; + if (d) { +#ifndef HAVE_FCHDIR + zchdir(buf + pos); + noholdintr(); +#endif + return d->dirname = ztrdup(buf + pos); + } + zchdir(buf + pos); + noholdintr(); + return buf + pos; + } + + /* Search the parent for the current directory. */ + if (!(dir = opendir(".."))) + break; + + while ((de = readdir(dir))) { + char *fn = de->d_name; + /* Ignore `.' and `..'. */ + if (fn[0] == '.' && + (fn[1] == '\0' || + (fn[1] == '.' && fn[2] == '\0'))) + continue; +#ifdef HAVE_STRUCT_DIRENT_D_STAT + if(de->d_stat.st_dev == dev && de->d_stat.st_ino == ino) { + /* Found the directory we're currently in */ + strncpy(nbuf + 3, fn, PATH_MAX); + break; + } +#else /* !HAVE_STRUCT_DIRENT_D_STAT */ +# ifdef HAVE_STRUCT_DIRENT_D_INO + if (dev != pdev || (ino_t) de->d_ino == ino) +# endif /* HAVE_STRUCT_DIRENT_D_INO */ + { + /* Maybe found directory, need to check device & inode */ + strncpy(nbuf + 3, fn, PATH_MAX); + lstat(nbuf, &sbuf); + if (sbuf.st_dev == dev && sbuf.st_ino == ino) + break; + } +#endif /* !HAVE_STRUCT_DIRENT_D_STAT */ + } + closedir(dir); + if (!de) + break; /* Not found */ + /* + * We get the "/" free just by copying from nbuf+2 instead + * of nbuf+3, which is where we copied the path component. + * This means buf[pos] is always a "/". + */ + len = strlen(nbuf + 2); + pos -= len; + while (pos <= 1) { + char *newbuf = zhalloc(2*bufsiz); + memcpy(newbuf + bufsiz, buf, bufsiz); + buf = newbuf; + pos += bufsiz; + bufsiz *= 2; + } + memcpy(buf + pos, nbuf + 2, len); +#ifdef HAVE_FCHDIR + if (d) + return d->dirname = ztrdup(buf + pos + 1); +#endif + if (chdir("..")) + break; + } + + /* + * Fix up the directory, if necessary. + * We're changing back down the hierarchy, ignore the + * "/" at buf[pos]. + */ + if (d) { +#ifndef HAVE_FCHDIR + if (buf[pos]) + zchdir(buf + pos + 1); + noholdintr(); +#endif + return NULL; + } + + if (buf[pos]) + zchdir(buf + pos + 1); + noholdintr(); + +#else /* __CYGWIN__, USE_GETCWD cases */ + + if (!getcwd(buf, bufsiz)) { + if (d) { + return NULL; + } + } else { + if (d) { + return d->dirname = ztrdup(buf); + } + return buf; + } +#endif + + /* + * Something bad happened. + * This has been seen when inside a special directory, + * such as the Netapp .snapshot directory, that doesn't + * appear as a directory entry in the parent directory. + * We'll just need our best guess. + * + * We only get here from zgetcwd(); let that fall back to pwd. + */ + + return NULL; +} + +/* + * Try to find the current directory. + * If we couldn't work it out internally, fall back to getcwd(). + * If it fails, fall back to pwd; if zgetcwd() is being used + * to set pwd, pwd should be NULL and we just return ".". + */ + +/**/ +char * +zgetcwd(void) +{ + char *ret = zgetdir(NULL); +#ifdef HAVE_GETCWD + if (!ret) { +#ifdef GETCWD_CALLS_MALLOC + char *cwd = getcwd(NULL, 0); + if (cwd) { + ret = dupstring(cwd); + free(cwd); + } +#else + char *cwdbuf = zalloc(PATH_MAX+1); + ret = getcwd(cwdbuf, PATH_MAX); + if (ret) + ret = dupstring(ret); + zfree(cwdbuf, PATH_MAX+1); +#endif /* GETCWD_CALLS_MALLOC */ + } +#endif /* HAVE_GETCWD */ + if (!ret) + ret = unmeta(pwd); + if (!ret) + ret = dupstring("."); + return ret; +} + +/* + * chdir with arbitrary long pathname. Returns 0 on success, -1 on normal * + * failure and -2 when chdir failed and the current directory is lost. + * + * This is to be treated as if at system level, so dir is unmetafied but + * terminated by a NULL. + */ + +/**/ +mod_export int +zchdir(char *dir) +{ + char *s; + int currdir = -2; + + for (;;) { + if (!*dir || chdir(dir) == 0) { +#ifdef HAVE_FCHDIR + if (currdir >= 0) + close(currdir); +#endif + return 0; + } + if ((errno != ENAMETOOLONG && errno != ENOMEM) || + strlen(dir) < PATH_MAX) + break; + for (s = dir + PATH_MAX - 1; s > dir && *s != '/'; s--) + ; + if (s == dir) + break; +#ifdef HAVE_FCHDIR + if (currdir == -2) + currdir = open(".", O_RDONLY|O_NOCTTY); +#endif + *s = '\0'; + if (chdir(dir) < 0) { + *s = '/'; + break; + } +#ifndef HAVE_FCHDIR + currdir = -1; +#endif + *s = '/'; + while (*++s == '/') + ; + dir = s; + } +#ifdef HAVE_FCHDIR + if (currdir >= 0) { + if (fchdir(currdir) < 0) { + close(currdir); + return -2; + } + close(currdir); + return -1; + } +#endif + return currdir == -2 ? -1 : -2; +} + +/* + * How to print out a 64 bit integer. This isn't needed (1) if longs + * are 64 bit, since ordinary %ld will work (2) if we couldn't find a + * 64 bit type anyway. + */ +/**/ +#ifdef ZSH_64_BIT_TYPE +/**/ +mod_export char * +output64(zlong val) +{ + static char llbuf[DIGBUFSIZE]; + convbase(llbuf, val, 0); + return llbuf; +} +/**/ +#endif /* ZSH_64_BIT_TYPE */ + +/**/ +#ifndef HAVE_STRTOUL + +/* + * Copyright (c) 1990, 1993 + * The Regents of the University of California. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the University nor the names of its contributors + * may be used to endorse or promote products derived from this software + * without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. + */ + +/* + * Convert a string to an unsigned long integer. + * + * Ignores `locale' stuff. Assumes that the upper and lower case + * alphabets and digits are each contiguous. + */ + +/**/ +unsigned long +strtoul(nptr, endptr, base) + const char *nptr; + char **endptr; + int base; +{ + const char *s; + unsigned long acc, cutoff; + int c; + int neg, any, cutlim; + + /* endptr may be NULL */ + + s = nptr; + do { + c = (unsigned char) *s++; + } while (isspace(c)); + if (c == '-') { + neg = 1; + c = *s++; + } else { + neg = 0; + if (c == '+') + c = *s++; + } + if ((base == 0 || base == 16) && + c == '0' && (*s == 'x' || *s == 'X')) { + c = s[1]; + s += 2; + base = 16; + } + if (base == 0) + base = c == '0' ? 8 : 10; + + cutoff = ULONG_MAX / (unsigned long)base; + cutlim = (int)(ULONG_MAX % (unsigned long)base); + for (acc = 0, any = 0;; c = (unsigned char) *s++) { + if (isdigit(c)) + c -= '0'; + else if (isalpha(c)) { + c -= isupper(c) ? 'A' - 10 : 'a' - 10; + } else + break; + if (c >= base) + break; + if (any < 0) + continue; + if (acc > cutoff || (acc == cutoff && c > cutlim)) { + any = -1; + acc = ULONG_MAX; + errno = ERANGE; + } else { + any = 1; + acc *= (unsigned long)base; + acc += c; + } + } + if (neg && any > 0) + acc = -acc; + if (endptr != NULL) + *endptr = any ? s - 1 : nptr; + return (acc); +} + +/**/ +#endif /* HAVE_STRTOUL */ + +/**/ +#ifdef ENABLE_UNICODE9 +#include "./wcwidth9.h" + +/**/ +int +u9_wcwidth(wchar_t ucs) +{ + int w = wcwidth9(ucs); + if (w < -1) + return 1; + return w; +} + +/**/ +int +u9_iswprint(wint_t ucs) +{ + if (ucs == 0) + return 0; + return wcwidth9(ucs) != -1; +} + +/**/ +#endif /* ENABLE_UNICODE9 */ + +/**/ +#if defined(__APPLE__) && defined(BROKEN_ISPRINT) + +/**/ +int +isprint_ascii(int c) +{ + if (!strcmp(nl_langinfo(CODESET), "UTF-8")) + return (c >= 0x20 && c <= 0x7e); + else + return isprint(c); +} + +/**/ +#endif /* __APPLE__ && BROKEN_ISPRINT */ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/exec.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/exec.c new file mode 100644 index 00000000..615a5086 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/exec.c @@ -0,0 +1,6250 @@ +/* + * exec.c - command execution + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "exec.pro" + +/* Flags for last argument of addvars */ + +enum { + /* Export the variable for "VAR=val cmd ..." */ + ADDVAR_EXPORT = 1 << 0, + /* Apply restrictions for variable */ + ADDVAR_RESTRICT = 1 << 1, + /* Variable list is being restored later */ + ADDVAR_RESTORE = 1 << 2 +}; + +/* Structure in which to save values around shell function call */ + +struct funcsave { + char opts[OPT_SIZE]; + char *argv0; + int zoptind, lastval, optcind, numpipestats; + int *pipestats; + char *scriptname; + int breaks, contflag, loops, emulation, noerrexit, oflags, restore_sticky; + Emulation_options sticky; + struct funcstack fstack; +}; +typedef struct funcsave *Funcsave; + +/* + * used to suppress ERREXIT and trapping of SIGZERR, SIGEXIT. + * Bits from noerrexit_bits. + */ + +/**/ +int noerrexit; + +/* used to suppress ERREXIT or ERRRETURN for one occurrence: 0 or 1 */ + +/**/ +int this_noerrexit; + +/* + * noerrs = 1: suppress error messages + * noerrs = 2: don't set errflag on parse error, either + */ + +/**/ +mod_export int noerrs; + +/* do not save history on exec and exit */ + +/**/ +int nohistsave; + +/* error flag: bits from enum errflag_bits */ + +/**/ +mod_export int errflag; + +/* + * State of trap return value. Value is from enum trap_state. + */ + +/**/ +int trap_state; + +/* + * Value associated with return from a trap. + * This is only active if we are inside a trap, else its value + * is irrelevant. It is initialised to -1 for a function trap and + * -2 for a non-function trap and if negative is decremented as + * we go deeper into functions and incremented as we come back up. + * The value is used to decide if an explicit "return" should cause + * a return from the caller of the trap; it does this by setting + * trap_return to a status (i.e. a non-negative value). + * + * In summary, trap_return is + * - zero unless we are in a trap + * - negative in a trap unless it has triggered. Code uses this + * to detect an active trap. + * - non-negative in a trap once it was triggered. It should remain + * non-negative until restored after execution of the trap. + */ + +/**/ +int trap_return; + +/* != 0 if this is a subshell */ + +/**/ +int subsh; + +/* != 0 if we have a return pending */ + +/**/ +mod_export int retflag; + +/**/ +long lastval2; + +/* The table of file descriptors. A table element is zero if the * + * corresponding fd is not used by the shell. It is greater than * + * 1 if the fd is used by a <(...) or >(...) substitution and 1 if * + * it is an internal file descriptor which must be closed before * + * executing an external command. The first ten elements of the * + * table is not used. A table element is set by movefd and cleard * + * by zclose. */ + +/**/ +mod_export unsigned char *fdtable; + +/* The allocated size of fdtable */ + +/**/ +int fdtable_size; + +/* The highest fd that marked with nonzero in fdtable */ + +/**/ +mod_export int max_zsh_fd; + +/* input fd from the coprocess */ + +/**/ +mod_export int coprocin; + +/* output fd from the coprocess */ + +/**/ +mod_export int coprocout; + +/* count of file locks recorded in fdtable */ + +/**/ +int fdtable_flocks; + + +/* != 0 if the line editor is active */ + +/**/ +mod_export int zleactive; + +/* pid of process undergoing 'process substitution' */ + +/**/ +pid_t cmdoutpid; + +/* pid of last process started by <(...), >(...) */ + +/**/ +mod_export pid_t procsubstpid; + +/* exit status of process undergoing 'process substitution' */ + +/**/ +int cmdoutval; + +/* + * This is set by an exiting $(...) substitution to indicate we need + * to retain the status. We initialize it to zero if we think we need + * to reset the status for a command. + */ + +/**/ +int use_cmdoutval; + +/* The context in which a shell function is called, see SFC_* in zsh.h. */ + +/**/ +mod_export int sfcontext; + +/* Stack to save some variables before executing a signal handler function */ + +/**/ +struct execstack *exstack; + +/* Stack with names of function calls, 'source' calls, and 'eval' calls + * currently active. */ + +/**/ +mod_export Funcstack funcstack; + +#define execerr() \ + do { \ + if (!forked) { \ + redir_err = lastval = 1; \ + goto done; \ + } else { \ + _exit(1); \ + } \ + } while (0) + +static int doneps4; +static char *STTYval; +static char *blank_env[] = { NULL }; + +/* Execution functions. */ + +static int (*execfuncs[WC_COUNT-WC_CURSH]) _((Estate, int)) = { + execcursh, exectime, NULL /* execfuncdef handled specially */, + execfor, execselect, + execwhile, execrepeat, execcase, execif, execcond, + execarith, execautofn, exectry +}; + +/* structure for command builtin for when it is used with -v or -V */ +static struct builtin commandbn = + BUILTIN("command", 0, bin_whence, 0, -1, BIN_COMMAND, "pvV", NULL); + +/* parse string into a list */ + +/**/ +mod_export Eprog +parse_string(char *s, int reset_lineno) +{ + Eprog p; + zlong oldlineno; + + zcontext_save(); + inpush(s, INP_LINENO, NULL); + strinbeg(0); + oldlineno = lineno; + if (reset_lineno) + lineno = 1; + p = parse_list(); + lineno = oldlineno; + if (tok == LEXERR && !lastval) + lastval = 1; + strinend(); + inpop(); + zcontext_restore(); + return p; +} + +/**/ +#ifdef HAVE_GETRLIMIT + +/* the resource limits for the shell and its children */ + +/**/ +mod_export struct rlimit current_limits[RLIM_NLIMITS], limits[RLIM_NLIMITS]; + +/**/ +mod_export int +zsetlimit(int limnum, char *nam) +{ + if (limits[limnum].rlim_max != current_limits[limnum].rlim_max || + limits[limnum].rlim_cur != current_limits[limnum].rlim_cur) { + if (setrlimit(limnum, limits + limnum)) { + if (nam) + zwarnnam(nam, "setrlimit failed: %e", errno); + limits[limnum] = current_limits[limnum]; + return -1; + } + current_limits[limnum] = limits[limnum]; + } + return 0; +} + +/**/ +mod_export int +setlimits(char *nam) +{ + int limnum; + int ret = 0; + + for (limnum = 0; limnum < RLIM_NLIMITS; limnum++) + if (zsetlimit(limnum, nam)) + ret++; + return ret; +} + +/**/ +#endif /* HAVE_GETRLIMIT */ + +/* fork and set limits */ + +/**/ +static pid_t +zfork(struct timeval *tv) +{ + pid_t pid; + struct timezone dummy_tz; + + /* + * Is anybody willing to explain this test? + */ + if (thisjob != -1 && thisjob >= jobtabsize - 1 && !expandjobtab()) { + zerr("job table full"); + return -1; + } + if (tv) + gettimeofday(tv, &dummy_tz); + /* + * Queueing signals is necessary on Linux because fork() + * manipulates mutexes, leading to deadlock in memory + * allocation. We don't expect fork() to be particularly + * zippy anyway. + */ + queue_signals(); + pid = fork(); + unqueue_signals(); + if (pid == -1) { + zerr("fork failed: %e", errno); + return -1; + } +#ifdef HAVE_GETRLIMIT + if (!pid) + /* set resource limits for the child process */ + setlimits(NULL); +#endif + return pid; +} + +/* + * Allen Edeln gebiet ich Andacht, + * Hohen und Niedern von Heimdalls Geschlecht; + * Ich will list_pipe's Wirken kuenden + * Die aeltesten Sagen, der ich mich entsinne... + * + * In most shells, if you do something like: + * + * cat foo | while read a; do grep $a bar; done + * + * the shell forks and executes the loop in the sub-shell thus created. + * In zsh this traditionally executes the loop in the current shell, which + * is nice to have if the loop does something to change the shell, like + * setting parameters or calling builtins. + * Putting the loop in a sub-shell makes life easy, because the shell only + * has to put it into the job-structure and then treats it as a normal + * process. Suspending and interrupting is no problem then. + * Some years ago, zsh either couldn't suspend such things at all, or + * it got really messed up when users tried to do it. As a solution, we + * implemented the list_pipe-stuff, which has since then become a reason + * for many nightmares. + * Pipelines like the one above are executed by the functions in this file + * which call each other (and sometimes recursively). The one above, for + * example would lead to a function call stack roughly like: + * + * execlist->execpline->execcmd->execwhile->execlist->execpline + * + * (when waiting for the grep, ignoring execpline2 for now). At this time, + * zsh has built two job-table entries for it: one for the cat and one for + * the grep. If the user hits ^Z at this point (and jobbing is used), the + * shell is notified that the grep was suspended. The list_pipe flag is + * used to tell the execpline where it was waiting that it was in a pipeline + * with a shell construct at the end (which may also be a shell function or + * several other things). When zsh sees the suspended grep, it forks to let + * the sub-shell execute the rest of the while loop. The parent shell walks + * up in the function call stack to the first execpline. There it has to find + * out that it has just forked and then has to add information about the sub- + * shell (its pid and the text for it) in the job entry of the cat. The pid + * is passed down in the list_pipe_pid variable. + * But there is a problem: the suspended grep is a child of the parent shell + * and can't be adopted by the sub-shell. So the parent shell also has to + * keep the information about this process (more precisely: this pipeline) + * by keeping the job table entry it created for it. The fact that there + * are two jobs which have to be treated together is remembered by setting + * the STAT_SUPERJOB flag in the entry for the cat-job (which now also + * contains a process-entry for the whole loop -- the sub-shell) and by + * setting STAT_SUBJOB in the job of the grep-job. With that we can keep + * sub-jobs from being displayed and we can handle an fg/bg on the super- + * job correctly. When the super-job is continued, the shell also wakes up + * the sub-job. But then, the grep will exit sometime. Now the parent shell + * has to remember not to try to wake it up again (in case of another ^Z). + * It also has to wake up the sub-shell (which suspended itself immediately + * after creation), so that the rest of the loop is executed by it. + * But there is more: when the sub-shell is created, the cat may already + * have exited, so we can't put the sub-shell in the process group of it. + * In this case, we put the sub-shell in the process group of the parent + * shell and in any case, the sub-shell has to put all commands executed + * by it into its own process group, because only this way the parent + * shell can control them since it only knows the process group of the sub- + * shell. Of course, this information is also important when putting a job + * in the foreground, where we have to attach its process group to the + * controlling tty. + * All this is made more difficult because we have to handle return values + * correctly. If the grep is signaled, its exit status has to be propagated + * back to the parent shell which needs it to set the exit status of the + * super-job. And of course, when the grep is signaled (including ^C), the + * loop has to be stopped, etc. + * The code for all this is distributed over three files (exec.c, jobs.c, + * and signals.c) and none of them is a simple one. So, all in all, there + * may still be bugs, but considering the complexity (with race conditions, + * signal handling, and all that), this should probably be expected. + */ + +/**/ +int list_pipe = 0, simple_pline = 0; + +static pid_t list_pipe_pid; +static struct timeval list_pipe_start; +static int nowait, pline_level = 0; +static int list_pipe_child = 0, list_pipe_job; +static char list_pipe_text[JOBTEXTSIZE]; + +/* execute a current shell command */ + +/**/ +static int +execcursh(Estate state, int do_exec) +{ + Wordcode end = state->pc + WC_CURSH_SKIP(state->pc[-1]); + + /* Skip word only used for try/always */ + state->pc++; + + /* + * The test thisjob != -1 was added because sometimes thisjob + * can be invalid at this point. The case in question was + * in a precmd function after operations involving background + * jobs. + * + * This is because sometimes we bypass job control to execute + * very simple functions via execssimple(). + */ + if (!list_pipe && thisjob != -1 && thisjob != list_pipe_job && + !hasprocs(thisjob)) + deletejob(jobtab + thisjob, 0); + cmdpush(CS_CURSH); + execlist(state, 1, do_exec); + cmdpop(); + + state->pc = end; + this_noerrexit = 1; + + return lastval; +} + +/* execve after handling $_ and #! */ + +#define POUNDBANGLIMIT 64 + +/**/ +static int +zexecve(char *pth, char **argv, char **newenvp) +{ + int eno; + static char buf[PATH_MAX * 2+1]; + char **eep; + + unmetafy(pth, NULL); + for (eep = argv; *eep; eep++) + if (*eep != pth) + unmetafy(*eep, NULL); + buf[0] = '_'; + buf[1] = '='; + if (*pth == '/') + strcpy(buf + 2, pth); + else + sprintf(buf + 2, "%s/%s", pwd, pth); + zputenv(buf); +#ifndef FD_CLOEXEC + closedumps(); +#endif + + if (newenvp == NULL) + newenvp = environ; + winch_unblock(); + execve(pth, argv, newenvp); + + /* If the execve returns (which in general shouldn't happen), * + * then check for an errno equal to ENOEXEC. This errno is set * + * if the process file has the appropriate access permission, * + * but has an invalid magic number in its header. */ + if ((eno = errno) == ENOEXEC || eno == ENOENT) { + char execvebuf[POUNDBANGLIMIT + 1], *ptr, *ptr2, *argv0; + int fd, ct, t0; + + if ((fd = open(pth, O_RDONLY|O_NOCTTY)) >= 0) { + argv0 = *argv; + *argv = pth; + execvebuf[0] = '\0'; + ct = read(fd, execvebuf, POUNDBANGLIMIT); + close(fd); + if (ct >= 0) { + if (execvebuf[0] == '#') { + if (execvebuf[1] == '!') { + for (t0 = 0; t0 != ct; t0++) + if (execvebuf[t0] == '\n') + break; + while (inblank(execvebuf[t0])) + execvebuf[t0--] = '\0'; + execvebuf[POUNDBANGLIMIT] = '\0'; + for (ptr = execvebuf + 2; *ptr && *ptr == ' '; ptr++); + for (ptr2 = ptr; *ptr && *ptr != ' '; ptr++); + if (eno == ENOENT) { + char *pprog; + if (*ptr) + *ptr = '\0'; + if (*ptr2 != '/' && + (pprog = pathprog(ptr2, NULL))) { + argv[-2] = ptr2; + argv[-1] = ptr + 1; + winch_unblock(); + execve(pprog, argv - 2, newenvp); + } + zerr("%s: bad interpreter: %s: %e", pth, ptr2, + eno); + } else if (*ptr) { + *ptr = '\0'; + argv[-2] = ptr2; + argv[-1] = ptr + 1; + winch_unblock(); + execve(ptr2, argv - 2, newenvp); + } else { + argv[-1] = ptr2; + winch_unblock(); + execve(ptr2, argv - 1, newenvp); + } + } else if (eno == ENOEXEC) { + argv[-1] = "sh"; + winch_unblock(); + execve("/bin/sh", argv - 1, newenvp); + } + } else if (eno == ENOEXEC) { + for (t0 = 0; t0 != ct; t0++) + if (!execvebuf[t0]) + break; + if (t0 == ct) { + argv[-1] = "sh"; + winch_unblock(); + execve("/bin/sh", argv - 1, newenvp); + } + } + } else + eno = errno; + *argv = argv0; + } else + eno = errno; + } + /* restore the original arguments and path but do not bother with * + * null characters as these cannot be passed to external commands * + * anyway. So the result is truncated at the first null char. */ + pth = metafy(pth, -1, META_NOALLOC); + for (eep = argv; *eep; eep++) + if (*eep != pth) + (void) metafy(*eep, -1, META_NOALLOC); + return eno; +} + +#define MAXCMDLEN (PATH_MAX*4) + +/* test whether we really want to believe the error number */ + +/**/ +static int +isgooderr(int e, char *dir) +{ + /* + * Maybe the directory was unreadable, or maybe it wasn't + * even a directory. + */ + return ((e != EACCES || !access(dir, X_OK)) && + e != ENOENT && e != ENOTDIR); +} + +/* + * Attempt to handle command not found. + * Return 0 if the condition was handled, non-zero otherwise. + */ + +/**/ +static int +commandnotfound(char *arg0, LinkList args) +{ + Shfunc shf = (Shfunc) + shfunctab->getnode(shfunctab, "command_not_found_handler"); + + if (!shf) { + lastval = 127; + return 1; + } + + pushnode(args, arg0); + lastval = doshfunc(shf, args, 1); + return 0; +} + +/* + * Search the default path for cmd. + * pbuf of length plen is the buffer to use. + * Return NULL if not found. + */ + +static char * +search_defpath(char *cmd, char *pbuf, int plen) +{ + char *ps = DEFAULT_PATH, *pe = NULL, *s; + + for (ps = DEFAULT_PATH; ps; ps = pe ? pe+1 : NULL) { + pe = strchr(ps, ':'); + if (*ps == '/') { + s = pbuf; + if (pe) { + if (pe - ps >= plen) + continue; + struncpy(&s, ps, pe-ps); + } else { + if (strlen(ps) >= plen) + continue; + strucpy(&s, ps); + } + *s++ = '/'; + if ((s - pbuf) + strlen(cmd) >= plen) + continue; + strucpy(&s, cmd); + if (iscom(pbuf)) + return pbuf; + } + } + return NULL; +} + +/* execute an external command */ + +/**/ +static void +execute(LinkList args, int flags, int defpath) +{ + Cmdnam cn; + char buf[MAXCMDLEN+1], buf2[MAXCMDLEN+1]; + char *s, *z, *arg0; + char **argv, **pp, **newenvp = NULL; + int eno = 0, ee; + + arg0 = (char *) peekfirst(args); + if (isset(RESTRICTED) && (strchr(arg0, '/') || defpath)) { + zerr("%s: restricted", arg0); + _exit(1); + } + + /* If the parameter STTY is set in the command's environment, * + * we first run the stty command with the value of this * + * parameter as it arguments. */ + if ((s = STTYval) && isatty(0) && (GETPGRP() == getpid())) { + char *t = tricat("stty", " ", s); + + STTYval = 0; /* this prevents infinite recursion */ + zsfree(s); + execstring(t, 1, 0, "stty"); + zsfree(t); + } else if (s) { + STTYval = 0; + zsfree(s); + } + + /* If ARGV0 is in the commands environment, we use * + * that as argv[0] for this external command */ + if (unset(RESTRICTED) && (z = zgetenv("ARGV0"))) { + setdata(firstnode(args), (void *) ztrdup(z)); + /* + * Note we don't do anything with the parameter structure + * for ARGV0: that's OK since we're about to exec or exit + * on failure. + */ +#ifdef USE_SET_UNSET_ENV + unsetenv("ARGV0"); +#else + delenvvalue(z - 6); +#endif + } else if (flags & BINF_DASH) { + /* Else if the pre-command `-' was given, we add `-' * + * to the front of argv[0] for this command. */ + sprintf(buf2, "-%s", arg0); + setdata(firstnode(args), (void *) ztrdup(buf2)); + } + + argv = makecline(args); + if (flags & BINF_CLEARENV) + newenvp = blank_env; + + /* + * Note that we don't close fd's attached to process substitution + * here, which should be visible to external processes. + */ + closem(FDT_XTRACE, 0); +#ifndef FD_CLOEXEC + if (SHTTY != -1) { + close(SHTTY); + SHTTY = -1; + } +#endif + child_unblock(); + if ((int) strlen(arg0) >= PATH_MAX) { + zerr("command too long: %s", arg0); + _exit(1); + } + for (s = arg0; *s; s++) + if (*s == '/') { + int lerrno = zexecve(arg0, argv, newenvp); + if (arg0 == s || unset(PATHDIRS) || + (arg0[0] == '.' && (arg0 + 1 == s || + (arg0[1] == '.' && arg0 + 2 == s)))) { + zerr("%e: %s", lerrno, arg0); + _exit((lerrno == EACCES || lerrno == ENOEXEC) ? 126 : 127); + } + break; + } + + /* for command -p, search the default path */ + if (defpath) { + char pbuf[PATH_MAX+1]; + char *dptr; + + if (!search_defpath(arg0, pbuf, PATH_MAX)) { + if (commandnotfound(arg0, args) == 0) + _exit(lastval); + zerr("command not found: %s", arg0); + _exit(127); + } + + ee = zexecve(pbuf, argv, newenvp); + + if ((dptr = strrchr(pbuf, '/'))) + *dptr = '\0'; + if (isgooderr(ee, *pbuf ? pbuf : "/")) + eno = ee; + + } else { + + if ((cn = (Cmdnam) cmdnamtab->getnode(cmdnamtab, arg0))) { + char nn[PATH_MAX+1], *dptr; + + if (cn->node.flags & HASHED) + strcpy(nn, cn->u.cmd); + else { + for (pp = path; pp < cn->u.name; pp++) + if (!**pp || (**pp == '.' && (*pp)[1] == '\0')) { + ee = zexecve(arg0, argv, newenvp); + if (isgooderr(ee, *pp)) + eno = ee; + } else if (**pp != '/') { + z = buf; + strucpy(&z, *pp); + *z++ = '/'; + strcpy(z, arg0); + ee = zexecve(buf, argv, newenvp); + if (isgooderr(ee, *pp)) + eno = ee; + } + strcpy(nn, cn->u.name ? *(cn->u.name) : ""); + strcat(nn, "/"); + strcat(nn, cn->node.nam); + } + ee = zexecve(nn, argv, newenvp); + + if ((dptr = strrchr(nn, '/'))) + *dptr = '\0'; + if (isgooderr(ee, *nn ? nn : "/")) + eno = ee; + } + for (pp = path; *pp; pp++) + if (!(*pp)[0] || ((*pp)[0] == '.' && !(*pp)[1])) { + ee = zexecve(arg0, argv, newenvp); + if (isgooderr(ee, *pp)) + eno = ee; + } else { + z = buf; + strucpy(&z, *pp); + *z++ = '/'; + strcpy(z, arg0); + ee = zexecve(buf, argv, newenvp); + if (isgooderr(ee, *pp)) + eno = ee; + } + } + + if (eno) + zerr("%e: %s", eno, arg0); + else if (commandnotfound(arg0, args) == 0) + _exit(lastval); + else + zerr("command not found: %s", arg0); + _exit((eno == EACCES || eno == ENOEXEC) ? 126 : 127); +} + +#define RET_IF_COM(X) { if (iscom(X)) return docopy ? dupstring(X) : arg0; } + +/* + * Get the full pathname of an external command. + * If the second argument is zero, return the first argument if found; + * if non-zero, return the path using heap memory. (RET_IF_COM(X), + * above). + * If the third argument is non-zero, use the system default path + * instead of the current path. + */ + +/**/ +mod_export char * +findcmd(char *arg0, int docopy, int default_path) +{ + char **pp; + char *z, *s, buf[MAXCMDLEN]; + Cmdnam cn; + + if (default_path) + { + if (search_defpath(arg0, buf, MAXCMDLEN)) + return docopy ? dupstring(buf) : arg0; + return NULL; + } + cn = (Cmdnam) cmdnamtab->getnode(cmdnamtab, arg0); + if (!cn && isset(HASHCMDS) && !isrelative(arg0)) + cn = hashcmd(arg0, path); + if ((int) strlen(arg0) > PATH_MAX) + return NULL; + if ((s = strchr(arg0, '/'))) { + RET_IF_COM(arg0); + if (arg0 == s || unset(PATHDIRS) || !strncmp(arg0, "./", 2) || + !strncmp(arg0, "../", 3)) { + return NULL; + } + } + if (cn) { + char nn[PATH_MAX+1]; + + if (cn->node.flags & HASHED) + strcpy(nn, cn->u.cmd); + else { + for (pp = path; pp < cn->u.name; pp++) + if (**pp != '/') { + z = buf; + if (**pp) { + strucpy(&z, *pp); + *z++ = '/'; + } + strcpy(z, arg0); + RET_IF_COM(buf); + } + strcpy(nn, cn->u.name ? *(cn->u.name) : ""); + strcat(nn, "/"); + strcat(nn, cn->node.nam); + } + RET_IF_COM(nn); + } + for (pp = path; *pp; pp++) { + z = buf; + if (**pp) { + strucpy(&z, *pp); + *z++ = '/'; + } + strcpy(z, arg0); + RET_IF_COM(buf); + } + return NULL; +} + +/* + * Return TRUE if the given path denotes an executable regular file, or a + * symlink to one. + */ + +/**/ +int +iscom(char *s) +{ + struct stat statbuf; + char *us = unmeta(s); + + return (access(us, X_OK) == 0 && stat(us, &statbuf) >= 0 && + S_ISREG(statbuf.st_mode)); +} + +/**/ +int +isreallycom(Cmdnam cn) +{ + char fullnam[MAXCMDLEN]; + + if (cn->node.flags & HASHED) + strcpy(fullnam, cn->u.cmd); + else if (!cn->u.name) + return 0; + else { + strcpy(fullnam, *(cn->u.name)); + strcat(fullnam, "/"); + strcat(fullnam, cn->node.nam); + } + return iscom(fullnam); +} + +/* + * Return TRUE if the given path contains a dot or dot-dot component + * and does not start with a slash. + */ + +/**/ +int +isrelative(char *s) +{ + if (*s != '/') + return 1; + for (; *s; s++) + if (*s == '.' && s[-1] == '/' && + (s[1] == '/' || s[1] == '\0' || + (s[1] == '.' && (s[2] == '/' || s[2] == '\0')))) + return 1; + return 0; +} + +/**/ +mod_export Cmdnam +hashcmd(char *arg0, char **pp) +{ + Cmdnam cn; + char *s, buf[PATH_MAX+1]; + char **pq; + + for (; *pp; pp++) + if (**pp == '/') { + s = buf; + struncpy(&s, *pp, PATH_MAX); + *s++ = '/'; + if ((s - buf) + strlen(arg0) >= PATH_MAX) + continue; + strcpy(s, arg0); + if (iscom(buf)) + break; + } + + if (!*pp) + return NULL; + + cn = (Cmdnam) zshcalloc(sizeof *cn); + cn->node.flags = 0; + cn->u.name = pp; + cmdnamtab->addnode(cmdnamtab, ztrdup(arg0), cn); + + if (isset(HASHDIRS)) { + for (pq = pathchecked; pq <= pp; pq++) + hashdir(pq); + pathchecked = pp + 1; + } + + return cn; +} + +/**/ +int +forklevel; + +/* Arguments to entersubsh() */ +enum { + /* Subshell is to be run asynchronously (else synchronously) */ + ESUB_ASYNC = 0x01, + /* + * Perform process group and tty handling and clear the + * (real) job table, since it won't be any longer valid + */ + ESUB_PGRP = 0x02, + /* Don't unset traps */ + ESUB_KEEPTRAP = 0x04, + /* This is only a fake entry to a subshell */ + ESUB_FAKE = 0x08, + /* Release the process group if pid is the shell's process group */ + ESUB_REVERTPGRP = 0x10, + /* Don't handle the MONITOR option even if previously set */ + ESUB_NOMONITOR = 0x20, + /* This is a subshell where job control is allowed */ + ESUB_JOB_CONTROL = 0x40 +}; + +/**/ +static void +entersubsh(int flags) +{ + int i, sig, monitor, job_control_ok; + + if (!(flags & ESUB_KEEPTRAP)) + for (sig = 0; sig < SIGCOUNT; sig++) + if (!(sigtrapped[sig] & ZSIG_FUNC)) + unsettrap(sig); + monitor = isset(MONITOR); + job_control_ok = monitor && (flags & ESUB_JOB_CONTROL) && isset(POSIXJOBS); + if (flags & ESUB_NOMONITOR) + opts[MONITOR] = 0; + if (!isset(MONITOR)) { + if (flags & ESUB_ASYNC) { + settrap(SIGINT, NULL, 0); + settrap(SIGQUIT, NULL, 0); + if (isatty(0)) { + close(0); + if (open("/dev/null", O_RDWR | O_NOCTTY)) { + zerr("can't open /dev/null: %e", errno); + _exit(1); + } + } + } + } else if (thisjob != -1 && (flags & ESUB_PGRP)) { + if (jobtab[list_pipe_job].gleader && (list_pipe || list_pipe_child)) { + if (setpgrp(0L, jobtab[list_pipe_job].gleader) == -1 || + killpg(jobtab[list_pipe_job].gleader, 0) == -1) { + jobtab[list_pipe_job].gleader = + jobtab[thisjob].gleader = (list_pipe_child ? mypgrp : getpid()); + setpgrp(0L, jobtab[list_pipe_job].gleader); + if (!(flags & ESUB_ASYNC)) + attachtty(jobtab[thisjob].gleader); + } + } + else if (!jobtab[thisjob].gleader || + setpgrp(0L, jobtab[thisjob].gleader) == -1) { + /* + * This is the standard point at which a newly started + * process gets put into the foreground by taking over + * the terminal. Note that in normal circumstances we do + * this only from the process itself. This only works if + * we are still ignoring SIGTTOU at this point; in this + * case ignoring the signal has the special effect that + * the operation is allowed to work (in addition to not + * causing the shell to be suspended). + */ + jobtab[thisjob].gleader = getpid(); + if (list_pipe_job != thisjob && + !jobtab[list_pipe_job].gleader) + jobtab[list_pipe_job].gleader = jobtab[thisjob].gleader; + setpgrp(0L, jobtab[thisjob].gleader); + if (!(flags & ESUB_ASYNC)) + attachtty(jobtab[thisjob].gleader); + } + } + if (!(flags & ESUB_FAKE)) + subsh = 1; + /* + * Increment the visible parameter ZSH_SUBSHELL even if this + * is a fake subshell because we are exec'ing at the end. + * Logically this should be equivalent to a real subshell so + * we don't hang out the dirty washing. + */ + zsh_subshell++; + if ((flags & ESUB_REVERTPGRP) && getpid() == mypgrp) + release_pgrp(); + shout = NULL; + if (flags & ESUB_NOMONITOR) { + /* + * Allowing any form of interactive signalling here is + * actively harmful as we are in a context where there is no + * control over the process. + */ + signal_ignore(SIGTTOU); + signal_ignore(SIGTTIN); + signal_ignore(SIGTSTP); + } else if (!job_control_ok) { + /* + * If this process is not going to be doing job control, + * we don't want to do special things with the corresponding + * signals. If it is, we need to keep the special behaviour: + * see note about attachtty() above. + */ + signal_default(SIGTTOU); + signal_default(SIGTTIN); + signal_default(SIGTSTP); + } + if (interact) { + signal_default(SIGTERM); + if (!(sigtrapped[SIGINT] & ZSIG_IGNORED)) + signal_default(SIGINT); + if (!(sigtrapped[SIGPIPE])) + signal_default(SIGPIPE); + } + if (!(sigtrapped[SIGQUIT] & ZSIG_IGNORED)) + signal_default(SIGQUIT); + /* + * sigtrapped[sig] == ZSIG_IGNORED for signals that remain ignored, + * but other trapped signals are temporarily blocked when intrap, + * and must be unblocked before continuing into the subshell. This + * is orthogonal to what the default handler for the signal may be. + * + * Start loop at 1 because 0 is SIGEXIT + */ + if (intrap) + for (sig = 1; sig < SIGCOUNT; sig++) + if (sigtrapped[sig] && sigtrapped[sig] != ZSIG_IGNORED) + signal_unblock(signal_mask(sig)); + if (!job_control_ok) + opts[MONITOR] = 0; + opts[USEZLE] = 0; + zleactive = 0; + /* + * If we've saved fd's for later restoring, we're never going + * to restore them now, so just close them. + */ + for (i = 10; i <= max_zsh_fd; i++) { + if (fdtable[i] & FDT_SAVED_MASK) + zclose(i); + } + if (flags & ESUB_PGRP) + clearjobtab(monitor); + get_usage(); + forklevel = locallevel; +} + +/* execute a string */ + +/**/ +mod_export void +execstring(char *s, int dont_change_job, int exiting, char *context) +{ + Eprog prog; + + pushheap(); + if (isset(VERBOSE)) { + zputs(s, stderr); + fputc('\n', stderr); + fflush(stderr); + } + if ((prog = parse_string(s, 0))) + execode(prog, dont_change_job, exiting, context); + popheap(); +} + +/**/ +mod_export void +execode(Eprog p, int dont_change_job, int exiting, char *context) +{ + struct estate s; + static int zsh_eval_context_len; + int alen; + + if (!zsh_eval_context_len) { + zsh_eval_context_len = 16; + alen = 0; + zsh_eval_context = (char **)zalloc(zsh_eval_context_len * + sizeof(*zsh_eval_context)); + } else { + alen = arrlen(zsh_eval_context); + if (zsh_eval_context_len == alen + 1) { + zsh_eval_context_len *= 2; + zsh_eval_context = zrealloc(zsh_eval_context, + zsh_eval_context_len * + sizeof(*zsh_eval_context)); + } + } + zsh_eval_context[alen] = context; + zsh_eval_context[alen+1] = NULL; + + s.prog = p; + s.pc = p->prog; + s.strs = p->strs; + useeprog(p); /* Mark as in use */ + + execlist(&s, dont_change_job, exiting); + + freeeprog(p); /* Free if now unused */ + + /* + * zsh_eval_context may have been altered by a recursive + * call, but that's OK since we're using the global value. + */ + zsh_eval_context[alen] = NULL; +} + +/* Execute a simplified command. This is used to execute things that + * will run completely in the shell, so that we can by-pass all that + * nasty job-handling and redirection stuff in execpline and execcmd. */ + +/**/ +static int +execsimple(Estate state) +{ + wordcode code = *state->pc++; + int lv, otj; + + if (errflag) + return (lastval = 1); + + if (!isset(EXECOPT)) + return lastval = 0; + + /* In evaluated traps, don't modify the line number. */ + if (!IN_EVAL_TRAP() && !ineval && code) + lineno = code - 1; + + code = wc_code(*state->pc++); + + /* + * Because we're bypassing job control, ensure the called + * code doesn't see the current job. + */ + otj = thisjob; + thisjob = -1; + + if (code == WC_ASSIGN) { + cmdoutval = 0; + addvars(state, state->pc - 1, 0); + setunderscore(""); + if (isset(XTRACE)) { + fputc('\n', xtrerr); + fflush(xtrerr); + } + lv = (errflag ? errflag : cmdoutval); + } else { + int q = queue_signal_level(); + dont_queue_signals(); + if (code == WC_FUNCDEF) + lv = execfuncdef(state, NULL); + else + lv = (execfuncs[code - WC_CURSH])(state, 0); + restore_queue_signals(q); + } + + thisjob = otj; + + return lastval = lv; +} + +/* Main routine for executing a list. * + * exiting means that the (sub)shell we are in is a definite goner * + * after the current list is finished, so we may be able to exec the * + * last command directly instead of forking. If dont_change_job is * + * nonzero, then restore the current job number after executing the * + * list. */ + +/**/ +void +execlist(Estate state, int dont_change_job, int exiting) +{ + static int donetrap; + Wordcode next; + wordcode code; + int ret, cj, csp, ltype; + int old_pline_level, old_list_pipe, old_list_pipe_job; + char *old_list_pipe_text; + zlong oldlineno; + /* + * ERREXIT only forces the shell to exit if the last command in a && + * or || fails. This is the case even if an earlier command is a + * shell function or other current shell structure, so we have to set + * noerrexit here if the sublist is not of type END. + */ + int oldnoerrexit = noerrexit; + + queue_signals(); + + cj = thisjob; + old_pline_level = pline_level; + old_list_pipe = list_pipe; + old_list_pipe_job = list_pipe_job; + if (*list_pipe_text) + old_list_pipe_text = ztrdup(list_pipe_text); + else + old_list_pipe_text = NULL; + oldlineno = lineno; + + if (sourcelevel && unset(SHINSTDIN)) { + pline_level = list_pipe = list_pipe_job = 0; + *list_pipe_text = '\0'; + } + + /* Loop over all sets of comands separated by newline, * + * semi-colon or ampersand (`sublists'). */ + code = *state->pc++; + if (wc_code(code) != WC_LIST) { + /* Empty list; this returns status zero. */ + lastval = 0; + } + while (wc_code(code) == WC_LIST && !breaks && !retflag && !errflag) { + int donedebug; + int this_donetrap = 0; + this_noerrexit = 0; + + ltype = WC_LIST_TYPE(code); + csp = cmdsp; + + if (!IN_EVAL_TRAP() && !ineval) { + /* + * Ensure we have a valid line number for debugging, + * unless we are in an evaluated trap in which case + * we retain the line number from the context. + * This was added for DEBUGBEFORECMD but I've made + * it unconditional to keep dependencies to a minimum. + * + * The line number is updated for individual pipelines. + * This isn't necessary for debug traps since they only + * run once per sublist. + */ + wordcode code2 = *state->pc, lnp1 = 0; + if (ltype & Z_SIMPLE) { + lnp1 = code2; + } else if (wc_code(code2) == WC_SUBLIST) { + if (WC_SUBLIST_FLAGS(code2) == WC_SUBLIST_SIMPLE) + lnp1 = state->pc[1]; + else + lnp1 = WC_PIPE_LINENO(state->pc[1]); + } + if (lnp1) + lineno = lnp1 - 1; + } + + if (sigtrapped[SIGDEBUG] && isset(DEBUGBEFORECMD) && !intrap) { + Wordcode pc2 = state->pc; + int oerrexit_opt = opts[ERREXIT]; + Param pm; + opts[ERREXIT] = 0; + noerrexit = NOERREXIT_EXIT | NOERREXIT_RETURN; + if (ltype & Z_SIMPLE) /* skip the line number */ + pc2++; + pm = assignsparam("ZSH_DEBUG_CMD", + getpermtext(state->prog, pc2, 0), + 0); + + exiting = donetrap; + ret = lastval; + dotrap(SIGDEBUG); + if (!retflag) + lastval = ret; + donetrap = exiting; + noerrexit = oldnoerrexit; + /* + * Only execute the trap once per sublist, even + * if the DEBUGBEFORECMD option changes. + */ + donedebug = isset(ERREXIT) ? 2 : 1; + opts[ERREXIT] = oerrexit_opt; + if (pm) + unsetparam_pm(pm, 0, 1); + } else + donedebug = intrap ? 1 : 0; + + /* Reset donetrap: this ensures that a trap is only * + * called once for each sublist that fails. */ + donetrap = 0; + if (ltype & Z_SIMPLE) { + next = state->pc + WC_LIST_SKIP(code); + if (donedebug != 2) + execsimple(state); + state->pc = next; + goto sublist_done; + } + + /* Loop through code followed by &&, ||, or end of sublist. */ + code = *state->pc++; + if (donedebug == 2) { + /* Skip sublist. */ + while (wc_code(code) == WC_SUBLIST) { + state->pc = state->pc + WC_SUBLIST_SKIP(code); + if (WC_SUBLIST_TYPE(code) == WC_SUBLIST_END) + break; + code = *state->pc++; + } + donetrap = 1; + /* yucky but consistent... */ + goto sublist_done; + } + while (wc_code(code) == WC_SUBLIST) { + int isend = (WC_SUBLIST_TYPE(code) == WC_SUBLIST_END); + next = state->pc + WC_SUBLIST_SKIP(code); + if (!oldnoerrexit) + noerrexit = isend ? 0 : NOERREXIT_EXIT | NOERREXIT_RETURN; + if (WC_SUBLIST_FLAGS(code) & WC_SUBLIST_NOT) { + /* suppress errexit for "! this_command" */ + if (isend) + this_noerrexit = 1; + /* suppress errexit for ! */ + noerrexit = NOERREXIT_EXIT | NOERREXIT_RETURN; + } + switch (WC_SUBLIST_TYPE(code)) { + case WC_SUBLIST_END: + /* End of sublist; just execute, ignoring status. */ + if (WC_SUBLIST_FLAGS(code) & WC_SUBLIST_SIMPLE) + execsimple(state); + else + execpline(state, code, ltype, (ltype & Z_END) && exiting); + state->pc = next; + goto sublist_done; + break; + case WC_SUBLIST_AND: + /* If the return code is non-zero, we skip pipelines until * + * we find a sublist followed by ORNEXT. */ + if ((ret = ((WC_SUBLIST_FLAGS(code) & WC_SUBLIST_SIMPLE) ? + execsimple(state) : + execpline(state, code, Z_SYNC, 0)))) { + state->pc = next; + code = *state->pc++; + next = state->pc + WC_SUBLIST_SKIP(code); + while (wc_code(code) == WC_SUBLIST && + WC_SUBLIST_TYPE(code) == WC_SUBLIST_AND) { + state->pc = next; + code = *state->pc++; + next = state->pc + WC_SUBLIST_SKIP(code); + } + if (wc_code(code) != WC_SUBLIST) { + /* We've skipped to the end of the list, not executing * + * the final pipeline, so don't perform error handling * + * for this sublist. */ + this_donetrap = 1; + goto sublist_done; + } else if (WC_SUBLIST_TYPE(code) == WC_SUBLIST_END) { + this_donetrap = 1; + /* + * Treat this in the same way as if we reached + * the end of the sublist normally. + */ + state->pc = next; + goto sublist_done; + } + } + cmdpush(CS_CMDAND); + break; + case WC_SUBLIST_OR: + /* If the return code is zero, we skip pipelines until * + * we find a sublist followed by ANDNEXT. */ + if (!(ret = ((WC_SUBLIST_FLAGS(code) & WC_SUBLIST_SIMPLE) ? + execsimple(state) : + execpline(state, code, Z_SYNC, 0)))) { + state->pc = next; + code = *state->pc++; + next = state->pc + WC_SUBLIST_SKIP(code); + while (wc_code(code) == WC_SUBLIST && + WC_SUBLIST_TYPE(code) == WC_SUBLIST_OR) { + state->pc = next; + code = *state->pc++; + next = state->pc + WC_SUBLIST_SKIP(code); + } + if (wc_code(code) != WC_SUBLIST) { + /* We've skipped to the end of the list, not executing * + * the final pipeline, so don't perform error handling * + * for this sublist. */ + this_donetrap = 1; + goto sublist_done; + } else if (WC_SUBLIST_TYPE(code) == WC_SUBLIST_END) { + this_donetrap = 1; + /* + * Treat this in the same way as if we reached + * the end of the sublist normally. + */ + state->pc = next; + goto sublist_done; + } + } + cmdpush(CS_CMDOR); + break; + } + state->pc = next; + code = *state->pc++; + } + state->pc--; +sublist_done: + + /* + * See hairy code near the end of execif() for the + * following. "noerrexit " only applies until + * we hit execcmd on the way down. We're now + * on the way back up, so don't restore it. + */ + if (!(oldnoerrexit & NOERREXIT_UNTIL_EXEC)) + noerrexit = oldnoerrexit; + + if (sigtrapped[SIGDEBUG] && !isset(DEBUGBEFORECMD) && !donedebug) { + /* + * Save and restore ERREXIT for consistency with + * DEBUGBEFORECMD, even though it's not used. + */ + int oerrexit_opt = opts[ERREXIT]; + opts[ERREXIT] = 0; + noerrexit = NOERREXIT_EXIT | NOERREXIT_RETURN; + exiting = donetrap; + ret = lastval; + dotrap(SIGDEBUG); + if (!retflag) + lastval = ret; + donetrap = exiting; + noerrexit = oldnoerrexit; + opts[ERREXIT] = oerrexit_opt; + } + + cmdsp = csp; + + /* Check whether we are suppressing traps/errexit * + * (typically in init scripts) and if we haven't * + * already performed them for this sublist. */ + if (!this_noerrexit && !donetrap && !this_donetrap) { + if (sigtrapped[SIGZERR] && lastval && + !(noerrexit & NOERREXIT_EXIT)) { + dotrap(SIGZERR); + donetrap = 1; + } + if (lastval) { + int errreturn = isset(ERRRETURN) && + (isset(INTERACTIVE) || locallevel || sourcelevel) && + !(noerrexit & NOERREXIT_RETURN); + int errexit = (isset(ERREXIT) || + (isset(ERRRETURN) && !errreturn)) && + !(noerrexit & NOERREXIT_EXIT); + if (errexit) { + if (sigtrapped[SIGEXIT]) + dotrap(SIGEXIT); + if (mypid != getpid()) + _exit(lastval); + else + exit(lastval); + } + if (errreturn) { + retflag = 1; + breaks = loops; + } + } + } + if (ltype & Z_END) + break; + code = *state->pc++; + } + pline_level = old_pline_level; + list_pipe = old_list_pipe; + list_pipe_job = old_list_pipe_job; + if (old_list_pipe_text) { + strcpy(list_pipe_text, old_list_pipe_text); + zsfree(old_list_pipe_text); + } else { + *list_pipe_text = '\0'; + } + lineno = oldlineno; + if (dont_change_job) + thisjob = cj; + + if (exiting && sigtrapped[SIGEXIT]) { + dotrap(SIGEXIT); + /* Make sure this doesn't get executed again. */ + sigtrapped[SIGEXIT] = 0; + } + + unqueue_signals(); +} + +/* Execute a pipeline. * + * last1 is a flag that this command is the last command in a shell * + * that is about to exit, so we can exec instead of forking. It gets * + * passed all the way down to execcmd() which actually makes the * + * decision. A 0 is always passed if the command is not the last in * + * the pipeline. This function assumes that the sublist is not NULL. * + * If last1 is zero but the command is at the end of a pipeline, we * + * pass 2 down to execcmd(). * + */ + +/**/ +static int +execpline(Estate state, wordcode slcode, int how, int last1) +{ + int ipipe[2], opipe[2]; + int pj, newjob; + int old_simple_pline = simple_pline; + int slflags = WC_SUBLIST_FLAGS(slcode); + wordcode code = *state->pc++; + static int lastwj, lpforked; + + if (wc_code(code) != WC_PIPE) + return lastval = (slflags & WC_SUBLIST_NOT) != 0; + else if (slflags & WC_SUBLIST_NOT) + last1 = 0; + + /* If trap handlers are allowed to run here, they may start another + * external job in the middle of us starting this one, which can + * result in jobs being reaped before their job table entries have + * been initialized, which in turn leads to waiting forever for + * jobs that no longer exist. So don't do that. + */ + queue_signals(); + + pj = thisjob; + ipipe[0] = ipipe[1] = opipe[0] = opipe[1] = 0; + child_block(); + + /* + * Get free entry in job table and initialize it. This is currently + * the only call to initjob() (apart from a minor exception in + * clearjobtab()), so this is also the only place where we can + * expand the job table under us. + */ + if ((thisjob = newjob = initjob()) == -1) { + child_unblock(); + unqueue_signals(); + return 1; + } + if (how & Z_TIMED) + jobtab[thisjob].stat |= STAT_TIMED; + + if (slflags & WC_SUBLIST_COPROC) { + how = Z_ASYNC; + if (coprocin >= 0) { + zclose(coprocin); + zclose(coprocout); + } + if (mpipe(ipipe) < 0) { + coprocin = coprocout = -1; + slflags &= ~WC_SUBLIST_COPROC; + } else if (mpipe(opipe) < 0) { + close(ipipe[0]); + close(ipipe[1]); + coprocin = coprocout = -1; + slflags &= ~WC_SUBLIST_COPROC; + } else { + coprocin = ipipe[0]; + coprocout = opipe[1]; + fdtable[coprocin] = fdtable[coprocout] = FDT_UNUSED; + } + } + /* This used to set list_pipe_pid=0 unconditionally, but in things + * like `ls|if true; then sleep 20; cat; fi' where the sleep was + * stopped, the top-level execpline() didn't get the pid for the + * sub-shell because it was overwritten. */ + if (!pline_level++) { + list_pipe_pid = 0; + nowait = 0; + simple_pline = (WC_PIPE_TYPE(code) == WC_PIPE_END); + list_pipe_job = newjob; + } + lastwj = lpforked = 0; + execpline2(state, code, how, opipe[0], ipipe[1], last1); + pline_level--; + if (how & Z_ASYNC) { + lastwj = newjob; + + if (thisjob == list_pipe_job) + list_pipe_job = 0; + jobtab[thisjob].stat |= STAT_NOSTTY; + if (slflags & WC_SUBLIST_COPROC) { + zclose(ipipe[1]); + zclose(opipe[0]); + } + if (how & Z_DISOWN) { + pipecleanfilelist(jobtab[thisjob].filelist, 0); + deletejob(jobtab + thisjob, 1); + thisjob = -1; + } + else + spawnjob(); + child_unblock(); + unqueue_signals(); + /* Executing background code resets shell status */ + return lastval = 0; + } else { + if (newjob != lastwj) { + Job jn = jobtab + newjob; + int updated; + + if (newjob == list_pipe_job && list_pipe_child) + _exit(0); + + lastwj = thisjob = newjob; + + if (list_pipe || (pline_level && !(how & Z_TIMED))) + jn->stat |= STAT_NOPRINT; + + if (nowait) { + if(!pline_level) { + int jobsub; + struct process *pn, *qn; + + curjob = newjob; + DPUTS(!list_pipe_pid, "invalid list_pipe_pid"); + addproc(list_pipe_pid, list_pipe_text, 0, + &list_pipe_start); + + /* If the super-job contains only the sub-shell, the + sub-shell is the group leader. */ + if (!jn->procs->next || lpforked == 2) { + jn->gleader = list_pipe_pid; + jn->stat |= STAT_SUBLEADER; + /* + * Pick up any subjob that's still lying around + * as it's now our responsibility. + * If we find it we're a SUPERJOB. + */ + for (jobsub = 1; jobsub <= maxjob; jobsub++) { + Job jnsub = jobtab + jobsub; + if (jnsub->stat & STAT_SUBJOB_ORPHANED) { + jn->other = jobsub; + jn->stat |= STAT_SUPERJOB; + jnsub->stat &= ~STAT_SUBJOB_ORPHANED; + jnsub->other = list_pipe_pid; + } + } + } + for (pn = jobtab[jn->other].procs; pn; pn = pn->next) + if (WIFSTOPPED(pn->status)) + break; + + if (pn) { + for (qn = jn->procs; qn->next; qn = qn->next); + qn->status = pn->status; + } + + jn->stat &= ~(STAT_DONE | STAT_NOPRINT); + jn->stat |= STAT_STOPPED | STAT_CHANGED | STAT_LOCKED | + STAT_INUSE; + printjob(jn, !!isset(LONGLISTJOBS), 1); + } + else if (newjob != list_pipe_job) + deletejob(jn, 0); + else + lastwj = -1; + } + + errbrk_saved = 0; + for (; !nowait;) { + if (list_pipe_child) { + jn->stat |= STAT_NOPRINT; + makerunning(jn); + } + if (!(jn->stat & STAT_LOCKED)) { + updated = hasprocs(thisjob); + waitjobs(); /* deals with signal queue */ + child_block(); + } else + updated = 0; + if (!updated && + list_pipe_job && hasprocs(list_pipe_job) && + !(jobtab[list_pipe_job].stat & STAT_STOPPED)) { + int q = queue_signal_level(); + child_unblock(); + child_block(); + dont_queue_signals(); + restore_queue_signals(q); + } + if (list_pipe_child && + jn->stat & STAT_DONE && + lastval2 & 0200) + killpg(mypgrp, lastval2 & ~0200); + if (!list_pipe_child && !lpforked && !subsh && jobbing && + (list_pipe || last1 || pline_level) && + ((jn->stat & STAT_STOPPED) || + (list_pipe_job && pline_level && + (jobtab[list_pipe_job].stat & STAT_STOPPED)))) { + pid_t pid = 0; + int synch[2]; + struct timeval bgtime; + + /* + * A pipeline with the shell handling the right + * hand side was stopped. We'll fork to allow + * it to continue. + */ + if (pipe(synch) < 0 || (pid = zfork(&bgtime)) == -1) { + /* Failure */ + if (pid < 0) { + close(synch[0]); + close(synch[1]); + } else + zerr("pipe failed: %e", errno); + zleentry(ZLE_CMD_TRASH); + fprintf(stderr, "zsh: job can't be suspended\n"); + fflush(stderr); + makerunning(jn); + killjb(jn, SIGCONT); + thisjob = newjob; + } + else if (pid) { + /* + * Parent: job control is here. If the job + * started for the RHS of the pipeline is still + * around, then its a SUBJOB and the job for + * earlier parts of the pipeeline is its SUPERJOB. + * The newly forked shell isn't recorded as a + * separate job here, just as list_pipe_pid. + * If the superjob exits (it may already have + * done so, see child branch below), we'll use + * list_pipe_pid to form the basis of a + * replacement job --- see SUBLEADER code above. + */ + char dummy; + + lpforked = + (killpg(jobtab[list_pipe_job].gleader, 0) == -1 ? 2 : 1); + list_pipe_pid = pid; + list_pipe_start = bgtime; + nowait = 1; + errflag |= ERRFLAG_ERROR; + breaks = loops; + close(synch[1]); + read_loop(synch[0], &dummy, 1); + close(synch[0]); + /* If this job has finished, we leave it as a + * normal (non-super-) job. */ + if (!(jn->stat & STAT_DONE)) { + jobtab[list_pipe_job].other = newjob; + jobtab[list_pipe_job].stat |= STAT_SUPERJOB; + jn->stat |= STAT_SUBJOB | STAT_NOPRINT; + jn->other = list_pipe_pid; /* see zsh.h */ + if (hasprocs(list_pipe_job)) + jn->gleader = jobtab[list_pipe_job].gleader; + } + if ((list_pipe || last1) && hasprocs(list_pipe_job)) + killpg(jobtab[list_pipe_job].gleader, SIGSTOP); + break; + } + else { + close(synch[0]); + entersubsh(ESUB_ASYNC); + /* + * At this point, we used to attach this process + * to the process group of list_pipe_job (the + * new superjob) any time that was still available. + * That caused problems in at least two + * cases because this forked shell was then + * suspended with the right hand side of the + * pipeline, and the SIGSTOP below suspended + * it a second time when it was continued. + * + * It's therefore not clear entirely why you'd ever + * do anything other than the following, but no + * doubt we'll find out... + */ + setpgrp(0L, mypgrp = getpid()); + close(synch[1]); + kill(getpid(), SIGSTOP); + list_pipe = 0; + list_pipe_child = 1; + opts[INTERACTIVE] = 0; + if (errbrk_saved) { + /* + * Keep any user interrupt bit in errflag. + */ + errflag = prev_errflag | (errflag & ERRFLAG_INT); + breaks = prev_breaks; + } + break; + } + } + else if (subsh && jn->stat & STAT_STOPPED) + thisjob = newjob; + else + break; + } + child_unblock(); + unqueue_signals(); + + if (list_pipe && (lastval & 0200) && pj >= 0 && + (!(jn->stat & STAT_INUSE) || (jn->stat & STAT_DONE))) { + deletejob(jn, 0); + jn = jobtab + pj; + if (jn->gleader) + killjb(jn, lastval & ~0200); + } + if (list_pipe_child || + ((jn->stat & STAT_DONE) && + (list_pipe || (pline_level && !(jn->stat & STAT_SUBJOB))))) + deletejob(jn, 0); + thisjob = pj; + } + else + unqueue_signals(); + if ((slflags & WC_SUBLIST_NOT) && !errflag) + lastval = !lastval; + } + if (!pline_level) + simple_pline = old_simple_pline; + return lastval; +} + +/* execute pipeline. This function assumes the `pline' is not NULL. */ + +/**/ +static void +execpline2(Estate state, wordcode pcode, + int how, int input, int output, int last1) +{ + struct execcmd_params eparams; + + if (breaks || retflag) + return; + + /* In evaluated traps, don't modify the line number. */ + if (!IN_EVAL_TRAP() && !ineval && WC_PIPE_LINENO(pcode)) + lineno = WC_PIPE_LINENO(pcode) - 1; + + if (pline_level == 1) { + if ((how & Z_ASYNC) || !sfcontext) + strcpy(list_pipe_text, + getjobtext(state->prog, + state->pc + (WC_PIPE_TYPE(pcode) == WC_PIPE_END ? + 0 : 1))); + else + list_pipe_text[0] = '\0'; + } + if (WC_PIPE_TYPE(pcode) == WC_PIPE_END) { + execcmd_analyse(state, &eparams); + execcmd_exec(state, &eparams, input, output, how, last1 ? 1 : 2, -1); + } else { + int pipes[2]; + int old_list_pipe = list_pipe; + Wordcode next = state->pc + (*state->pc); + + ++state->pc; + execcmd_analyse(state, &eparams); + + if (mpipe(pipes) < 0) { + /* FIXME */ + } + + addfilelist(NULL, pipes[0]); + execcmd_exec(state, &eparams, input, pipes[1], how, 0, pipes[0]); + zclose(pipes[1]); + state->pc = next; + + /* if another execpline() is invoked because the command is * + * a list it must know that we're already in a pipeline */ + cmdpush(CS_PIPE); + list_pipe = 1; + execpline2(state, *state->pc++, how, pipes[0], output, last1); + list_pipe = old_list_pipe; + cmdpop(); + } +} + +/* make the argv array */ + +/**/ +static char ** +makecline(LinkList list) +{ + LinkNode node; + char **argv, **ptr; + + /* A bigger argv is necessary for executing scripts */ + ptr = argv = 2 + (char **) hcalloc((countlinknodes(list) + 4) * + sizeof(char *)); + + if (isset(XTRACE)) { + if (!doneps4) + printprompt4(); + + for (node = firstnode(list); node; incnode(node)) { + *ptr++ = (char *)getdata(node); + quotedzputs(getdata(node), xtrerr); + if (nextnode(node)) + fputc(' ', xtrerr); + } + fputc('\n', xtrerr); + fflush(xtrerr); + } else { + for (node = firstnode(list); node; incnode(node)) + *ptr++ = (char *)getdata(node); + } + *ptr = NULL; + return (argv); +} + +/**/ +mod_export void +untokenize(char *s) +{ + if (*s) { + int c; + + while ((c = *s++)) + if (itok(c)) { + char *p = s - 1; + + if (c != Nularg) + *p++ = ztokens[c - Pound]; + + while ((c = *s++)) { + if (itok(c)) { + if (c != Nularg) + *p++ = ztokens[c - Pound]; + } else + *p++ = c; + } + *p = '\0'; + break; + } + } +} + + +/* + * Given a tokenized string, output it to standard output in + * such a way that it's clear which tokens are active. + * Hence Star becomes an unquoted "*", while a "*" becomes "\*". + * + * The code here is a kind of amalgamation of the tests in + * zshtokenize() and untokenize() with some outputting. + */ + +/**/ +void +quote_tokenized_output(char *str, FILE *file) +{ + char *s = str; + + for (; *s; s++) { + switch (*s) { + case Meta: + putc(*++s ^ 32, file); + continue; + + case Nularg: + /* Do nothing. I think. */ + continue; + + case '\\': + case '<': + case '>': + case '(': + case '|': + case ')': + case '^': + case '#': + case '~': + case '[': + case ']': + case '*': + case '?': + case '$': + case ' ': + putc('\\', file); + break; + + case '\t': + fputs("$'\\t'", file); + continue; + + case '\n': + fputs("$'\\n'", file); + continue; + + case '\r': + fputs("$'\\r'", file); + continue; + + case '=': + if (s == str) + putc('\\', file); + break; + + default: + if (itok(*s)) { + putc(ztokens[*s - Pound], file); + continue; + } + break; + } + + putc(*s, file); + } +} + +/* Check that we can use a parameter for allocating a file descriptor. */ + +static int +checkclobberparam(struct redir *f) +{ + struct value vbuf; + Value v; + char *s = f->varid; + int fd; + + if (!s) + return 1; + + if (!(v = getvalue(&vbuf, &s, 0))) + return 1; + + if (v->pm->node.flags & PM_READONLY) { + zwarn("can't allocate file descriptor to readonly parameter %s", + f->varid); + /* don't flag a system error for this */ + errno = 0; + return 0; + } + + /* + * We can't clobber the value in the parameter if it's + * already an opened file descriptor --- that means it's a decimal + * integer corresponding to an opened file descriptor, + * not merely an expression that evaluates to a file descriptor. + */ + if (!isset(CLOBBER) && (s = getstrvalue(v)) && + (fd = (int)zstrtol(s, &s, 10)) >= 0 && !*s && + fd <= max_zsh_fd && fdtable[fd] == FDT_EXTERNAL) { + zwarn("can't clobber parameter %s containing file descriptor %d", + f->varid, fd); + /* don't flag a system error for this */ + errno = 0; + return 0; + } + return 1; +} + +/* Open a file for writing redirection */ + +/**/ +static int +clobber_open(struct redir *f) +{ + struct stat buf; + int fd, oerrno; + + /* If clobbering, just open. */ + if (isset(CLOBBER) || IS_CLOBBER_REDIR(f->type)) + return open(unmeta(f->name), + O_WRONLY | O_CREAT | O_TRUNC | O_NOCTTY, 0666); + + /* If not clobbering, attempt to create file exclusively. */ + if ((fd = open(unmeta(f->name), + O_WRONLY | O_CREAT | O_EXCL | O_NOCTTY, 0666)) >= 0) + return fd; + + /* If that fails, we are still allowed to open non-regular files. * + * Try opening, and if it's a regular file then close it again * + * because we weren't supposed to open it. */ + oerrno = errno; + if ((fd = open(unmeta(f->name), O_WRONLY | O_NOCTTY)) != -1) { + if(!fstat(fd, &buf) && !S_ISREG(buf.st_mode)) + return fd; + close(fd); + } + errno = oerrno; + return -1; +} + +/* size of buffer for tee and cat processes */ +#define TCBUFSIZE 4092 + +/* close an multio (success) */ + +/**/ +static void +closemn(struct multio **mfds, int fd, int type) +{ + if (fd >= 0 && mfds[fd] && mfds[fd]->ct >= 2) { + struct multio *mn = mfds[fd]; + char buf[TCBUFSIZE]; + int len, i; + pid_t pid; + struct timeval bgtime; + + /* + * We need to block SIGCHLD in case the process + * we are spawning terminates before the job table + * is set up to handle it. + */ + child_block(); + if ((pid = zfork(&bgtime))) { + for (i = 0; i < mn->ct; i++) + zclose(mn->fds[i]); + zclose(mn->pipe); + if (pid == -1) { + mfds[fd] = NULL; + child_unblock(); + return; + } + mn->ct = 1; + mn->fds[0] = fd; + addproc(pid, NULL, 1, &bgtime); + child_unblock(); + return; + } + /* pid == 0 */ + child_unblock(); + closeallelse(mn); + if (mn->rflag) { + /* tee process */ + while ((len = read(mn->pipe, buf, TCBUFSIZE)) != 0) { + if (len < 0) { + if (errno == EINTR) + continue; + else + break; + } + for (i = 0; i < mn->ct; i++) + write_loop(mn->fds[i], buf, len); + } + } else { + /* cat process */ + for (i = 0; i < mn->ct; i++) + while ((len = read(mn->fds[i], buf, TCBUFSIZE)) != 0) { + if (len < 0) { + if (errno == EINTR) + continue; + else + break; + } + write_loop(mn->pipe, buf, len); + } + } + _exit(0); + } else if (fd >= 0 && type == REDIR_CLOSE) + mfds[fd] = NULL; +} + +/* close all the mnodes (failure) */ + +/**/ +static void +closemnodes(struct multio **mfds) +{ + int i, j; + + for (i = 0; i < 10; i++) + if (mfds[i]) { + for (j = 0; j < mfds[i]->ct; j++) + zclose(mfds[i]->fds[j]); + mfds[i] = NULL; + } +} + +/**/ +static void +closeallelse(struct multio *mn) +{ + int i, j; + long openmax; + + openmax = fdtable_size; + + for (i = 0; i < openmax; i++) + if (mn->pipe != i) { + for (j = 0; j < mn->ct; j++) + if (mn->fds[j] == i) + break; + if (j == mn->ct) + zclose(i); + } +} + +/* + * A multio is a list of fds associated with a certain fd. + * Thus if you do "foo >bar >ble", the multio for fd 1 will have + * two fds, the result of open("bar",...), and the result of + * open("ble",....). + */ + +/* + * Add a fd to an multio. fd1 must be < 10, and may be in any state. + * fd2 must be open, and is `consumed' by this function. Note that + * fd1 == fd2 is possible, and indicates that fd1 was really closed. + * We effectively do `fd2 = movefd(fd2)' at the beginning of this + * function, but in most cases we can avoid an extra dup by delaying + * the movefd: we only >need< to move it if we're actually doing a + * multiple redirection. + * + * If varid is not NULL, we open an fd above 10 and set the parameter + * named varid to that value. fd1 is not used. + */ + +/**/ +static void +addfd(int forked, int *save, struct multio **mfds, int fd1, int fd2, int rflag, + char *varid) +{ + int pipes[2]; + + if (varid) { + /* fd will be over 10, don't touch mfds */ + fd1 = movefd(fd2); + if (fd1 == -1) { + zerr("cannot moved fd %d: %e", fd2, errno); + return; + } else { + fdtable[fd1] = FDT_EXTERNAL; + setiparam(varid, (zlong)fd1); + /* + * If setting the parameter failed, close the fd else + * it will leak. + */ + if (errflag) + zclose(fd1); + } + } else if (!mfds[fd1] || unset(MULTIOS)) { + if(!mfds[fd1]) { /* starting a new multio */ + mfds[fd1] = (struct multio *) zhalloc(sizeof(struct multio)); + if (!forked && save[fd1] == -2) { + if (fd1 == fd2) + save[fd1] = -1; + else { + int fdN = movefd(fd1); + /* + * fd1 may already be closed here, so + * ignore bad file descriptor error + */ + if (fdN < 0) { + if (errno != EBADF) { + zerr("cannot duplicate fd %d: %e", fd1, errno); + mfds[fd1] = NULL; + closemnodes(mfds); + return; + } + } else { + DPUTS(fdtable[fdN] != FDT_INTERNAL, + "Saved file descriptor not marked as internal"); + fdtable[fdN] |= FDT_SAVED_MASK; + } + save[fd1] = fdN; + } + } + } + if (!varid) + redup(fd2, fd1); + mfds[fd1]->ct = 1; + mfds[fd1]->fds[0] = fd1; + mfds[fd1]->rflag = rflag; + } else { + if (mfds[fd1]->rflag != rflag) { + zerr("file mode mismatch on fd %d", fd1); + closemnodes(mfds); + return; + } + if (mfds[fd1]->ct == 1) { /* split the stream */ + int fdN = movefd(fd1); + if (fdN < 0) { + zerr("multio failed for fd %d: %e", fd1, errno); + closemnodes(mfds); + return; + } + mfds[fd1]->fds[0] = fdN; + fdN = movefd(fd2); + if (fdN < 0) { + zerr("multio failed for fd %d: %e", fd2, errno); + closemnodes(mfds); + return; + } + mfds[fd1]->fds[1] = fdN; + if (mpipe(pipes) < 0) { + zerr("multio failed for fd %d: %e", fd2, errno); + closemnodes(mfds); + return; + } + mfds[fd1]->pipe = pipes[1 - rflag]; + redup(pipes[rflag], fd1); + mfds[fd1]->ct = 2; + } else { /* add another fd to an already split stream */ + int fdN; + if(!(mfds[fd1]->ct % MULTIOUNIT)) { + int new = sizeof(struct multio) + sizeof(int) * mfds[fd1]->ct; + int old = new - sizeof(int) * MULTIOUNIT; + mfds[fd1] = hrealloc((char *)mfds[fd1], old, new); + } + if ((fdN = movefd(fd2)) < 0) { + zerr("multio failed for fd %d: %e", fd2, errno); + closemnodes(mfds); + return; + } + mfds[fd1]->fds[mfds[fd1]->ct++] = fdN; + } + } +} + +/**/ +static void +addvars(Estate state, Wordcode pc, int addflags) +{ + LinkList vl; + int xtr, isstr, htok = 0; + char **arr, **ptr, *name; + int flags; + + Wordcode opc = state->pc; + wordcode ac; + local_list1(svl); + + /* + * Warn when creating a global without using typeset -g in a + * function. Don't do this if there is a list of variables marked + * to be restored after the command, since then the assignment + * is implicitly scoped. + */ + flags = !(addflags & ADDVAR_RESTORE) ? ASSPM_WARN : 0; + xtr = isset(XTRACE); + if (xtr) { + printprompt4(); + doneps4 = 1; + } + state->pc = pc; + while (wc_code(ac = *state->pc++) == WC_ASSIGN) { + int myflags = flags; + name = ecgetstr(state, EC_DUPTOK, &htok); + if (htok) + untokenize(name); + if (WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC) + myflags |= ASSPM_AUGMENT; + if (xtr) + fprintf(xtrerr, + WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC ? "%s+=" : "%s=", name); + if ((isstr = (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR))) { + init_list1(svl, ecgetstr(state, EC_DUPTOK, &htok)); + vl = &svl; + } else { + vl = ecgetlist(state, WC_ASSIGN_NUM(ac), EC_DUPTOK, &htok); + if (errflag) { + state->pc = opc; + return; + } + } + + if (vl && htok) { + int prefork_ret = 0; + prefork(vl, (isstr ? (PREFORK_SINGLE|PREFORK_ASSIGN) : + PREFORK_ASSIGN), &prefork_ret); + if (errflag) { + state->pc = opc; + return; + } + if (prefork_ret & PREFORK_KEY_VALUE) + myflags |= ASSPM_KEY_VALUE; + if (!isstr || (isset(GLOBASSIGN) && isstr && + haswilds((char *)getdata(firstnode(vl))))) { + globlist(vl, prefork_ret); + /* Unset the parameter to force it to be recreated + * as either scalar or array depending on how many + * matches were found for the glob. + */ + if (isset(GLOBASSIGN) && isstr) + unsetparam(name); + if (errflag) { + state->pc = opc; + return; + } + } + } + if (isstr && (empty(vl) || !nextnode(firstnode(vl)))) { + Param pm; + char *val; + int allexp; + + if (empty(vl)) + val = ztrdup(""); + else { + untokenize(peekfirst(vl)); + val = ztrdup(ugetnode(vl)); + } + if (xtr) { + quotedzputs(val, xtrerr); + fputc(' ', xtrerr); + } + if ((addflags & ADDVAR_EXPORT) && !strchr(name, '[')) { + if ((addflags & ADDVAR_RESTRICT) && isset(RESTRICTED) && + (pm = (Param) paramtab->removenode(paramtab, name)) && + (pm->node.flags & PM_RESTRICTED)) { + zerr("%s: restricted", pm->node.nam); + zsfree(val); + state->pc = opc; + return; + } + if (strcmp(name, "STTY") == 0) { + zsfree(STTYval); + STTYval = ztrdup(val); + } + allexp = opts[ALLEXPORT]; + opts[ALLEXPORT] = 1; + if (isset(KSHARRAYS)) + unsetparam(name); + pm = assignsparam(name, val, myflags); + opts[ALLEXPORT] = allexp; + } else + pm = assignsparam(name, val, myflags); + if (errflag) { + state->pc = opc; + return; + } + continue; + } + if (vl) { + ptr = arr = (char **) zalloc(sizeof(char *) * + (countlinknodes(vl) + 1)); + + while (nonempty(vl)) + *ptr++ = ztrdup((char *) ugetnode(vl)); + } else + ptr = arr = (char **) zalloc(sizeof(char *)); + + *ptr = NULL; + if (xtr) { + fprintf(xtrerr, "( "); + for (ptr = arr; *ptr; ptr++) { + quotedzputs(*ptr, xtrerr); + fputc(' ', xtrerr); + } + fprintf(xtrerr, ") "); + } + assignaparam(name, arr, myflags); + if (errflag) { + state->pc = opc; + return; + } + } + state->pc = opc; +} + +/**/ +void +setunderscore(char *str) +{ + queue_signals(); + if (str && *str) { + int l = strlen(str) + 1, nl = (l + 31) & ~31; + + if (nl > underscorelen || (underscorelen - nl) > 64) { + zfree(zunderscore, underscorelen); + zunderscore = (char *) zalloc(underscorelen = nl); + } + strcpy(zunderscore, str); + underscoreused = l; + } else { + if (underscorelen > 128) { + zfree(zunderscore, underscorelen); + zunderscore = (char *) zalloc(underscorelen = 32); + } + *zunderscore = '\0'; + underscoreused = 1; + } + unqueue_signals(); +} + +/* These describe the type of expansions that need to be done on the words + * used in the thing we are about to execute. They are set in execcmd() and + * used in execsubst() which might be called from one of the functions + * called from execcmd() (like execfor() and so on). */ + +static int esprefork, esglob = 1; + +/**/ +void +execsubst(LinkList strs) +{ + if (strs) { + prefork(strs, esprefork, NULL); + if (esglob && !errflag) { + LinkList ostrs = strs; + globlist(strs, 0); + strs = ostrs; + } + } +} + +/* + * Check if a builtin requires an autoload and if so + * deal with it. This may return NULL. + */ + +/**/ +static HashNode +resolvebuiltin(const char *cmdarg, HashNode hn) +{ + if (!((Builtin) hn)->handlerfunc) { + char *modname = dupstring(((Builtin) hn)->optstr); + /* + * Ensure the module is loaded and the + * feature corresponding to the builtin + * is enabled. + */ + (void)ensurefeature(modname, "b:", + (hn->flags & BINF_AUTOALL) ? NULL : + hn->nam); + hn = builtintab->getnode(builtintab, cmdarg); + if (!hn) { + lastval = 1; + zerr("autoloading module %s failed to define builtin: %s", + modname, cmdarg); + return NULL; + } + } + return hn; +} + +/* + * We are about to execute a command at the lowest level of the + * hierarchy. Analyse the parameters from the wordcode. + */ + +/**/ +static void +execcmd_analyse(Estate state, Execcmd_params eparams) +{ + wordcode code; + int i; + + eparams->beg = state->pc; + eparams->redir = + (wc_code(*state->pc) == WC_REDIR ? ecgetredirs(state) : NULL); + if (wc_code(*state->pc) == WC_ASSIGN) { + cmdoutval = 0; + eparams->varspc = state->pc; + while (wc_code((code = *state->pc)) == WC_ASSIGN) + state->pc += (WC_ASSIGN_TYPE(code) == WC_ASSIGN_SCALAR ? + 3 : WC_ASSIGN_NUM(code) + 2); + } else + eparams->varspc = NULL; + + code = *state->pc++; + + eparams->type = wc_code(code); + eparams->postassigns = 0; + + /* It would be nice if we could use EC_DUPTOK instead of EC_DUP here. + * But for that we would need to check/change all builtins so that + * they don't modify their argument strings. */ + switch (eparams->type) { + case WC_SIMPLE: + eparams->args = ecgetlist(state, WC_SIMPLE_ARGC(code), EC_DUP, + &eparams->htok); + eparams->assignspc = NULL; + break; + + case WC_TYPESET: + eparams->args = ecgetlist(state, WC_TYPESET_ARGC(code), EC_DUP, + &eparams->htok); + eparams->postassigns = *state->pc++; + eparams->assignspc = state->pc; + for (i = 0; i < eparams->postassigns; i++) { + code = *state->pc; + DPUTS(wc_code(code) != WC_ASSIGN, + "BUG: miscounted typeset assignments"); + state->pc += (WC_ASSIGN_TYPE(code) == WC_ASSIGN_SCALAR ? + 3 : WC_ASSIGN_NUM(code) + 2); + } + break; + + default: + eparams->args = NULL; + eparams->assignspc = NULL; + eparams->htok = 0; + break; + } +} + +/* + * Transfer the first node of args to preargs, performing + * prefork expansion on the way if necessary. + */ +static void execcmd_getargs(LinkList preargs, LinkList args, int expand) +{ + if (!firstnode(args)) { + return; + } else if (expand) { + local_list0(svl); + init_list0(svl); + /* not init_list1, as we need real nodes */ + addlinknode(&svl, uremnode(args, firstnode(args))); + /* Analysing commands, so vanilla options to prefork */ + prefork(&svl, 0, NULL); + joinlists(preargs, &svl); + } else { + addlinknode(preargs, uremnode(args, firstnode(args))); + } +} + +/**/ +static int +execcmd_fork(Estate state, int how, int type, Wordcode varspc, + LinkList *filelistp, char *text, int oautocont, + int close_if_forked) +{ + pid_t pid; + int synch[2], flags; + char dummy; + struct timeval bgtime; + + child_block(); + + if (pipe(synch) < 0) { + zerr("pipe failed: %e", errno); + return -1; + } else if ((pid = zfork(&bgtime)) == -1) { + close(synch[0]); + close(synch[1]); + lastval = 1; + errflag |= ERRFLAG_ERROR; + return -1; + } + if (pid) { + close(synch[1]); + read_loop(synch[0], &dummy, 1); + close(synch[0]); + if (how & Z_ASYNC) { + lastpid = (zlong) pid; + } else if (!jobtab[thisjob].stty_in_env && varspc) { + /* search for STTY=... */ + Wordcode p = varspc; + wordcode ac; + + while (wc_code(ac = *p) == WC_ASSIGN) { + if (!strcmp(ecrawstr(state->prog, p + 1, NULL), "STTY")) { + jobtab[thisjob].stty_in_env = 1; + break; + } + p += (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR ? + 3 : WC_ASSIGN_NUM(ac) + 2); + } + } + addproc(pid, text, 0, &bgtime); + if (oautocont >= 0) + opts[AUTOCONTINUE] = oautocont; + pipecleanfilelist(jobtab[thisjob].filelist, 1); + return pid; + } + + /* pid == 0 */ + close(synch[0]); + flags = ((how & Z_ASYNC) ? ESUB_ASYNC : 0) | ESUB_PGRP; + if ((type != WC_SUBSH) && !(how & Z_ASYNC)) + flags |= ESUB_KEEPTRAP; + if (type == WC_SUBSH && !(how & Z_ASYNC)) + flags |= ESUB_JOB_CONTROL; + *filelistp = jobtab[thisjob].filelist; + entersubsh(flags); + close(synch[1]); + zclose(close_if_forked); + + if (sigtrapped[SIGINT] & ZSIG_IGNORED) + holdintr(); + /* + * EXIT traps shouldn't be called even if we forked to run + * shell code as this isn't the main shell. + */ + sigtrapped[SIGEXIT] = 0; +#ifdef HAVE_NICE + /* Check if we should run background jobs at a lower priority. */ + if ((how & Z_ASYNC) && isset(BGNICE)) + if (nice(5) < 0) + zwarn("nice(5) failed: %e", errno); +#endif /* HAVE_NICE */ + + return 0; +} + +/* + * Execute a command at the lowest level of the hierarchy. + */ + +/**/ +static void +execcmd_exec(Estate state, Execcmd_params eparams, + int input, int output, int how, int last1, int close_if_forked) +{ + HashNode hn = NULL; + LinkList filelist = NULL; + LinkNode node; + Redir fn; + struct multio *mfds[10]; + char *text; + int save[10]; + int fil, dfil, is_cursh, do_exec = 0, redir_err = 0, i; + int nullexec = 0, magic_assign = 0, forked = 0, old_lastval; + int is_shfunc = 0, is_builtin = 0, is_exec = 0, use_defpath = 0; + /* Various flags to the command. */ + int cflags = 0, orig_cflags = 0, checked = 0, oautocont = -1; + FILE *oxtrerr = xtrerr, *newxtrerr = NULL; + /* + * Retrieve parameters for quick reference (they are unique + * to us so we can modify the structure if we want). + */ + LinkList args = eparams->args; + LinkList redir = eparams->redir; + Wordcode varspc = eparams->varspc; + int type = eparams->type; + /* + * preargs comes from expanding the head of the args list + * in order to check for prefix commands. + */ + LinkList preargs; + + doneps4 = 0; + + /* + * If assignment but no command get the status from variable + * assignment. + */ + old_lastval = lastval; + if (!args && varspc) + lastval = errflag ? errflag : cmdoutval; + /* + * If there are arguments, we should reset the status for the + * command before execution---unless we are using the result of a + * command substitution, which will be indicated by setting + * use_cmdoutval to 1. We haven't kicked those off yet, so + * there's no race. + */ + use_cmdoutval = !args; + + for (i = 0; i < 10; i++) { + save[i] = -2; + mfds[i] = NULL; + } + + /* If the command begins with `%', then assume it is a * + * reference to a job in the job table. */ + if ((type == WC_SIMPLE || type == WC_TYPESET) && args && nonempty(args) && + *(char *)peekfirst(args) == '%') { + if (how & Z_DISOWN) { + oautocont = opts[AUTOCONTINUE]; + opts[AUTOCONTINUE] = 1; + } + pushnode(args, dupstring((how & Z_DISOWN) + ? "disown" : (how & Z_ASYNC) ? "bg" : "fg")); + how = Z_SYNC; + } + + /* If AUTORESUME is set, the command is SIMPLE, and doesn't have * + * any redirections, then check if it matches as a prefix of a * + * job currently in the job table. If it does, then we treat it * + * as a command to resume this job. */ + if (isset(AUTORESUME) && type == WC_SIMPLE && (how & Z_SYNC) && + args && nonempty(args) && (!redir || empty(redir)) && !input && + !nextnode(firstnode(args))) { + if (unset(NOTIFY)) + scanjobs(); + if (findjobnam(peekfirst(args)) != -1) + pushnode(args, dupstring("fg")); + } + + if ((how & Z_ASYNC) || output) { + /* + * If running in the background, or not the last command in a + * pipeline, we don't need any of the rest of this function to + * affect the state in the main shell, so fork immediately. + * + * In other cases we may need to process the command line + * a bit further before we make the decision. + */ + text = getjobtext(state->prog, eparams->beg); + switch (execcmd_fork(state, how, type, varspc, &filelist, + text, oautocont, close_if_forked)) { + case -1: + goto fatal; + case 0: + break; + default: + return; + } + last1 = forked = 1; + } else + text = NULL; + + /* Check if it's a builtin needing automatic MAGIC_EQUALS_SUBST * + * handling. Things like typeset need this. We can't detect the * + * command if it contains some tokens (e.g. x=ex; ${x}port), so this * + * only works in simple cases. has_token() is called to make sure * + * this really is a simple case. */ + if ((type == WC_SIMPLE || type == WC_TYPESET) && args) { + /* + * preargs contains args that have been expanded by prefork. + * Running execcmd_getargs() causes any argument available + * in args to be exanded where necessary and transferred to + * preargs. We call execcmd_getargs() every time we need to + * analyse an argument not available in preargs, though there is + * no guarantee a further argument will be available. + */ + preargs = newlinklist(); + execcmd_getargs(preargs, args, eparams->htok); + while (nonempty(preargs)) { + char *cmdarg = (char *) peekfirst(preargs); + checked = !has_token(cmdarg); + if (!checked) + break; + if (type == WC_TYPESET && + (hn = builtintab->getnode2(builtintab, cmdarg))) { + /* + * If reserved word for typeset command found (and so + * enabled), use regardless of whether builtin is + * enabled as we share the implementation. + * + * Reserved words take precedence over shell functions. + */ + checked = 1; + } else if (isset(POSIXBUILTINS) && (cflags & BINF_EXEC)) { + /* + * POSIX doesn't allow "exec" to operate on builtins + * or shell functions. + */ + break; + } else { + if (!(cflags & (BINF_BUILTIN | BINF_COMMAND)) && + (hn = shfunctab->getnode(shfunctab, cmdarg))) { + is_shfunc = 1; + break; + } + if (!(hn = builtintab->getnode(builtintab, cmdarg))) { + checked = !(cflags & BINF_BUILTIN); + break; + } + } + orig_cflags |= cflags; + cflags &= ~BINF_BUILTIN & ~BINF_COMMAND; + cflags |= hn->flags; + if (!(hn->flags & BINF_PREFIX)) { + is_builtin = 1; + + /* autoload the builtin if necessary */ + if (!(hn = resolvebuiltin(cmdarg, hn))) { + if (forked) + _exit(lastval); + return; + } + if (type != WC_TYPESET) + magic_assign = (hn->flags & BINF_MAGICEQUALS); + break; + } + checked = 0; + /* + * We usually don't need the argument containing the + * precommand modifier itself. Exception: when "command" + * will implemented by a call to "whence", in which case + * we'll simply re-insert the argument. + */ + uremnode(preargs, firstnode(preargs)); + if (!firstnode(preargs)) { + execcmd_getargs(preargs, args, eparams->htok); + if (!firstnode(preargs)) + break; + } + if ((cflags & BINF_COMMAND)) { + /* + * Check for options to "command". + * If just -p, this is handled here: use the default + * path to execute. + * If -v or -V, possibly with -p, dispatch to bin_whence + * but with flag to indicate special handling of -p. + * Otherwise, just leave marked as BINF_COMMAND + * modifier with no additional action. + */ + LinkNode argnode, oldnode, pnode = NULL; + char *argdata, *cmdopt; + int has_p = 0, has_vV = 0, has_other = 0; + argnode = firstnode(preargs); + argdata = (char *) getdata(argnode); + while (IS_DASH(*argdata)) { + /* Just to be definite, stop on single "-", too, */ + if (!argdata[1] || + (IS_DASH(argdata[1]) && !argdata[2])) + break; + for (cmdopt = argdata+1; *cmdopt; cmdopt++) { + switch (*cmdopt) { + case 'p': + /* + * If we've got this multiple times (command + * -p -p) we'll treat the second -p as a + * command because we only remove one below. + * Don't think that's a big issue, and it's + * also traditional behaviour. + */ + has_p = 1; + pnode = argnode; + break; + case 'v': + case 'V': + has_vV = 1; + break; + default: + has_other = 1; + break; + } + } + if (has_other) { + /* Don't know how to handle this, so don't */ + has_p = has_vV = 0; + break; + } + + oldnode = argnode; + argnode = nextnode(argnode); + if (!argnode) { + execcmd_getargs(preargs, args, eparams->htok); + if (!(argnode = nextnode(oldnode))) + break; + } + argdata = (char *) getdata(argnode); + } + if (has_vV) { + /* + * Leave everything alone, dispatch to whence. + * We need to put the name back in the list. + */ + pushnode(preargs, "command"); + hn = &commandbn.node; + is_builtin = 1; + break; + } else if (has_p) { + /* Use default path */ + use_defpath = 1; + /* + * We don't need this node as we're not treating + * "command" as a builtin this time. + */ + if (pnode) + uremnode(preargs, pnode); + } + /* + * Else just any trailing + * end-of-options marker. This can only occur + * if we just had -p or something including more + * than just -p, -v and -V, in which case we behave + * as if this is command [non-option-stuff]. This + * isn't a good place for standard option handling. + */ + if (IS_DASH(argdata[0]) && IS_DASH(argdata[1]) && !argdata[2]) + uremnode(preargs, argnode); + } else if (cflags & BINF_EXEC) { + /* + * Check for compatibility options to exec builtin. + * It would be nice to do these more generically, + * but currently we don't have a mechanism for + * precommand modifiers. + */ + LinkNode argnode = firstnode(preargs), oldnode; + char *argdata = (char *) getdata(argnode); + char *cmdopt, *exec_argv0 = NULL; + /* + * Careful here: we want to make sure a final dash + * is passed through in order that it still behaves + * as a precommand modifier (zsh equivalent of -l). + * It has to be last, but I think that's OK since + * people aren't likely to mix the option style + * with the zsh style. + */ + while (argdata && IS_DASH(*argdata) && strlen(argdata) >= 2) { + oldnode = argnode; + argnode = nextnode(oldnode); + if (!argnode) { + execcmd_getargs(preargs, args, eparams->htok); + argnode = nextnode(oldnode); + } + if (!argnode) { + zerr("exec requires a command to execute"); + lastval = 1; + errflag |= ERRFLAG_ERROR; + goto done; + } + uremnode(preargs, oldnode); + if (IS_DASH(argdata[0]) && IS_DASH(argdata[1]) && !argdata[2]) + break; + for (cmdopt = &argdata[1]; *cmdopt; ++cmdopt) { + switch (*cmdopt) { + case 'a': + /* argument is ARGV0 string */ + if (cmdopt[1]) { + exec_argv0 = cmdopt+1; + /* position on last non-NULL character */ + cmdopt += strlen(cmdopt+1); + } else { + if (!argnode) { + zerr("exec requires a command to execute"); + lastval = 1; + errflag |= ERRFLAG_ERROR; + goto done; + } + if (!nextnode(argnode)) + execcmd_getargs(preargs, args, + eparams->htok); + if (!nextnode(argnode)) { + zerr("exec flag -a requires a parameter"); + lastval = 1; + errflag |= ERRFLAG_ERROR; + goto done; + } + exec_argv0 = (char *) getdata(argnode); + oldnode = argnode; + argnode = nextnode(argnode); + uremnode(args, oldnode); + } + break; + case 'c': + cflags |= BINF_CLEARENV; + break; + case 'l': + cflags |= BINF_DASH; + break; + default: + zerr("unknown exec flag -%c", *cmdopt); + lastval = 1; + errflag |= ERRFLAG_ERROR; + if (forked) + _exit(lastval); + return; + } + } + if (!argnode) + break; + argdata = (char *) getdata(argnode); + } + if (exec_argv0) { + char *str, *s; + exec_argv0 = dupstring(exec_argv0); + remnulargs(exec_argv0); + untokenize(exec_argv0); + size_t sz = strlen(exec_argv0); + str = s = zalloc(5 + 1 + sz + 1); + strcpy(s, "ARGV0="); + s+=6; + strcpy(s, exec_argv0); + zputenv(str); + } + } + hn = NULL; + if ((cflags & BINF_COMMAND) && unset(POSIXBUILTINS)) + break; + if (!nonempty(preargs)) + execcmd_getargs(preargs, args, eparams->htok); + } + } else + preargs = NULL; + + /* if we get this far, it is OK to pay attention to lastval again */ + if (noerrexit & NOERREXIT_UNTIL_EXEC) + noerrexit = 0; + + /* Do prefork substitutions. + * + * Decide if we need "magic" handling of ~'s etc. in + * assignment-like arguments. + * - If magic_assign is set, we are using a builtin of the + * tyepset family, but did not recognise this as a keyword, + * so need guess-o-matic behaviour. + * - Otherwise, if we did recognise the keyword, we never need + * guess-o-matic behaviour as the argument was properly parsed + * as such. + * - Otherwise, use the behaviour specified by the MAGIC_EQUAL_SUBST + * option. + */ + esprefork = (magic_assign || + (isset(MAGICEQUALSUBST) && type != WC_TYPESET)) ? + PREFORK_TYPESET : 0; + + if (args) { + if (eparams->htok) + prefork(args, esprefork, NULL); + if (preargs) + args = joinlists(preargs, args); + } + + if (type == WC_SIMPLE || type == WC_TYPESET) { + int unglobbed = 0; + + for (;;) { + char *cmdarg; + + if (!(cflags & BINF_NOGLOB)) + while (!checked && !errflag && args && nonempty(args) && + has_token((char *) peekfirst(args))) + zglob(args, firstnode(args), 0); + else if (!unglobbed) { + for (node = firstnode(args); node; incnode(node)) + untokenize((char *) getdata(node)); + unglobbed = 1; + } + + /* Current shell should not fork unless the * + * exec occurs at the end of a pipeline. */ + if ((cflags & BINF_EXEC) && last1) + do_exec = 1; + + /* Empty command */ + if (!args || empty(args)) { + if (redir && nonempty(redir)) { + if (do_exec) { + /* Was this "exec < foobar"? */ + nullexec = 1; + break; + } else if (varspc) { + nullexec = 2; + break; + } else if (!nullcmd || !*nullcmd || opts[CSHNULLCMD] || + (cflags & BINF_PREFIX)) { + zerr("redirection with no command"); + lastval = 1; + errflag |= ERRFLAG_ERROR; + if (forked) + _exit(lastval); + return; + } else if (!nullcmd || !*nullcmd || opts[SHNULLCMD]) { + if (!args) + args = newlinklist(); + addlinknode(args, dupstring(":")); + } else if (readnullcmd && *readnullcmd && + ((Redir) peekfirst(redir))->type == REDIR_READ && + !nextnode(firstnode(redir))) { + if (!args) + args = newlinklist(); + addlinknode(args, dupstring(readnullcmd)); + } else { + if (!args) + args = newlinklist(); + addlinknode(args, dupstring(nullcmd)); + } + } else if ((cflags & BINF_PREFIX) && (cflags & BINF_COMMAND)) { + lastval = 0; + if (forked) + _exit(lastval); + return; + } else { + /* + * No arguments. Reset the status if there were + * arguments before and no command substitution + * has provided a status. + */ + if (badcshglob == 1) { + zerr("no match"); + lastval = 1; + if (forked) + _exit(lastval); + return; + } + cmdoutval = use_cmdoutval ? lastval : 0; + if (varspc) { + /* Make sure $? is still correct for assignment */ + lastval = old_lastval; + addvars(state, varspc, 0); + } + if (errflag) + lastval = 1; + else + lastval = cmdoutval; + if (isset(XTRACE)) { + fputc('\n', xtrerr); + fflush(xtrerr); + } + if (forked) + _exit(lastval); + return; + } + } else if (isset(RESTRICTED) && (cflags & BINF_EXEC) && do_exec) { + zerrnam("exec", "%s: restricted", + (char *) getdata(firstnode(args))); + lastval = 1; + if (forked) + _exit(lastval); + return; + } + + /* + * Quit looking for a command if: + * - there was an error; or + * - we checked the simple cases needing MAGIC_EQUAL_SUBST; or + * - we know we already found a builtin (because either: + * - we loaded a builtin from a module, or + * - we have determined there are options which would + * require us to use the "command" builtin); or + * - we aren't using POSIX and so BINF_COMMAND indicates a zsh + * precommand modifier is being used in place of the + * builtin + * - we are using POSIX and this is an EXEC, so we can't + * execute a builtin or function. + */ + if (errflag || checked || is_builtin || + (isset(POSIXBUILTINS) ? + (cflags & BINF_EXEC) : (cflags & BINF_COMMAND))) + break; + + cmdarg = (char *) peekfirst(args); + if (!(cflags & (BINF_BUILTIN | BINF_COMMAND)) && + (hn = shfunctab->getnode(shfunctab, cmdarg))) { + is_shfunc = 1; + break; + } + if (!(hn = builtintab->getnode(builtintab, cmdarg))) { + if (cflags & BINF_BUILTIN) { + zwarn("no such builtin: %s", cmdarg); + lastval = 1; + if (oautocont >= 0) + opts[AUTOCONTINUE] = oautocont; + if (forked) + _exit(lastval); + return; + } + break; + } + if (!(hn->flags & BINF_PREFIX)) { + is_builtin = 1; + + /* autoload the builtin if necessary */ + if (!(hn = resolvebuiltin(cmdarg, hn))) { + if (forked) + _exit(lastval); + return; + } + break; + } + cflags &= ~BINF_BUILTIN & ~BINF_COMMAND; + cflags |= hn->flags; + uremnode(args, firstnode(args)); + hn = NULL; + } + } + + if (errflag) { + if (!lastval) + lastval = 1; + if (oautocont >= 0) + opts[AUTOCONTINUE] = oautocont; + if (forked) + _exit(lastval); + return; + } + + /* Get the text associated with this command. */ + if (!text && + (!sfcontext && (jobbing || (how & Z_TIMED)))) + text = getjobtext(state->prog, eparams->beg); + + /* + * Set up special parameter $_ + * For execfuncdef we may need to take account of an + * anonymous function with arguments. + */ + if (type != WC_FUNCDEF) + setunderscore((args && nonempty(args)) ? + ((char *) getdata(lastnode(args))) : ""); + + /* Warn about "rm *" */ + if (type == WC_SIMPLE && interact && unset(RMSTARSILENT) && + isset(SHINSTDIN) && args && nonempty(args) && + nextnode(firstnode(args)) && !strcmp(peekfirst(args), "rm")) { + LinkNode node, next; + + for (node = nextnode(firstnode(args)); node && !errflag; node = next) { + char *s = (char *) getdata(node); + int l = strlen(s); + + next = nextnode(node); + if (s[0] == Star && !s[1]) { + if (!checkrmall(pwd)) { + errflag |= ERRFLAG_ERROR; + break; + } + } else if (l >= 2 && s[l - 2] == '/' && s[l - 1] == Star) { + char t = s[l - 2]; + int rmall; + + s[l - 2] = 0; + rmall = checkrmall(s); + s[l - 2] = t; + + if (!rmall) { + errflag |= ERRFLAG_ERROR; + break; + } + } + } + } + + if (type == WC_FUNCDEF) { + /* + * The first word of a function definition is a list of + * names. If this is empty, we're doing an anonymous function: + * in that case redirections are handled normally. + * If not, it's a function definition: then we don't do + * redirections here but pass in the list of redirections to + * be stored for recall with the function. + */ + if (*state->pc != 0) { + /* Nonymous, don't do redirections here */ + redir = NULL; + } + } else if (is_shfunc || type == WC_AUTOFN) { + Shfunc shf; + if (is_shfunc) + shf = (Shfunc)hn; + else { + shf = loadautofn(state->prog->shf, 1, 0, 0); + if (shf) + state->prog->shf = shf; + else { + /* + * This doesn't set errflag, so just return now. + */ + lastval = 1; + if (oautocont >= 0) + opts[AUTOCONTINUE] = oautocont; + if (forked) + _exit(lastval); + return; + } + } + /* + * A function definition may have a list of additional + * redirections to apply, so retrieve it. + */ + if (shf->redir) { + struct estate s; + LinkList redir2; + + s.prog = shf->redir; + s.pc = shf->redir->prog; + s.strs = shf->redir->strs; + redir2 = ecgetredirs(&s); + if (!redir) + redir = redir2; + else { + while (nonempty(redir2)) + addlinknode(redir, ugetnode(redir2)); + } + } + } + + if (errflag) { + lastval = 1; + if (oautocont >= 0) + opts[AUTOCONTINUE] = oautocont; + if (forked) + _exit(lastval); + return; + } + + if ((type == WC_SIMPLE || type == WC_TYPESET) && !nullexec) { + char *s; + char trycd = (isset(AUTOCD) && isset(SHINSTDIN) && + (!redir || empty(redir)) && args && !empty(args) && + !nextnode(firstnode(args)) && *(char *)peekfirst(args)); + + DPUTS((!args || empty(args)), "BUG: empty(args) in exec.c"); + if (!hn) { + /* Resolve external commands */ + char *cmdarg = (char *) peekfirst(args); + char **checkpath = pathchecked; + int dohashcmd = isset(HASHCMDS); + + hn = cmdnamtab->getnode(cmdnamtab, cmdarg); + if (hn && trycd && !isreallycom((Cmdnam)hn)) { + if (!(((Cmdnam)hn)->node.flags & HASHED)) { + checkpath = path; + dohashcmd = 1; + } + cmdnamtab->removenode(cmdnamtab, cmdarg); + cmdnamtab->freenode(hn); + hn = NULL; + } + if (!hn && dohashcmd && strcmp(cmdarg, "..")) { + for (s = cmdarg; *s && *s != '/'; s++); + if (!*s) + hn = (HashNode) hashcmd(cmdarg, checkpath); + } + } + + /* If no command found yet, see if it * + * is a directory we should AUTOCD to. */ + if (!hn && trycd && (s = cancd(peekfirst(args)))) { + peekfirst(args) = (void *) s; + pushnode(args, dupstring("--")); + pushnode(args, dupstring("cd")); + if ((hn = builtintab->getnode(builtintab, "cd"))) + is_builtin = 1; + } + } + + /* This is nonzero if the command is a current shell procedure? */ + is_cursh = (is_builtin || is_shfunc || nullexec || type >= WC_CURSH); + + /************************************************************************** + * Do we need to fork? We need to fork if: * + * 1) The command is supposed to run in the background. This * + * case is now handled above (forked = 1 here). (or) * + * 2) There is no `exec' flag, and either: * + * a) This is a builtin or shell function with output piped somewhere. * + * b) This is an external command and we can't do a `fake exec'. * + * * + * A `fake exec' is possible if we have all the following conditions: * + * 1) last1 flag is 1. This indicates that the current shell will not * + * be needed after the current command. This is typically the case * + * when the command is the last stage in a subshell, or is the * + * last command after the option `-c'. * + * 2) We don't have any traps set. * + * 3) We don't have any files to delete. * + * * + * The condition above for a `fake exec' will also work for a current * + * shell command such as a builtin, but doesn't really buy us anything * + * (doesn't save us a process), since it is already running in the * + * current shell. * + **************************************************************************/ + + if (!forked) { + if (!do_exec && + (((is_builtin || is_shfunc) && output) || + (!is_cursh && (last1 != 1 || nsigtrapped || havefiles() || + fdtable_flocks)))) { + switch (execcmd_fork(state, how, type, varspc, &filelist, + text, oautocont, close_if_forked)) { + case -1: + goto fatal; + case 0: + break; + default: + return; + } + forked = 1; + } else if (is_cursh) { + /* This is a current shell procedure that didn't need to fork. * + * This includes current shell procedures that are being exec'ed, * + * as well as null execs. */ + jobtab[thisjob].stat |= STAT_CURSH; + if (!jobtab[thisjob].procs) + jobtab[thisjob].stat |= STAT_NOPRINT; + if (is_builtin) + jobtab[thisjob].stat |= STAT_BUILTIN; + } else { + /* This is an exec (real or fake) for an external command. * + * Note that any form of exec means that the subshell is fake * + * (but we may be in a subshell already). */ + is_exec = 1; + /* + * If we are in a subshell environment anyway, say we're forked, + * even if we're actually not forked because we know the + * subshell is exiting. This ensures SHLVL reflects the current + * shell, and also optimises out any save/restore we'd need to + * do if we were returning to the main shell. + */ + if (type == WC_SUBSH) + forked = 1; + } + } + + if ((esglob = !(cflags & BINF_NOGLOB)) && args && eparams->htok) { + LinkList oargs = args; + globlist(args, 0); + args = oargs; + } + if (errflag) { + lastval = 1; + goto err; + } + + /* Make a copy of stderr for xtrace output before redirecting */ + fflush(xtrerr); + if (isset(XTRACE) && xtrerr == stderr && + (type < WC_SUBSH || type == WC_TIMED)) { + if ((newxtrerr = fdopen(movefd(dup(fileno(stderr))), "w"))) { + xtrerr = newxtrerr; + fdtable[fileno(xtrerr)] = FDT_XTRACE; + } + } + + /* Add pipeline input/output to mnodes */ + if (input) + addfd(forked, save, mfds, 0, input, 0, NULL); + if (output) + addfd(forked, save, mfds, 1, output, 1, NULL); + + /* Do process substitutions */ + if (redir) + spawnpipes(redir, nullexec); + + /* Do io redirections */ + while (redir && nonempty(redir)) { + fn = (Redir) ugetnode(redir); + + DPUTS(fn->type == REDIR_HEREDOC || fn->type == REDIR_HEREDOCDASH, + "BUG: unexpanded here document"); + if (fn->type == REDIR_INPIPE) { + if (!checkclobberparam(fn) || fn->fd2 == -1) { + if (fn->fd2 != -1) + zclose(fn->fd2); + closemnodes(mfds); + fixfds(save); + execerr(); + } + addfd(forked, save, mfds, fn->fd1, fn->fd2, 0, fn->varid); + } else if (fn->type == REDIR_OUTPIPE) { + if (!checkclobberparam(fn) || fn->fd2 == -1) { + if (fn->fd2 != -1) + zclose(fn->fd2); + closemnodes(mfds); + fixfds(save); + execerr(); + } + addfd(forked, save, mfds, fn->fd1, fn->fd2, 1, fn->varid); + } else { + int closed; + if (fn->type != REDIR_HERESTR && xpandredir(fn, redir)) + continue; + if (errflag) { + closemnodes(mfds); + fixfds(save); + execerr(); + } + if (isset(RESTRICTED) && IS_WRITE_FILE(fn->type)) { + zwarn("writing redirection not allowed in restricted mode"); + execerr(); + } + if (unset(EXECOPT)) + continue; + switch(fn->type) { + case REDIR_HERESTR: + if (!checkclobberparam(fn)) + fil = -1; + else + fil = getherestr(fn); + if (fil == -1) { + if (errno && errno != EINTR) + zwarn("can't create temp file for here document: %e", + errno); + closemnodes(mfds); + fixfds(save); + execerr(); + } + addfd(forked, save, mfds, fn->fd1, fil, 0, fn->varid); + break; + case REDIR_READ: + case REDIR_READWRITE: + if (!checkclobberparam(fn)) + fil = -1; + else if (fn->type == REDIR_READ) + fil = open(unmeta(fn->name), O_RDONLY | O_NOCTTY); + else + fil = open(unmeta(fn->name), + O_RDWR | O_CREAT | O_NOCTTY, 0666); + if (fil == -1) { + closemnodes(mfds); + fixfds(save); + if (errno != EINTR) + zwarn("%e: %s", errno, fn->name); + execerr(); + } + addfd(forked, save, mfds, fn->fd1, fil, 0, fn->varid); + /* If this is 'exec < file', read from stdin, * + * not terminal, unless `file' is a terminal. */ + if (nullexec == 1 && fn->fd1 == 0 && + isset(SHINSTDIN) && interact && !zleactive) + init_io(NULL); + break; + case REDIR_CLOSE: + if (fn->varid) { + char *s = fn->varid, *t; + struct value vbuf; + Value v; + int bad = 0; + + if (!(v = getvalue(&vbuf, &s, 0))) { + bad = 1; + } else if (v->pm->node.flags & PM_READONLY) { + bad = 2; + } else { + s = getstrvalue(v); + if (errflag) + bad = 1; + else { + fn->fd1 = zstrtol(s, &t, 0); + if (s == t) + bad = 1; + else if (*t) { + /* Check for base#number format */ + if (*t == '#' && *s != '0') + fn->fd1 = zstrtol(s = t+1, &t, fn->fd1); + if (s == t || *t) + bad = 1; + } + if (!bad && fn->fd1 <= max_zsh_fd) { + if (fn->fd1 >= 10 && + (fdtable[fn->fd1] & FDT_TYPE_MASK) == + FDT_INTERNAL) + bad = 3; + } + } + } + if (bad) { + const char *bad_msg[] = { + "parameter %s does not contain a file descriptor", + "can't close file descriptor from readonly parameter %s", + "file descriptor %d used by shell, not closed" + }; + if (bad > 2) + zwarn(bad_msg[bad-1], fn->fd1); + else + zwarn(bad_msg[bad-1], fn->varid); + execerr(); + } + } + /* + * Note we may attempt to close an fd beyond max_zsh_fd: + * OK as long as we never look in fdtable for it. + */ + closed = 0; + if (!forked && fn->fd1 < 10 && save[fn->fd1] == -2) { + save[fn->fd1] = movefd(fn->fd1); + if (save[fn->fd1] >= 0) { + /* + * The original fd is now closed, we don't need + * to do it below. + */ + closed = 1; + } + } + if (fn->fd1 < 10) + closemn(mfds, fn->fd1, REDIR_CLOSE); + /* + * Only report failures to close file descriptors + * if they're under user control as we don't know + * what the previous status of others was. + */ + if (!closed && zclose(fn->fd1) < 0 && fn->varid) { + zwarn("failed to close file descriptor %d: %e", + fn->fd1, errno); + } + break; + case REDIR_MERGEIN: + case REDIR_MERGEOUT: + if (fn->fd2 < 10) + closemn(mfds, fn->fd2, fn->type); + if (!checkclobberparam(fn)) + fil = -1; + else if (fn->fd2 > 9 && + /* + * If the requested fd is > max_zsh_fd, + * the shell doesn't know about it. + * Just assume the user knows what they're + * doing. + */ + (fn->fd2 <= max_zsh_fd && + ((fdtable[fn->fd2] != FDT_UNUSED && + fdtable[fn->fd2] != FDT_EXTERNAL) || + fn->fd2 == coprocin || + fn->fd2 == coprocout))) { + fil = -1; + errno = EBADF; + } else { + int fd = fn->fd2; + if(fd == -2) + fd = (fn->type == REDIR_MERGEOUT) ? coprocout : coprocin; + fil = movefd(dup(fd)); + } + if (fil == -1) { + char fdstr[DIGBUFSIZE]; + + closemnodes(mfds); + fixfds(save); + if (fn->fd2 != -2) + sprintf(fdstr, "%d", fn->fd2); + if (errno) + zwarn("%s: %e", fn->fd2 == -2 ? "coprocess" : fdstr, + errno); + execerr(); + } + addfd(forked, save, mfds, fn->fd1, fil, + fn->type == REDIR_MERGEOUT, fn->varid); + break; + default: + if (!checkclobberparam(fn)) + fil = -1; + else if (IS_APPEND_REDIR(fn->type)) + fil = open(unmeta(fn->name), + ((unset(CLOBBER) && unset(APPENDCREATE)) && + !IS_CLOBBER_REDIR(fn->type)) ? + O_WRONLY | O_APPEND | O_NOCTTY : + O_WRONLY | O_APPEND | O_CREAT | O_NOCTTY, 0666); + else + fil = clobber_open(fn); + if(fil != -1 && IS_ERROR_REDIR(fn->type)) + dfil = movefd(dup(fil)); + else + dfil = 0; + if (fil == -1 || dfil == -1) { + if(fil != -1) + close(fil); + closemnodes(mfds); + fixfds(save); + if (errno && errno != EINTR) + zwarn("%e: %s", errno, fn->name); + execerr(); + } + addfd(forked, save, mfds, fn->fd1, fil, 1, fn->varid); + if(IS_ERROR_REDIR(fn->type)) + addfd(forked, save, mfds, 2, dfil, 1, NULL); + break; + } + /* May be error in addfd due to setting parameter. */ + if (errflag) { + closemnodes(mfds); + fixfds(save); + execerr(); + } + } + } + + /* We are done with redirection. close the mnodes, * + * spawning tee/cat processes as necessary. */ + for (i = 0; i < 10; i++) + if (mfds[i] && mfds[i]->ct >= 2) + closemn(mfds, i, REDIR_CLOSE); + + if (nullexec) { + /* + * If nullexec is 2, we have variables to add with the redirections + * in place. If nullexec is 1, we may have variables but they + * need the standard restore logic. + */ + if (varspc) { + LinkList restorelist = 0, removelist = 0; + if (!isset(POSIXBUILTINS) && nullexec != 2) + save_params(state, varspc, &restorelist, &removelist); + addvars(state, varspc, 0); + if (restorelist) + restore_params(restorelist, removelist); + } + lastval = errflag ? errflag : cmdoutval; + if (nullexec == 1) { + /* + * If nullexec is 1 we specifically *don't* restore the original + * fd's before returning. + */ + for (i = 0; i < 10; i++) + if (save[i] != -2) + zclose(save[i]); + goto done; + } + if (isset(XTRACE)) { + fputc('\n', xtrerr); + fflush(xtrerr); + } + } else if (isset(EXECOPT) && !errflag) { + int q = queue_signal_level(); + /* + * We delay the entersubsh() to here when we are exec'ing + * the current shell (including a fake exec to run a builtin then + * exit) in case there is an error return. + */ + if (is_exec) { + int flags = ((how & Z_ASYNC) ? ESUB_ASYNC : 0) | + ESUB_PGRP | ESUB_FAKE; + if (type != WC_SUBSH) + flags |= ESUB_KEEPTRAP; + if ((do_exec || (type >= WC_CURSH && last1 == 1)) + && !forked) + flags |= ESUB_REVERTPGRP; + entersubsh(flags); + } + if (type == WC_FUNCDEF) { + Eprog redir_prog; + if (!redir && wc_code(*eparams->beg) == WC_REDIR) { + /* + * We're not using a redirection from the currently + * parsed environment, which is what we'd do for an + * anonymous function, but there are redirections we + * should store with the new function. + */ + struct estate s; + + s.prog = state->prog; + s.pc = eparams->beg; + s.strs = state->prog->strs; + + /* + * The copy uses the wordcode parsing area, so save and + * restore state. + */ + zcontext_save(); + redir_prog = eccopyredirs(&s); + zcontext_restore(); + } else + redir_prog = NULL; + + dont_queue_signals(); + lastval = execfuncdef(state, redir_prog); + restore_queue_signals(q); + } + else if (type >= WC_CURSH) { + if (last1 == 1) + do_exec = 1; + dont_queue_signals(); + if (type == WC_AUTOFN) { + /* + * We pre-loaded this to get any redirs. + * So we execuate a simplified function here. + */ + lastval = execautofn_basic(state, do_exec); + } else + lastval = (execfuncs[type - WC_CURSH])(state, do_exec); + restore_queue_signals(q); + } else if (is_builtin || is_shfunc) { + LinkList restorelist = 0, removelist = 0; + int do_save = 0; + /* builtin or shell function */ + + if (!forked) { + if (isset(POSIXBUILTINS)) { + /* + * If it's a function or special builtin --- save + * if it's got "command" in front. + * If it's a normal command --- save. + */ + if (is_shfunc || (hn->flags & (BINF_PSPECIAL|BINF_ASSIGN))) + do_save = (orig_cflags & BINF_COMMAND); + else + do_save = 1; + } else { + /* + * Save if it's got "command" in front or it's + * not a magic-equals assignment. + */ + if ((cflags & (BINF_COMMAND|BINF_ASSIGN)) || !magic_assign) + do_save = 1; + } + if (do_save && varspc) + save_params(state, varspc, &restorelist, &removelist); + } + if (varspc) { + /* Export this if the command is a shell function, + * but not if it's a builtin. + */ + int flags = 0; + if (is_shfunc) + flags |= ADDVAR_EXPORT; + if (restorelist) + flags |= ADDVAR_RESTORE; + + addvars(state, varspc, flags); + if (errflag) { + if (restorelist) + restore_params(restorelist, removelist); + lastval = 1; + fixfds(save); + goto done; + } + } + + if (is_shfunc) { + /* It's a shell function */ + pipecleanfilelist(filelist, 0); + execshfunc((Shfunc) hn, args); + } else { + /* It's a builtin */ + LinkList assigns = (LinkList)0; + int postassigns = eparams->postassigns; + if (forked) + closem(FDT_INTERNAL, 0); + if (postassigns) { + Wordcode opc = state->pc; + state->pc = eparams->assignspc; + assigns = newlinklist(); + while (postassigns--) { + int htok; + wordcode ac = *state->pc++; + char *name = ecgetstr(state, EC_DUPTOK, &htok); + Asgment asg; + local_list1(svl); + + DPUTS(wc_code(ac) != WC_ASSIGN, + "BUG: bad assignment list for typeset"); + if (htok) { + init_list1(svl, name); + if (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR && + WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC) { + char *data; + /* + * Special case: this is a name only, so + * it's not required to be a single + * expansion. Furthermore, for + * consistency with the builtin + * interface, it may expand into + * scalar assignments: + * ass=(one=two three=four) + * typeset a=b $ass + */ + /* Unused dummy value for name */ + (void)ecgetstr(state, EC_DUPTOK, &htok); + prefork(&svl, PREFORK_TYPESET, NULL); + if (errflag) { + state->pc = opc; + break; + } + globlist(&svl, 0); + if (errflag) { + state->pc = opc; + break; + } + while ((data = ugetnode(&svl))) { + char *ptr; + asg = (Asgment)zhalloc(sizeof(struct asgment)); + asg->flags = 0; + if ((ptr = strchr(data, '='))) { + *ptr++ = '\0'; + asg->name = data; + asg->value.scalar = ptr; + } else { + asg->name = data; + asg->value.scalar = NULL; + } + uaddlinknode(assigns, &asg->node); + } + continue; + } + prefork(&svl, PREFORK_SINGLE, NULL); + name = empty(&svl) ? "" : + (char *)getdata(firstnode(&svl)); + } + untokenize(name); + asg = (Asgment)zhalloc(sizeof(struct asgment)); + asg->name = name; + if (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR) { + char *val = ecgetstr(state, EC_DUPTOK, &htok); + asg->flags = 0; + if (WC_ASSIGN_TYPE2(ac) == WC_ASSIGN_INC) { + /* Fake assignment, no value */ + asg->value.scalar = NULL; + } else { + if (htok) { + init_list1(svl, val); + prefork(&svl, + PREFORK_SINGLE|PREFORK_ASSIGN, + NULL); + if (errflag) { + state->pc = opc; + break; + } + /* + * No globassign for typeset + * arguments, thank you + */ + val = empty(&svl) ? "" : + (char *)getdata(firstnode(&svl)); + } + untokenize(val); + asg->value.scalar = val; + } + } else { + asg->flags = ASG_ARRAY; + asg->value.array = + ecgetlist(state, WC_ASSIGN_NUM(ac), + EC_DUPTOK, &htok); + if (asg->value.array) + { + if (!errflag) { + int prefork_ret = 0; + prefork(asg->value.array, PREFORK_ASSIGN, + &prefork_ret); + if (errflag) { + state->pc = opc; + break; + } + if (prefork_ret & PREFORK_KEY_VALUE) + asg->flags |= ASG_KEY_VALUE; + globlist(asg->value.array, prefork_ret); + } + if (errflag) { + state->pc = opc; + break; + } + } + } + + uaddlinknode(assigns, &asg->node); + } + state->pc = opc; + } + dont_queue_signals(); + if (!errflag) { + int ret = execbuiltin(args, assigns, (Builtin) hn); + /* + * In case of interruption assume builtin status + * is less useful than what interrupt set. + */ + if (!(errflag & ERRFLAG_INT)) + lastval = ret; + } + if (do_save & BINF_COMMAND) + errflag &= ~ERRFLAG_ERROR; + restore_queue_signals(q); + fflush(stdout); + if (save[1] == -2) { + if (ferror(stdout)) { + zwarn("write error: %e", errno); + clearerr(stdout); + } + } else + clearerr(stdout); + } + if (isset(PRINTEXITVALUE) && isset(SHINSTDIN) && + lastval && !subsh) { +#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD) + fprintf(stderr, "zsh: exit %lld\n", lastval); +#else + fprintf(stderr, "zsh: exit %ld\n", (long)lastval); +#endif + fflush(stderr); + } + + if (do_exec) { + if (subsh) + _exit(lastval); + + /* If we are exec'ing a command, and we are not in a subshell, * + * then check if we should save the history file. */ + if (isset(RCS) && interact && !nohistsave) + savehistfile(NULL, 1, HFILE_USE_OPTIONS); + exit(lastval); + } + if (restorelist) + restore_params(restorelist, removelist); + + } else { + if (!subsh) { + /* for either implicit or explicit "exec", decrease $SHLVL + * as we're now done as a shell */ + if (!forked) + setiparam("SHLVL", --shlvl); + + /* If we are exec'ing a command, and we are not * + * in a subshell, then save the history file. */ + if (do_exec && isset(RCS) && interact && !nohistsave) + savehistfile(NULL, 1, HFILE_USE_OPTIONS); + } + if (type == WC_SIMPLE || type == WC_TYPESET) { + if (varspc) { + int addflags = ADDVAR_EXPORT|ADDVAR_RESTRICT; + if (forked) + addflags |= ADDVAR_RESTORE; + addvars(state, varspc, addflags); + if (errflag) + _exit(1); + } + closem(FDT_INTERNAL, 0); + if (coprocin != -1) { + zclose(coprocin); + coprocin = -1; + } + if (coprocout != -1) { + zclose(coprocout); + coprocout = -1; + } +#ifdef HAVE_GETRLIMIT + if (!forked) + setlimits(NULL); +#endif + if (how & Z_ASYNC) { + zsfree(STTYval); + STTYval = 0; + } + execute(args, cflags, use_defpath); + } else { /* ( ... ) */ + DPUTS(varspc, + "BUG: assignment before complex command"); + list_pipe = 0; + pipecleanfilelist(filelist, 0); + /* If we're forked (and we should be), no need to return */ + DPUTS(last1 != 1 && !forked, "BUG: not exiting?"); + DPUTS(type != WC_SUBSH, "Not sure what we're doing."); + /* Skip word only used for try/always blocks */ + state->pc++; + execlist(state, 0, 1); + } + } + } + + err: + if (forked) { + /* + * So what's going on here then? Well, I'm glad you asked. + * + * If we create multios for use in a subshell we do + * this after forking, in this function above. That + * means that the current (sub)process is responsible + * for clearing them up. However, the processes won't + * go away until we have closed the fd's talking to them. + * Since we're about to exit the shell there's nothing + * to stop us closing all fd's (including the ones 0 to 9 + * that we usually leave alone). + * + * Then we wait for any processes. When we forked, + * we cleared the jobtable and started a new job just for + * any oddments like this, so if there aren't any we won't + * need to wait. The result of not waiting is that + * the multios haven't flushed the fd's properly, leading + * to obscure missing data. + * + * It would probably be cleaner to ensure that the + * parent shell handled multios, but that requires + * some architectural changes which are likely to be + * hairy. + */ + for (i = 0; i < 10; i++) + if (fdtable[i] != FDT_UNUSED) + close(i); + closem(FDT_UNUSED, 1); + if (thisjob != -1) + waitjobs(); + _exit(lastval); + } + fixfds(save); + + done: + if (isset(POSIXBUILTINS) && + (cflags & (BINF_PSPECIAL|BINF_EXEC)) && + !(orig_cflags & BINF_COMMAND)) { + /* + * For POSIX-compatible behaviour with special + * builtins (including exec which we don't usually + * classify as a builtin) we treat all errors as fatal. + * The "command" builtin is not special so resets this behaviour. + */ + forked |= zsh_subshell; + fatal: + if (redir_err || errflag) { + if (!isset(INTERACTIVE)) { + if (forked) + _exit(1); + else + exit(1); + } + errflag |= ERRFLAG_ERROR; + } + } + if (newxtrerr) { + fil = fileno(newxtrerr); + fclose(newxtrerr); + xtrerr = oxtrerr; + zclose(fil); + } + + zsfree(STTYval); + STTYval = 0; + if (oautocont >= 0) + opts[AUTOCONTINUE] = oautocont; +} + +/* Arrange to have variables restored. */ + +/**/ +static void +save_params(Estate state, Wordcode pc, LinkList *restore_p, LinkList *remove_p) +{ + Param pm; + char *s; + wordcode ac; + + *restore_p = newlinklist(); + *remove_p = newlinklist(); + + while (wc_code(ac = *pc) == WC_ASSIGN) { + s = ecrawstr(state->prog, pc + 1, NULL); + if ((pm = (Param) paramtab->getnode(paramtab, s))) { + Param tpm; + if (pm->env) + delenv(pm); + if (!(pm->node.flags & PM_SPECIAL)) { + /* + * We used to remove ordinary parameters from the + * table, but that meant "HELLO=$HELLO shellfunc" + * failed because the expansion of $HELLO hasn't + * been done at this point. Instead, copy the + * parameter: in this case, we'll insert the + * copied parameter straight back into the parameter + * table so we want to be sure everything is + * properly set up and in permanent memory. + */ + tpm = (Param) zshcalloc(sizeof *tpm); + tpm->node.nam = ztrdup(pm->node.nam); + copyparam(tpm, pm, 0); + pm = tpm; + } else if (!(pm->node.flags & PM_READONLY) && + (unset(RESTRICTED) || !(pm->node.flags & PM_RESTRICTED))) { + /* + * In this case we're just saving parts of + * the parameter in a tempory, so use heap allocation + * and don't bother copying every detail. + */ + tpm = (Param) hcalloc(sizeof *tpm); + tpm->node.nam = pm->node.nam; + copyparam(tpm, pm, 1); + pm = tpm; + } + addlinknode(*remove_p, dupstring(s)); + addlinknode(*restore_p, pm); + } else + addlinknode(*remove_p, dupstring(s)); + + pc += (WC_ASSIGN_TYPE(ac) == WC_ASSIGN_SCALAR ? + 3 : WC_ASSIGN_NUM(ac) + 2); + } +} + +/* Restore saved parameters after executing a shfunc or builtin */ + +/**/ +static void +restore_params(LinkList restorelist, LinkList removelist) +{ + Param pm; + char *s; + + /* remove temporary parameters */ + while ((s = (char *) ugetnode(removelist))) { + if ((pm = (Param) paramtab->getnode(paramtab, s)) && + !(pm->node.flags & PM_SPECIAL)) { + pm->node.flags &= ~PM_READONLY; + unsetparam_pm(pm, 0, 0); + } + } + + if (restorelist) { + /* restore saved parameters */ + while ((pm = (Param) ugetnode(restorelist))) { + if (pm->node.flags & PM_SPECIAL) { + Param tpm = (Param) paramtab->getnode(paramtab, pm->node.nam); + + DPUTS(!tpm || PM_TYPE(pm->node.flags) != PM_TYPE(tpm->node.flags) || + !(pm->node.flags & PM_SPECIAL), + "BUG: in restoring special parameters"); + if (!pm->env && tpm->env) + delenv(tpm); + tpm->node.flags = pm->node.flags; + switch (PM_TYPE(pm->node.flags)) { + case PM_SCALAR: + tpm->gsu.s->setfn(tpm, pm->u.str); + break; + case PM_INTEGER: + tpm->gsu.i->setfn(tpm, pm->u.val); + break; + case PM_EFLOAT: + case PM_FFLOAT: + tpm->gsu.f->setfn(tpm, pm->u.dval); + break; + case PM_ARRAY: + tpm->gsu.a->setfn(tpm, pm->u.arr); + break; + case PM_HASHED: + tpm->gsu.h->setfn(tpm, pm->u.hash); + break; + } + pm = tpm; + } else { + paramtab->addnode(paramtab, pm->node.nam, pm); + } + if ((pm->node.flags & PM_EXPORTED) && ((s = getsparam(pm->node.nam)))) + addenv(pm, s); + } + } +} + +/* restore fds after redirecting a builtin */ + +/**/ +static void +fixfds(int *save) +{ + int old_errno = errno; + int i; + + for (i = 0; i != 10; i++) + if (save[i] != -2) + redup(save[i], i); + errno = old_errno; +} + +/* + * Close internal shell fds. + * + * Close any that are marked as used if "how" is FDT_UNUSED, else + * close any with the value "how". + * + * If "all" is zero, we'll skip cases where we need the file + * descriptor to be visible externally. + */ + +/**/ +mod_export void +closem(int how, int all) +{ + int i; + + for (i = 10; i <= max_zsh_fd; i++) + if (fdtable[i] != FDT_UNUSED && + /* + * Process substitution needs to be visible to user; + * fd's are explicitly cleaned up by filelist handling. + */ + (all || fdtable[i] != FDT_PROC_SUBST) && + (how == FDT_UNUSED || (fdtable[i] & FDT_TYPE_MASK) == how)) { + if (i == SHTTY) + SHTTY = -1; + zclose(i); + } +} + +/* convert here document into a here string */ + +/**/ +char * +gethere(char **strp, int typ) +{ + char *buf; + int bsiz, qt = 0, strip = 0; + char *s, *t, *bptr, c; + char *str = *strp; + + for (s = str; *s; s++) + if (inull(*s)) { + qt = 1; + break; + } + str = quotesubst(str); + untokenize(str); + if (typ == REDIR_HEREDOCDASH) { + strip = 1; + while (*str == '\t') + str++; + } + *strp = str; + bptr = buf = zalloc(bsiz = 256); + for (;;) { + t = bptr; + + while ((c = hgetc()) == '\t' && strip) + ; + for (;;) { + if (bptr >= buf + bsiz - 2) { + ptrdiff_t toff = t - buf; + ptrdiff_t bptroff = bptr - buf; + char *newbuf = realloc(buf, 2 * bsiz); + if (!newbuf) { + /* out of memory */ + zfree(buf, bsiz); + return NULL; + } + buf = newbuf; + t = buf + toff; + bptr = buf + bptroff; + bsiz *= 2; + } + if (lexstop || c == '\n') + break; + if (!qt && c == '\\') { + *bptr++ = c; + c = hgetc(); + if (c == '\n') { + bptr--; + c = hgetc(); + continue; + } + } + *bptr++ = c; + c = hgetc(); + } + *bptr = '\0'; + if (!strcmp(t, str)) + break; + if (lexstop) { + t = bptr; + break; + } + *bptr++ = '\n'; + } + *t = '\0'; + s = buf; + buf = dupstring(buf); + zfree(s, bsiz); + if (!qt) { + int ef = errflag; + + parsestr(&buf); + + if (!(errflag & ERRFLAG_ERROR)) { + /* Retain any user interrupt error */ + errflag = ef | (errflag & ERRFLAG_INT); + } + } + return buf; +} + +/* open here string fd */ + +/**/ +static int +getherestr(struct redir *fn) +{ + char *s, *t; + int fd, len; + + t = fn->name; + singsub(&t); + untokenize(t); + unmetafy(t, &len); + /* + * For real here-strings we append a newline, as if the + * string given was a complete command line. + * + * For here-strings from here documents, we use the original + * text exactly. + */ + if (!(fn->flags & REDIRF_FROM_HEREDOC)) + t[len++] = '\n'; + if ((fd = gettempfile(NULL, 1, &s)) < 0) + return -1; + write_loop(fd, t, len); + close(fd); + fd = open(s, O_RDONLY | O_NOCTTY); + unlink(s); + return fd; +} + +/* + * Test if some wordcode starts with a simple redirection of type + * redir_type. If it does, return the name of the file, copied onto + * the heap. If it doesn't, return NULL. + */ + +static char * +simple_redir_name(Eprog prog, int redir_type) +{ + Wordcode pc; + + pc = prog->prog; + if (prog != &dummy_eprog && + wc_code(pc[0]) == WC_LIST && (WC_LIST_TYPE(pc[0]) & Z_END) && + wc_code(pc[1]) == WC_SUBLIST && !WC_SUBLIST_FLAGS(pc[1]) && + WC_SUBLIST_TYPE(pc[1]) == WC_SUBLIST_END && + wc_code(pc[2]) == WC_PIPE && WC_PIPE_TYPE(pc[2]) == WC_PIPE_END && + wc_code(pc[3]) == WC_REDIR && WC_REDIR_TYPE(pc[3]) == redir_type && + !WC_REDIR_VARID(pc[3]) && + !pc[4] && + wc_code(pc[6]) == WC_SIMPLE && !WC_SIMPLE_ARGC(pc[6])) { + return dupstring(ecrawstr(prog, pc + 5, NULL)); + } + + return NULL; +} + +/* $(...) */ + +/**/ +LinkList +getoutput(char *cmd, int qt) +{ + Eprog prog; + int pipes[2]; + pid_t pid; + char *s; + + int onc = nocomments; + nocomments = (interact && unset(INTERACTIVECOMMENTS)); + prog = parse_string(cmd, 0); + nocomments = onc; + + if (!prog) + return NULL; + + if ((s = simple_redir_name(prog, REDIR_READ))) { + /* $(< word) */ + int stream; + LinkList retval; + int readerror; + + singsub(&s); + if (errflag) + return NULL; + untokenize(s); + if ((stream = open(unmeta(s), O_RDONLY | O_NOCTTY)) == -1) { + zwarn("%e: %s", errno, s); + lastval = cmdoutval = 1; + return newlinklist(); + } + retval = readoutput(stream, qt, &readerror); + if (readerror) { + zwarn("error when reading %s: %e", s, readerror); + lastval = cmdoutval = 1; + } + return retval; + } + if (mpipe(pipes) < 0) { + errflag |= ERRFLAG_ERROR; + cmdoutpid = 0; + return NULL; + } + child_block(); + cmdoutval = 0; + if ((cmdoutpid = pid = zfork(NULL)) == -1) { + /* fork error */ + zclose(pipes[0]); + zclose(pipes[1]); + errflag |= ERRFLAG_ERROR; + cmdoutpid = 0; + child_unblock(); + return NULL; + } else if (pid) { + LinkList retval; + + zclose(pipes[1]); + retval = readoutput(pipes[0], qt, NULL); + fdtable[pipes[0]] = FDT_UNUSED; + waitforpid(pid, 0); /* unblocks */ + lastval = cmdoutval; + return retval; + } + /* pid == 0 */ + child_unblock(); + zclose(pipes[0]); + redup(pipes[1], 1); + entersubsh(ESUB_PGRP|ESUB_NOMONITOR); + cmdpush(CS_CMDSUBST); + execode(prog, 0, 1, "cmdsubst"); + cmdpop(); + close(1); + _exit(lastval); + zerr("exit returned in child!!"); + kill(getpid(), SIGKILL); + return NULL; +} + +/* read output of command substitution */ + +/**/ +mod_export LinkList +readoutput(int in, int qt, int *readerror) +{ + LinkList ret; + char *buf, *ptr; + int bsiz, c, cnt = 0; + FILE *fin; + int q = queue_signal_level(); + + fin = fdopen(in, "r"); + ret = newlinklist(); + ptr = buf = (char *) hcalloc(bsiz = 64); + /* + * We need to be sensitive to SIGCHLD else we can be + * stuck forever with important processes unreaped. + * The case that triggered this was where the exiting + * process is group leader of the foreground process and we need + * to reclaim the terminal else ^C doesn't work. + */ + dont_queue_signals(); + child_unblock(); + while ((c = fgetc(fin)) != EOF || errno == EINTR) { + if (c == EOF) { + errno = 0; + clearerr(fin); + continue; + } + if (imeta(c)) { + *ptr++ = Meta; + c ^= 32; + cnt++; + } + if (++cnt >= bsiz) { + char *pp; + queue_signals(); + pp = (char *) hcalloc(bsiz *= 2); + dont_queue_signals(); + + memcpy(pp, buf, cnt - 1); + ptr = (buf = pp) + cnt - 1; + } + *ptr++ = c; + } + child_block(); + restore_queue_signals(q); + if (readerror) + *readerror = ferror(fin) ? errno : 0; + fclose(fin); + while (cnt && ptr[-1] == '\n') + ptr--, cnt--; + *ptr = '\0'; + if (qt) { + if (!cnt) { + *ptr++ = Nularg; + *ptr = '\0'; + } + addlinknode(ret, buf); + } else { + char **words = spacesplit(buf, 0, 1, 0); + + while (*words) { + if (isset(GLOBSUBST)) + shtokenize(*words); + addlinknode(ret, *words++); + } + } + return ret; +} + +/**/ +static Eprog +parsecmd(char *cmd, char **eptr) +{ + char *str; + Eprog prog; + + for (str = cmd + 2; *str && *str != Outpar; str++); + if (!*str || cmd[1] != Inpar) { + /* + * This can happen if the expression is being parsed + * inside another construct, e.g. as a value within ${..:..} etc. + * So print a proper error message instead of the not very + * useful but traditional "oops". + */ + char *errstr = dupstrpfx(cmd, 2); + untokenize(errstr); + zerr("unterminated `%s...)'", errstr); + return NULL; + } + *str = '\0'; + if (eptr) + *eptr = str+1; + if (!(prog = parse_string(cmd + 2, 0))) { + zerr("parse error in process substitution"); + return NULL; + } + return prog; +} + +/* =(...) */ + +/**/ +char * +getoutputfile(char *cmd, char **eptr) +{ + pid_t pid; + char *nam; + Eprog prog; + int fd; + char *s; + + if (thisjob == -1){ + zerr("process substitution %s cannot be used here", cmd); + return NULL; + } + if (!(prog = parsecmd(cmd, eptr))) + return NULL; + if (!(nam = gettempname(NULL, 1))) + return NULL; + + if ((s = simple_redir_name(prog, REDIR_HERESTR))) { + /* + * =(<<(...) */ + +/**/ +char * +getproc(char *cmd, char **eptr) +{ +#if !defined(HAVE_FIFOS) && !defined(PATH_DEV_FD) + zerr("doesn't look like your system supports FIFOs."); + return NULL; +#else + Eprog prog; + int out = *cmd == Inang; + char *pnam; + pid_t pid; + struct timeval bgtime; + +#ifndef PATH_DEV_FD + int fd; + if (thisjob == -1) { + zerr("process substitution %s cannot be used here", cmd); + return NULL; + } + if (!(pnam = namedpipe())) + return NULL; + if (!(prog = parsecmd(cmd, eptr))) + return NULL; + addfilelist(pnam, 0); + + if ((pid = zfork(&bgtime))) { + if (pid == -1) + return NULL; + if (!out) + addproc(pid, NULL, 1, &bgtime); + procsubstpid = pid; + return pnam; + } + closem(FDT_UNUSED, 0); + fd = open(pnam, out ? O_WRONLY | O_NOCTTY : O_RDONLY | O_NOCTTY); + if (fd == -1) { + zerr("can't open %s: %e", pnam, errno); + _exit(1); + } + entersubsh(ESUB_ASYNC|ESUB_PGRP); + redup(fd, out); +#else /* PATH_DEV_FD */ + int pipes[2], fd; + + if (thisjob == -1) { + zerr("process substitution %s cannot be used here", cmd); + return NULL; + } + pnam = zhalloc(strlen(PATH_DEV_FD) + 1 + DIGBUFSIZE); + if (!(prog = parsecmd(cmd, eptr))) + return NULL; + if (mpipe(pipes) < 0) + return NULL; + if ((pid = zfork(&bgtime))) { + sprintf(pnam, "%s/%d", PATH_DEV_FD, pipes[!out]); + zclose(pipes[out]); + if (pid == -1) + { + zclose(pipes[!out]); + return NULL; + } + fd = pipes[!out]; + fdtable[fd] = FDT_PROC_SUBST; + addfilelist(NULL, fd); + if (!out) + { + addproc(pid, NULL, 1, &bgtime); + } + procsubstpid = pid; + return pnam; + } + entersubsh(ESUB_ASYNC|ESUB_PGRP); + redup(pipes[out], out); + closem(FDT_UNUSED, 0); /* this closes pipes[!out] as well */ +#endif /* PATH_DEV_FD */ + + cmdpush(CS_CMDSUBST); + execode(prog, 0, 1, out ? "outsubst" : "insubst"); + cmdpop(); + zclose(out); + _exit(lastval); + return NULL; +#endif /* HAVE_FIFOS and PATH_DEV_FD not defined */ +} + +/* + * > >(...) or < <(...) (does not use named pipes) + * + * If the second argument is 1, this is part of + * an "exec < <(...)" or "exec > >(...)" and we shouldn't + * wait for the job to finish before continuing. + */ + +/**/ +static int +getpipe(char *cmd, int nullexec) +{ + Eprog prog; + int pipes[2], out = *cmd == Inang; + pid_t pid; + struct timeval bgtime; + char *ends; + + if (!(prog = parsecmd(cmd, &ends))) + return -1; + if (*ends) { + zerr("invalid syntax for process substitution in redirection"); + return -1; + } + if (mpipe(pipes) < 0) + return -1; + if ((pid = zfork(&bgtime))) { + zclose(pipes[out]); + if (pid == -1) { + zclose(pipes[!out]); + return -1; + } + if (!nullexec) + addproc(pid, NULL, 1, &bgtime); + procsubstpid = pid; + return pipes[!out]; + } + entersubsh(ESUB_PGRP); + redup(pipes[out], out); + closem(FDT_UNUSED, 0); /* this closes pipes[!out] as well */ + cmdpush(CS_CMDSUBST); + execode(prog, 0, 1, out ? "outsubst" : "insubst"); + cmdpop(); + _exit(lastval); + return 0; +} + +/* open pipes with fds >= 10 */ + +/**/ +static int +mpipe(int *pp) +{ + if (pipe(pp) < 0) { + zerr("pipe failed: %e", errno); + return -1; + } + pp[0] = movefd(pp[0]); + pp[1] = movefd(pp[1]); + return 0; +} + +/* + * Do process substitution with redirection + * + * If the second argument is 1, this is part of + * an "exec < <(...)" or "exec > >(...)" and we shouldn't + * wait for the job to finish before continuing. + * Likewise, we shouldn't wait if we are opening the file + * descriptor using the {fd}>>(...) notation since it stays + * valid for subsequent commands. + */ + +/**/ +static void +spawnpipes(LinkList l, int nullexec) +{ + LinkNode n; + Redir f; + char *str; + + n = firstnode(l); + for (; n; incnode(n)) { + f = (Redir) getdata(n); + if (f->type == REDIR_OUTPIPE || f->type == REDIR_INPIPE) { + str = f->name; + f->fd2 = getpipe(str, nullexec || f->varid); + } + } +} + +/* evaluate a [[ ... ]] */ + +/**/ +static int +execcond(Estate state, UNUSED(int do_exec)) +{ + int stat; + + state->pc--; + if (isset(XTRACE)) { + printprompt4(); + fprintf(xtrerr, "[["); + tracingcond++; + } + cmdpush(CS_COND); + stat = evalcond(state, NULL); + /* + * 2 indicates a syntax error. For compatibility, turn this + * into a shell error. + */ + if (stat == 2) + errflag |= ERRFLAG_ERROR; + cmdpop(); + if (isset(XTRACE)) { + fprintf(xtrerr, " ]]\n"); + fflush(xtrerr); + tracingcond--; + } + return stat; +} + +/* evaluate a ((...)) arithmetic command */ + +/**/ +static int +execarith(Estate state, UNUSED(int do_exec)) +{ + char *e; + mnumber val = zero_mnumber; + int htok = 0; + + if (isset(XTRACE)) { + printprompt4(); + fprintf(xtrerr, "(("); + } + cmdpush(CS_MATH); + e = ecgetstr(state, EC_DUPTOK, &htok); + if (htok) + singsub(&e); + if (isset(XTRACE)) + fprintf(xtrerr, " %s", e); + + val = matheval(e); + + cmdpop(); + + if (isset(XTRACE)) { + fprintf(xtrerr, " ))\n"); + fflush(xtrerr); + } + if (errflag) { + errflag &= ~ERRFLAG_ERROR; + return 2; + } + /* should test for fabs(val.u.d) < epsilon? */ + return (val.type == MN_INTEGER) ? val.u.l == 0 : val.u.d == 0.0; +} + +/* perform time ... command */ + +/**/ +static int +exectime(Estate state, UNUSED(int do_exec)) +{ + int jb; + + jb = thisjob; + if (WC_TIMED_TYPE(state->pc[-1]) == WC_TIMED_EMPTY) { + shelltime(); + return 0; + } + execpline(state, *state->pc++, Z_TIMED|Z_SYNC, 0); + thisjob = jb; + return lastval; +} + +/* Define a shell function */ + +static const char *const ANONYMOUS_FUNCTION_NAME = "(anon)"; + +/**/ +static int +execfuncdef(Estate state, Eprog redir_prog) +{ + Shfunc shf; + char *s = NULL; + int signum, nprg, sbeg, nstrs, npats, len, plen, i, htok = 0, ret = 0; + int anon_func = 0; + Wordcode beg = state->pc, end; + Eprog prog; + Patprog *pp; + LinkList names; + + end = beg + WC_FUNCDEF_SKIP(state->pc[-1]); + names = ecgetlist(state, *state->pc++, EC_DUPTOK, &htok); + nprg = end - beg; + sbeg = *state->pc++; + nstrs = *state->pc++; + npats = *state->pc++; + + nprg = (end - state->pc); + plen = nprg * sizeof(wordcode); + len = plen + (npats * sizeof(Patprog)) + nstrs; + + if (htok && names) { + execsubst(names); + if (errflag) { + state->pc = end; + return 1; + } + } + + DPUTS(!names && redir_prog, + "Passing redirection to anon function definition."); + while (!names || (s = (char *) ugetnode(names))) { + if (!names) { + prog = (Eprog) zhalloc(sizeof(*prog)); + prog->nref = -1; /* on the heap */ + } else { + prog = (Eprog) zalloc(sizeof(*prog)); + prog->nref = 1; /* allocated from permanent storage */ + } + prog->npats = npats; + prog->len = len; + if (state->prog->dump || !names) { + if (!names) { + prog->flags = EF_HEAP; + prog->dump = NULL; + prog->pats = pp = (Patprog *) zhalloc(npats * sizeof(Patprog)); + } else { + prog->flags = EF_MAP; + incrdumpcount(state->prog->dump); + prog->dump = state->prog->dump; + prog->pats = pp = (Patprog *) zalloc(npats * sizeof(Patprog)); + } + prog->prog = state->pc; + prog->strs = state->strs + sbeg; + } else { + prog->flags = EF_REAL; + prog->pats = pp = (Patprog *) zalloc(len); + prog->prog = (Wordcode) (prog->pats + npats); + prog->strs = (char *) (prog->prog + nprg); + prog->dump = NULL; + memcpy(prog->prog, state->pc, plen); + memcpy(prog->strs, state->strs + sbeg, nstrs); + } + for (i = npats; i--; pp++) + *pp = dummy_patprog1; + prog->shf = NULL; + + shf = (Shfunc) zalloc(sizeof(*shf)); + shf->funcdef = prog; + shf->node.flags = 0; + /* No dircache here, not a directory */ + shf->filename = ztrdup(scriptfilename); + shf->lineno = + (funcstack && (funcstack->tp == FS_FUNC || + funcstack->tp == FS_EVAL)) ? + funcstack->flineno + lineno : + lineno; + /* + * redir_prog is permanently allocated --- but if + * this function has multiple names we need an additional + * one. Original redir_prog used with the last name + * because earlier functions are freed in case of duplicate + * names. + */ + if (names && nonempty(names) && redir_prog) + shf->redir = dupeprog(redir_prog, 0); + else { + shf->redir = redir_prog; + redir_prog = 0; + } + shfunc_set_sticky(shf); + + if (!names) { + /* + * Anonymous function, execute immediately. + * Function name is "(anon)". + */ + LinkList args; + + anon_func = 1; + shf->node.flags |= PM_ANONYMOUS; + + state->pc = end; + end += *state->pc++; + args = ecgetlist(state, *state->pc++, EC_DUPTOK, &htok); + + if (htok && args) { + execsubst(args); + if (errflag) { + freeeprog(shf->funcdef); + if (shf->redir) /* shouldn't be */ + freeeprog(shf->redir); + dircache_set(&shf->filename, NULL); + zfree(shf, sizeof(*shf)); + state->pc = end; + return 1; + } + } + + setunderscore((args && nonempty(args)) ? + ((char *) getdata(lastnode(args))) : ""); + + if (!args) + args = newlinklist(); + shf->node.nam = (char *) ANONYMOUS_FUNCTION_NAME; + pushnode(args, shf->node.nam); + + execshfunc(shf, args); + ret = lastval; + + if (isset(PRINTEXITVALUE) && isset(SHINSTDIN) && + lastval) { +#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD) + fprintf(stderr, "zsh: exit %lld\n", lastval); +#else + fprintf(stderr, "zsh: exit %ld\n", (long)lastval); +#endif + fflush(stderr); + } + + freeeprog(shf->funcdef); + if (shf->redir) /* shouldn't be */ + freeeprog(shf->redir); + dircache_set(&shf->filename, NULL); + zfree(shf, sizeof(*shf)); + break; + } else { + /* is this shell function a signal trap? */ + if (!strncmp(s, "TRAP", 4) && + (signum = getsignum(s + 4)) != -1) { + if (settrap(signum, NULL, ZSIG_FUNC)) { + freeeprog(shf->funcdef); + dircache_set(&shf->filename, NULL); + zfree(shf, sizeof(*shf)); + state->pc = end; + return 1; + } + + /* + * Remove the old node explicitly in case it has + * an alternative name + */ + removetrapnode(signum); + } + shfunctab->addnode(shfunctab, ztrdup(s), shf); + } + } + if (!anon_func) + setunderscore(""); + if (redir_prog) { + /* For completeness, shouldn't happen */ + freeeprog(redir_prog); + } + state->pc = end; + return ret; +} + +/* Duplicate a sticky emulation */ + +/**/ + +mod_export Emulation_options +sticky_emulation_dup(Emulation_options src, int useheap) +{ + Emulation_options newsticky = useheap ? + hcalloc(sizeof(*src)) : zshcalloc(sizeof(*src)); + newsticky->emulation = src->emulation; + if (src->n_on_opts) { + size_t sz = src->n_on_opts * sizeof(*src->on_opts); + newsticky->n_on_opts = src->n_on_opts; + newsticky->on_opts = useheap ? zhalloc(sz) : zalloc(sz); + memcpy(newsticky->on_opts, src->on_opts, sz); + } + if (src->n_off_opts) { + size_t sz = src->n_off_opts * sizeof(*src->off_opts); + newsticky->n_off_opts = src->n_off_opts; + newsticky->off_opts = useheap ? zhalloc(sz) : zalloc(sz); + memcpy(newsticky->off_opts, src->off_opts, sz); + } + + return newsticky; +} + +/* Set the sticky emulation attributes for a shell function */ + +/**/ + +mod_export void +shfunc_set_sticky(Shfunc shf) +{ + if (sticky) + shf->sticky = sticky_emulation_dup(sticky, 0); + else + shf->sticky = NULL; +} + + +/* Main entry point to execute a shell function. */ + +/**/ +static void +execshfunc(Shfunc shf, LinkList args) +{ + LinkList last_file_list = NULL; + unsigned char *ocs; + int ocsp, osfc; + + if (errflag) + return; + + /* thisjob may be invalid if we're called via execsimple: see execcursh */ + if (!list_pipe && thisjob != -1 && thisjob != list_pipe_job && + !hasprocs(thisjob)) { + /* Without this deletejob the process table * + * would be filled by a recursive function. */ + last_file_list = jobtab[thisjob].filelist; + jobtab[thisjob].filelist = NULL; + deletejob(jobtab + thisjob, 0); + } + + if (isset(XTRACE)) { + LinkNode lptr; + printprompt4(); + if (args) + for (lptr = firstnode(args); lptr; incnode(lptr)) { + if (lptr != firstnode(args)) + fputc(' ', xtrerr); + quotedzputs((char *)getdata(lptr), xtrerr); + } + fputc('\n', xtrerr); + fflush(xtrerr); + } + queue_signals(); + ocs = cmdstack; + ocsp = cmdsp; + cmdstack = (unsigned char *) zalloc(CMDSTACKSZ); + cmdsp = 0; + if ((osfc = sfcontext) == SFC_NONE) + sfcontext = SFC_DIRECT; + xtrerr = stderr; + + doshfunc(shf, args, 0); + + sfcontext = osfc; + free(cmdstack); + cmdstack = ocs; + cmdsp = ocsp; + + if (!list_pipe) + deletefilelist(last_file_list, 0); + unqueue_signals(); +} + +/* + * Function to execute the special type of command that represents an + * autoloaded shell function. The command structure tells us which + * function it is. This function is actually called as part of the + * execution of the autoloaded function itself, so when the function + * has been autoloaded, its list is just run with no frills. + * + * There are two cases because if we are doing all-singing, all-dancing + * non-simple code we load the shell function early in execcmd() (the + * action also present in the non-basic version) to check if + * there are redirections that need to be handled at that point. + * Then we call execautofn_basic() to do the rest. + */ + +/**/ +static int +execautofn_basic(Estate state, UNUSED(int do_exec)) +{ + Shfunc shf; + char *oldscriptname, *oldscriptfilename; + + shf = state->prog->shf; + + /* + * Probably we didn't know the filename where this function was + * defined yet. + */ + if (funcstack && !funcstack->filename) + funcstack->filename = getshfuncfile(shf); + + oldscriptname = scriptname; + oldscriptfilename = scriptfilename; + scriptname = dupstring(shf->node.nam); + scriptfilename = getshfuncfile(shf); + execode(shf->funcdef, 1, 0, "loadautofunc"); + scriptname = oldscriptname; + scriptfilename = oldscriptfilename; + + return lastval; +} + +/**/ +static int +execautofn(Estate state, UNUSED(int do_exec)) +{ + Shfunc shf; + + if (!(shf = loadautofn(state->prog->shf, 1, 0, 0))) + return 1; + + state->prog->shf = shf; + return execautofn_basic(state, 0); +} + +/* + * Helper function to install the source file name of a shell function + * just autoloaded. + * + * We attempt to do this efficiently as the typical case is the + * directory part is a well-known directory, which is cached, and + * the non-directory part is the same as the node name. + */ + +/**/ +static void +loadautofnsetfile(Shfunc shf, char *fdir) +{ + /* + * If shf->filename is already the load directory --- + * keep it as we can still use it to get the load file. + * This makes autoload with an absolute path particularly efficient. + */ + if (!(shf->node.flags & PM_LOADDIR) || + strcmp(shf->filename, fdir) != 0) { + /* Old directory name not useful... */ + dircache_set(&shf->filename, NULL); + if (fdir) { + /* ...can still cache directory */ + shf->node.flags |= PM_LOADDIR; + dircache_set(&shf->filename, fdir); + } else { + /* ...no separate directory part to cache, for some reason. */ + shf->node.flags &= ~PM_LOADDIR; + shf->filename = ztrdup(shf->node.nam); + } + } +} + +/**/ +Shfunc +loadautofn(Shfunc shf, int fksh, int autol, int current_fpath) +{ + int noalias = noaliases, ksh = 1; + Eprog prog; + char *fdir; /* Directory path where func found */ + + pushheap(); + + noaliases = (shf->node.flags & PM_UNALIASED); + if (shf->filename && shf->filename[0] == '/' && + (shf->node.flags & PM_LOADDIR)) + { + char *spec_path[2]; + spec_path[0] = dupstring(shf->filename); + spec_path[1] = NULL; + prog = getfpfunc(shf->node.nam, &ksh, &fdir, spec_path, 0); + if (prog == &dummy_eprog && + (current_fpath || (shf->node.flags & PM_CUR_FPATH))) + prog = getfpfunc(shf->node.nam, &ksh, &fdir, NULL, 0); + } + else + prog = getfpfunc(shf->node.nam, &ksh, &fdir, NULL, 0); + noaliases = noalias; + + if (ksh == 1) { + ksh = fksh; + if (ksh == 1) + ksh = (shf->node.flags & PM_KSHSTORED) ? 2 : + (shf->node.flags & PM_ZSHSTORED) ? 0 : 1; + } + + if (prog == &dummy_eprog) { + /* We're not actually in the function; decrement locallevel */ + locallevel--; + zwarn("%s: function definition file not found", shf->node.nam); + locallevel++; + popheap(); + return NULL; + } + if (!prog) { + popheap(); + return NULL; + } + if (ksh == 2 || (ksh == 1 && isset(KSHAUTOLOAD))) { + if (autol) { + prog->flags |= EF_RUN; + + freeeprog(shf->funcdef); + if (prog->flags & EF_MAP) + shf->funcdef = prog; + else + shf->funcdef = dupeprog(prog, 0); + shf->node.flags &= ~PM_UNDEFINED; + loadautofnsetfile(shf, fdir); + } else { + VARARR(char, n, strlen(shf->node.nam) + 1); + strcpy(n, shf->node.nam); + execode(prog, 1, 0, "evalautofunc"); + shf = (Shfunc) shfunctab->getnode(shfunctab, n); + if (!shf || (shf->node.flags & PM_UNDEFINED)) { + /* We're not actually in the function; decrement locallevel */ + locallevel--; + zwarn("%s: function not defined by file", n); + locallevel++; + popheap(); + return NULL; + } + } + } else { + freeeprog(shf->funcdef); + if (prog->flags & EF_MAP) + shf->funcdef = stripkshdef(prog, shf->node.nam); + else + shf->funcdef = dupeprog(stripkshdef(prog, shf->node.nam), 0); + shf->node.flags &= ~PM_UNDEFINED; + loadautofnsetfile(shf, fdir); + } + popheap(); + + return shf; +} + +/* + * Check if a sticky emulation differs from the current one. + */ + +/**/ + +int sticky_emulation_differs(Emulation_options sticky2) +{ + /* If no new sticky emulation, not a different emulation */ + if (!sticky2) + return 0; + /* If no current sticky emulation, different */ + if (!sticky) + return 1; + /* If basic emulation different, different */ + if (sticky->emulation != sticky2->emulation) + return 1; + /* If differing numbers of options, different */ + if (sticky->n_on_opts != sticky2->n_on_opts || + sticky->n_off_opts != sticky2->n_off_opts) + return 1; + /* + * We need to compare option arrays, if non-null. + * We made parseopts() create the list of options in option + * order to make this easy. + */ + /* If different options turned on, different */ + if (sticky->n_on_opts && + memcmp(sticky->on_opts, sticky2->on_opts, + sticky->n_on_opts * sizeof(*sticky->on_opts)) != 0) + return 1; + /* If different options turned on, different */ + if (sticky->n_off_opts && + memcmp(sticky->off_opts, sticky2->off_opts, + sticky->n_off_opts * sizeof(*sticky->off_opts)) != 0) + return 1; + return 0; +} + +/* + * execute a shell function + * + * name is the name of the function + * + * prog is the code to execute + * + * doshargs, if set, are parameters to pass to the function, + * in which the first element is the function name (even if + * FUNCTIONARGZERO is set as this is handled inside this function). + * + * If noreturnval is nonzero, then reset the current return + * value (lastval) to its value before the shell function + * was executed. However, in any case return the status value + * from the function (i.e. if noreturnval is not set, this + * will be the same as lastval). + */ + +/**/ +mod_export int +doshfunc(Shfunc shfunc, LinkList doshargs, int noreturnval) +{ + char **pptab, **x; + int ret; + char *name = shfunc->node.nam; + int flags = shfunc->node.flags; + char *fname = dupstring(name); + Eprog prog; + static int oflags; + static int funcdepth; + Heap funcheap; + + queue_signals(); /* Lots of memory and global state changes coming */ + + NEWHEAPS(funcheap) { + /* + * Save data in heap rather than on stack to keep recursive + * function cost down --- use of heap memory should be efficient + * at this point. Saving is not actually massive. + */ + Funcsave funcsave = zhalloc(sizeof(struct funcsave)); + funcsave->scriptname = scriptname; + funcsave->argv0 = NULL; + funcsave->breaks = breaks; + funcsave->contflag = contflag; + funcsave->loops = loops; + funcsave->lastval = lastval; + funcsave->pipestats = NULL; + funcsave->numpipestats = numpipestats; + funcsave->noerrexit = noerrexit; + if (trap_state == TRAP_STATE_PRIMED) + trap_return--; + /* + * Suppression of ERR_RETURN is turned off in function scope. + */ + noerrexit &= ~NOERREXIT_RETURN; + if (noreturnval) { + /* + * Easiest to use the heap here since we're bracketed + * immediately by a pushheap/popheap pair. + */ + size_t bytes = sizeof(int)*numpipestats; + funcsave->pipestats = (int *)zhalloc(bytes); + memcpy(funcsave->pipestats, pipestats, bytes); + } + + starttrapscope(); + startpatternscope(); + + pptab = pparams; + if (!(flags & PM_UNDEFINED)) + scriptname = dupstring(name); + funcsave->zoptind = zoptind; + funcsave->optcind = optcind; + if (!isset(POSIXBUILTINS)) { + zoptind = 1; + optcind = 0; + } + + /* We need to save the current options even if LOCALOPTIONS is * + * not currently set. That's because if it gets set in the * + * function we need to restore the original options on exit. */ + memcpy(funcsave->opts, opts, sizeof(opts)); + funcsave->emulation = emulation; + funcsave->sticky = sticky; + + if (sticky_emulation_differs(shfunc->sticky)) { + /* + * Function is marked for sticky emulation. + * Enable it now. + * + * We deliberately do not do this if the sticky emulation + * in effect is the same as that requested. This enables + * option setting naturally within emulation environments. + * Note that a difference in EMULATE_FULLY (emulate with + * or without -R) counts as a different environment. + * + * This propagates the sticky emulation to subfunctions. + */ + sticky = sticky_emulation_dup(shfunc->sticky, 1); + emulation = sticky->emulation; + funcsave->restore_sticky = 1; + installemulation(emulation, opts); + if (sticky->n_on_opts) { + OptIndex *onptr; + for (onptr = sticky->on_opts; + onptr < sticky->on_opts + sticky->n_on_opts; + onptr++) + opts[*onptr] = 1; + } + if (sticky->n_off_opts) { + OptIndex *offptr; + for (offptr = sticky->off_opts; + offptr < sticky->off_opts + sticky->n_off_opts; + offptr++) + opts[*offptr] = 0; + } + /* All emulations start with pattern disables clear */ + clearpatterndisables(); + } else + funcsave->restore_sticky = 0; + + if (flags & (PM_TAGGED|PM_TAGGED_LOCAL)) + opts[XTRACE] = 1; + else if (oflags & PM_TAGGED_LOCAL) { + if (shfunc->node.nam == ANONYMOUS_FUNCTION_NAME /* pointer comparison */) + flags |= PM_TAGGED_LOCAL; + else + opts[XTRACE] = 0; + } + if (flags & PM_WARNNESTED) + opts[WARNNESTEDVAR] = 1; + else if (oflags & PM_WARNNESTED) { + if (shfunc->node.nam == ANONYMOUS_FUNCTION_NAME) + flags |= PM_WARNNESTED; + else + opts[WARNNESTEDVAR] = 0; + } + funcsave->oflags = oflags; + /* + * oflags is static, because we compare it on the next recursive + * call. Hence also we maintain a saved version for restoring + * the previous value of oflags after the call. + */ + oflags = flags; + opts[PRINTEXITVALUE] = 0; + if (doshargs) { + LinkNode node; + + node = firstnode(doshargs); + pparams = x = (char **) zshcalloc(((sizeof *x) * + (1 + countlinknodes(doshargs)))); + if (isset(FUNCTIONARGZERO)) { + funcsave->argv0 = argzero; + argzero = ztrdup(getdata(node)); + } + /* first node contains name regardless of option */ + node = node->next; + for (; node; node = node->next, x++) + *x = ztrdup(getdata(node)); + } else { + pparams = (char **) zshcalloc(sizeof *pparams); + if (isset(FUNCTIONARGZERO)) { + funcsave->argv0 = argzero; + argzero = ztrdup(argzero); + } + } + ++funcdepth; + if (zsh_funcnest >= 0 && funcdepth > zsh_funcnest) { + zerr("maximum nested function level reached; increase FUNCNEST?"); + lastval = 1; + goto undoshfunc; + } + funcsave->fstack.name = dupstring(name); + /* + * The caller is whatever is immediately before on the stack, + * unless we're at the top, in which case it's the script + * or interactive shell name. + */ + funcsave->fstack.caller = funcstack ? funcstack->name : + dupstring(funcsave->argv0 ? funcsave->argv0 : argzero); + funcsave->fstack.lineno = lineno; + funcsave->fstack.prev = funcstack; + funcsave->fstack.tp = FS_FUNC; + funcstack = &funcsave->fstack; + + funcsave->fstack.flineno = shfunc->lineno; + funcsave->fstack.filename = getshfuncfile(shfunc); + + prog = shfunc->funcdef; + if (prog->flags & EF_RUN) { + Shfunc shf; + + prog->flags &= ~EF_RUN; + + runshfunc(prog, NULL, funcsave->fstack.name); + + if (!(shf = (Shfunc) shfunctab->getnode(shfunctab, + (name = fname)))) { + zwarn("%s: function not defined by file", name); + if (noreturnval) + errflag |= ERRFLAG_ERROR; + else + lastval = 1; + goto doneshfunc; + } + prog = shf->funcdef; + } + runshfunc(prog, wrappers, funcsave->fstack.name); + doneshfunc: + funcstack = funcsave->fstack.prev; + undoshfunc: + --funcdepth; + if (retflag) { + /* + * This function is forced to return. + */ + retflag = 0; + /* + * The calling function isn't necessarily forced to return, + * but it should be made sensitive to ERR_EXIT and + * ERR_RETURN as the assumptions we made at the end of + * constructs within this function no longer apply. If + * there are cases where this is not true, they need adding + * to C03traps.ztst. + */ + this_noerrexit = 0; + breaks = funcsave->breaks; + } + freearray(pparams); + if (funcsave->argv0) { + zsfree(argzero); + argzero = funcsave->argv0; + } + pparams = pptab; + if (!isset(POSIXBUILTINS)) { + zoptind = funcsave->zoptind; + optcind = funcsave->optcind; + } + scriptname = funcsave->scriptname; + oflags = funcsave->oflags; + + endpatternscope(); /* before restoring old LOCALPATTERNS */ + + if (funcsave->restore_sticky) { + /* + * If we switched to an emulation environment just for + * this function, we interpret the option and emulation + * switch as being a firewall between environments. + */ + memcpy(opts, funcsave->opts, sizeof(opts)); + emulation = funcsave->emulation; + sticky = funcsave->sticky; + } else if (isset(LOCALOPTIONS)) { + /* restore all shell options except PRIVILEGED and RESTRICTED */ + funcsave->opts[PRIVILEGED] = opts[PRIVILEGED]; + funcsave->opts[RESTRICTED] = opts[RESTRICTED]; + memcpy(opts, funcsave->opts, sizeof(opts)); + emulation = funcsave->emulation; + } else { + /* just restore a couple. */ + opts[XTRACE] = funcsave->opts[XTRACE]; + opts[PRINTEXITVALUE] = funcsave->opts[PRINTEXITVALUE]; + opts[LOCALOPTIONS] = funcsave->opts[LOCALOPTIONS]; + opts[LOCALLOOPS] = funcsave->opts[LOCALLOOPS]; + opts[WARNNESTEDVAR] = funcsave->opts[WARNNESTEDVAR]; + } + + if (opts[LOCALLOOPS]) { + if (contflag) + zwarn("`continue' active at end of function scope"); + if (breaks) + zwarn("`break' active at end of function scope"); + breaks = funcsave->breaks; + contflag = funcsave->contflag; + loops = funcsave->loops; + } + + endtrapscope(); + + if (trap_state == TRAP_STATE_PRIMED) + trap_return++; + ret = lastval; + noerrexit = funcsave->noerrexit; + if (noreturnval) { + lastval = funcsave->lastval; + numpipestats = funcsave->numpipestats; + memcpy(pipestats, funcsave->pipestats, sizeof(int)*numpipestats); + } + } OLDHEAPS; + + unqueue_signals(); + + /* + * Exit with a tidy up. + * Only leave if we're at the end of the appropriate function --- + * not a nested function. As we usually skip the function body, + * the only likely case where we need that second test is + * when we have an "always" block. The endparamscope() has + * already happened, hence the "+1" here. + * + * If we are in an exit trap, finish it first... we wouldn't set + * exit_pending if we were already in one. + */ + if (exit_pending && exit_level >= locallevel+1 && !in_exit_trap) { + if (locallevel > forklevel) { + /* Still functions to return: force them to do so. */ + retflag = 1; + breaks = loops; + } else { + /* + * All functions finished: time to exit the shell. + * We already did the `stopmsg' test when the + * exit command was handled. + */ + stopmsg = 1; + zexit(exit_pending >> 1, 0); + } + } + + return ret; +} + +/* This finally executes a shell function and any function wrappers * + * defined by modules. This works by calling the wrapper function which * + * in turn has to call back this function with the arguments it gets. */ + +/**/ +mod_export void +runshfunc(Eprog prog, FuncWrap wrap, char *name) +{ + int cont, ouu; + char *ou; + + queue_signals(); + + ou = zalloc(ouu = underscoreused); + if (ou) + memcpy(ou, zunderscore, underscoreused); + + while (wrap) { + wrap->module->wrapper++; + cont = wrap->handler(prog, wrap->next, name); + wrap->module->wrapper--; + + if (!wrap->module->wrapper && + (wrap->module->node.flags & MOD_UNLOAD)) + unload_module(wrap->module); + + if (!cont) { + if (ou) + zfree(ou, ouu); + unqueue_signals(); + return; + } + wrap = wrap->next; + } + startparamscope(); + execode(prog, 1, 0, "shfunc"); /* handles signal unqueueing */ + if (ou) { + setunderscore(ou); + zfree(ou, ouu); + } + endparamscope(); + + unqueue_signals(); +} + +/* + * Search fpath for an undefined function. Finds the file, and returns the + * list of its contents. + * + * If test is 0, load the function. + * + * If test_only is 1, don't load function, just test for it: + * Non-null return means function was found + * + * *fdir points to path at which found (as passed in, not duplicated) + */ + +/**/ +Eprog +getfpfunc(char *s, int *ksh, char **fdir, char **alt_path, int test_only) +{ + char **pp, buf[PATH_MAX+1]; + off_t len; + off_t rlen; + char *d; + Eprog r; + int fd; + + pp = alt_path ? alt_path : fpath; + for (; *pp; pp++) { + if (strlen(*pp) + strlen(s) + 1 >= PATH_MAX) + continue; + if (**pp) + sprintf(buf, "%s/%s", *pp, s); + else + strcpy(buf, s); + if ((r = try_dump_file(*pp, s, buf, ksh, test_only))) { + if (fdir) + *fdir = *pp; + return r; + } + unmetafy(buf, NULL); + if (!access(buf, R_OK) && (fd = open(buf, O_RDONLY | O_NOCTTY)) != -1) { + struct stat st; + if (!fstat(fd, &st) && S_ISREG(st.st_mode) && + (len = lseek(fd, 0, 2)) != -1) { + if (test_only) { + close(fd); + if (fdir) + *fdir = *pp; + return &dummy_eprog; + } + d = (char *) zalloc(len + 1); + lseek(fd, 0, 0); + if ((rlen = read(fd, d, len)) >= 0) { + char *oldscriptname = scriptname; + + close(fd); + d[rlen] = '\0'; + d = metafy(d, rlen, META_REALLOC); + + scriptname = dupstring(s); + r = parse_string(d, 1); + scriptname = oldscriptname; + + if (fdir) + *fdir = *pp; + + zfree(d, len + 1); + + return r; + } else + close(fd); + + zfree(d, len + 1); + } else + close(fd); + } + } + return test_only ? NULL : &dummy_eprog; +} + +/* Handle the most common type of ksh-style autoloading, when doing a * + * zsh-style autoload. Given the list read from an autoload file, and the * + * name of the function being defined, check to see if the file consists * + * entirely of a single definition for that function. If so, use the * + * contents of that definition. Otherwise, use the entire file. */ + +/**/ +Eprog +stripkshdef(Eprog prog, char *name) +{ + Wordcode pc; + wordcode code; + char *ptr1, *ptr2; + + if (!prog) + return NULL; + pc = prog->prog; + code = *pc++; + if (wc_code(code) != WC_LIST || + (WC_LIST_TYPE(code) & (Z_SYNC|Z_END|Z_SIMPLE)) != (Z_SYNC|Z_END|Z_SIMPLE)) + return prog; + pc++; + code = *pc++; + if (wc_code(code) != WC_FUNCDEF || *pc != 1) + return prog; + + /* + * See if name of function requested (name) is same as + * name of function in word code. name may still have "-" + * tokenised. The word code shouldn't, as function names should be + * untokenised, but reports say it sometimes does. + */ + ptr1 = name; + ptr2 = ecrawstr(prog, pc + 1, NULL); + while (*ptr1 && *ptr2) { + if (*ptr1 != *ptr2 && *ptr1 != Dash && *ptr1 != '-' && + *ptr2 != Dash && *ptr2 != '-') + break; + ptr1++; + ptr2++; + } + if (*ptr1 || *ptr2) + return prog; + + { + Eprog ret; + Wordcode end = pc + WC_FUNCDEF_SKIP(code); + int sbeg = pc[2], nstrs = pc[3], nprg, npats = pc[4], plen, len, i; + Patprog *pp; + + pc += 5; + + nprg = end - pc; + plen = nprg * sizeof(wordcode); + len = plen + (npats * sizeof(Patprog)) + nstrs; + + if (prog->flags & EF_MAP) { + ret = prog; + free(prog->pats); + ret->pats = pp = (Patprog *) zalloc(npats * sizeof(Patprog)); + ret->prog = pc; + ret->strs = prog->strs + sbeg; + } else { + ret = (Eprog) zhalloc(sizeof(*ret)); + ret->flags = EF_HEAP; + ret->pats = pp = (Patprog *) zhalloc(len); + ret->prog = (Wordcode) (ret->pats + npats); + ret->strs = (char *) (ret->prog + nprg); + memcpy(ret->prog, pc, plen); + memcpy(ret->strs, prog->strs + sbeg, nstrs); + ret->dump = NULL; + } + ret->len = len; + ret->npats = npats; + for (i = npats; i--; pp++) + *pp = dummy_patprog1; + ret->shf = NULL; + + return ret; + } +} + +/* check to see if AUTOCD applies here */ + +/**/ +static char * +cancd(char *s) +{ + int nocdpath = s[0] == '.' && + (s[1] == '/' || !s[1] || (s[1] == '.' && (s[2] == '/' || !s[1]))); + char *t; + + if (*s != '/') { + char sbuf[PATH_MAX+1], **cp; + + if (cancd2(s)) + return s; + if (access(unmeta(s), X_OK) == 0) + return NULL; + if (!nocdpath) + for (cp = cdpath; *cp; cp++) { + if (strlen(*cp) + strlen(s) + 1 >= PATH_MAX) + continue; + if (**cp) + sprintf(sbuf, "%s/%s", *cp, s); + else + strcpy(sbuf, s); + if (cancd2(sbuf)) { + doprintdir = -1; + return dupstring(sbuf); + } + } + if ((t = cd_able_vars(s))) { + if (cancd2(t)) { + doprintdir = -1; + return t; + } + } + return NULL; + } + return cancd2(s) ? s : NULL; +} + +/**/ +static int +cancd2(char *s) +{ + struct stat buf; + char *us, *us2 = NULL; + int ret; + + /* + * If CHASEDOTS and CHASELINKS are not set, we want to rationalize the + * path by removing foo/.. combinations in the logical rather than + * the physical path. If either is set, we test the physical path. + */ + if (!isset(CHASEDOTS) && !isset(CHASELINKS)) { + if (*s != '/') + us = tricat(pwd[1] ? pwd : "", "/", s); + else + us = ztrdup(s); + fixdir(us2 = us); + } else + us = unmeta(s); + ret = !(access(us, X_OK) || stat(us, &buf) || !S_ISDIR(buf.st_mode)); + if (us2) + free(us2); + return ret; +} + +/**/ +void +execsave(void) +{ + struct execstack *es; + + es = (struct execstack *) zalloc(sizeof(struct execstack)); + es->list_pipe_pid = list_pipe_pid; + es->nowait = nowait; + es->pline_level = pline_level; + es->list_pipe_child = list_pipe_child; + es->list_pipe_job = list_pipe_job; + strcpy(es->list_pipe_text, list_pipe_text); + es->lastval = lastval; + es->noeval = noeval; + es->badcshglob = badcshglob; + es->cmdoutpid = cmdoutpid; + es->cmdoutval = cmdoutval; + es->use_cmdoutval = use_cmdoutval; + es->procsubstpid = procsubstpid; + es->trap_return = trap_return; + es->trap_state = trap_state; + es->trapisfunc = trapisfunc; + es->traplocallevel = traplocallevel; + es->noerrs = noerrs; + es->this_noerrexit = this_noerrexit; + es->underscore = ztrdup(zunderscore); + es->next = exstack; + exstack = es; + noerrs = cmdoutpid = 0; +} + +/**/ +void +execrestore(void) +{ + struct execstack *en = exstack; + + DPUTS(!exstack, "BUG: execrestore() without execsave()"); + + queue_signals(); + exstack = exstack->next; + + list_pipe_pid = en->list_pipe_pid; + nowait = en->nowait; + pline_level = en->pline_level; + list_pipe_child = en->list_pipe_child; + list_pipe_job = en->list_pipe_job; + strcpy(list_pipe_text, en->list_pipe_text); + lastval = en->lastval; + noeval = en->noeval; + badcshglob = en->badcshglob; + cmdoutpid = en->cmdoutpid; + cmdoutval = en->cmdoutval; + use_cmdoutval = en->use_cmdoutval; + procsubstpid = en->procsubstpid; + trap_return = en->trap_return; + trap_state = en->trap_state; + trapisfunc = en->trapisfunc; + traplocallevel = en->traplocallevel; + noerrs = en->noerrs; + this_noerrexit = en->this_noerrexit; + setunderscore(en->underscore); + zsfree(en->underscore); + free(en); + + unqueue_signals(); +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/glob.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/glob.c new file mode 100644 index 00000000..ed2c90bd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/glob.c @@ -0,0 +1,3913 @@ +/* + * glob.c - filename generation + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "glob.pro" + +#if defined(OFF_T_IS_64_BIT) && defined(__GNUC__) +# define ALIGN64 __attribute__((aligned(8))) +#else +# define ALIGN64 +#endif + +/* flag for CSHNULLGLOB */ + +typedef struct gmatch *Gmatch; + +struct gmatch { + /* Metafied file name */ + char *name; + /* Unmetafied file name; embedded nulls can't occur in file names */ + char *uname; + /* + * Array of sort strings: one for each GS_EXEC sort type in + * the glob qualifiers. + */ + char **sortstrs; + off_t size ALIGN64; + long atime; + long mtime; + long ctime; + long links; + off_t _size ALIGN64; + long _atime; + long _mtime; + long _ctime; + long _links; +#ifdef GET_ST_ATIME_NSEC + long ansec; + long _ansec; +#endif +#ifdef GET_ST_MTIME_NSEC + long mnsec; + long _mnsec; +#endif +#ifdef GET_ST_CTIME_NSEC + long cnsec; + long _cnsec; +#endif +}; + +#define GS_NAME 1 +#define GS_DEPTH 2 +#define GS_EXEC 4 + +#define GS_SHIFT_BASE 8 + +#define GS_SIZE (GS_SHIFT_BASE) +#define GS_ATIME (GS_SHIFT_BASE << 1) +#define GS_MTIME (GS_SHIFT_BASE << 2) +#define GS_CTIME (GS_SHIFT_BASE << 3) +#define GS_LINKS (GS_SHIFT_BASE << 4) + +#define GS_SHIFT 5 +#define GS__SIZE (GS_SIZE << GS_SHIFT) +#define GS__ATIME (GS_ATIME << GS_SHIFT) +#define GS__MTIME (GS_MTIME << GS_SHIFT) +#define GS__CTIME (GS_CTIME << GS_SHIFT) +#define GS__LINKS (GS_LINKS << GS_SHIFT) + +#define GS_DESC (GS_SHIFT_BASE << (2*GS_SHIFT)) +#define GS_NONE (GS_SHIFT_BASE << (2*GS_SHIFT+1)) + +#define GS_NORMAL (GS_SIZE | GS_ATIME | GS_MTIME | GS_CTIME | GS_LINKS) +#define GS_LINKED (GS_NORMAL << GS_SHIFT) + +/**/ +int badcshglob; + +/**/ +int pathpos; /* position in pathbuf (needed by pattern code) */ + +/* + * pathname buffer (needed by pattern code). + * It is currently believed the string in here is stored metafied and is + * unmetafied temporarily as needed by system calls. + */ + +/**/ +char *pathbuf; + +typedef struct stat *Statptr; /* This makes the Ultrix compiler happy. Go figure. */ + +/* modifier for unit conversions */ + +#define TT_DAYS 0 +#define TT_HOURS 1 +#define TT_MINS 2 +#define TT_WEEKS 3 +#define TT_MONTHS 4 +#define TT_SECONDS 5 + +#define TT_BYTES 0 +#define TT_POSIX_BLOCKS 1 +#define TT_KILOBYTES 2 +#define TT_MEGABYTES 3 +#define TT_GIGABYTES 4 +#define TT_TERABYTES 5 + + +typedef int (*TestMatchFunc) _((char *, struct stat *, off_t, char *)); + +struct qual { + struct qual *next; /* Next qualifier, must match */ + struct qual *or; /* Alternative set of qualifiers to match */ + TestMatchFunc func; /* Function to call to test match */ + off_t data ALIGN64; /* Argument passed to function */ + int sense; /* Whether asserting or negating */ + int amc; /* Flag for which time to test (a, m, c) */ + int range; /* Whether to test <, > or = (as per signum) */ + int units; /* Multiplier for time or size, respectively */ + char *sdata; /* currently only: expression to eval */ +}; + +/* Prefix, suffix for doing zle trickery */ + +/**/ +mod_export char *glob_pre, *glob_suf; + +/* Element of a glob sort */ +struct globsort { + /* Sort type */ + int tp; + /* Sort code to eval, if type is GS_EXEC */ + char *exec; +}; + +/* Maximum entries in sort array */ +#define MAX_SORTS (12) + +/* struct to easily save/restore current state */ + +struct globdata { + int gd_pathpos; + char *gd_pathbuf; + + int gd_matchsz; /* size of matchbuf */ + int gd_matchct; /* number of matches found */ + int gd_pathbufsz; /* size of pathbuf */ + int gd_pathbufcwd; /* where did we chdir()'ed */ + Gmatch gd_matchbuf; /* array of matches */ + Gmatch gd_matchptr; /* &matchbuf[matchct] */ + char *gd_colonmod; /* colon modifiers in qualifier list */ + + /* Qualifiers pertaining to current pattern */ + struct qual *gd_quals; + + /* Other state values for current pattern */ + int gd_qualct, gd_qualorct; + int gd_range, gd_amc, gd_units; + int gd_gf_nullglob, gd_gf_markdirs, gd_gf_noglobdots, gd_gf_listtypes; + int gd_gf_numsort; + int gd_gf_follow, gd_gf_sorts, gd_gf_nsorts; + struct globsort gd_gf_sortlist[MAX_SORTS]; + LinkList gd_gf_pre_words, gd_gf_post_words; + + char *gd_glob_pre, *gd_glob_suf; +}; + +/* The variable with the current globbing state and convenience macros */ + +static struct globdata curglobdata; + +#define matchsz (curglobdata.gd_matchsz) +#define matchct (curglobdata.gd_matchct) +#define pathbufsz (curglobdata.gd_pathbufsz) +#define pathbufcwd (curglobdata.gd_pathbufcwd) +#define matchbuf (curglobdata.gd_matchbuf) +#define matchptr (curglobdata.gd_matchptr) +#define colonmod (curglobdata.gd_colonmod) +#define quals (curglobdata.gd_quals) +#define qualct (curglobdata.gd_qualct) +#define qualorct (curglobdata.gd_qualorct) +#define g_range (curglobdata.gd_range) +#define g_amc (curglobdata.gd_amc) +#define g_units (curglobdata.gd_units) +#define gf_nullglob (curglobdata.gd_gf_nullglob) +#define gf_markdirs (curglobdata.gd_gf_markdirs) +#define gf_noglobdots (curglobdata.gd_gf_noglobdots) +#define gf_listtypes (curglobdata.gd_gf_listtypes) +#define gf_numsort (curglobdata.gd_gf_numsort) +#define gf_follow (curglobdata.gd_gf_follow) +#define gf_sorts (curglobdata.gd_gf_sorts) +#define gf_nsorts (curglobdata.gd_gf_nsorts) +#define gf_sortlist (curglobdata.gd_gf_sortlist) +#define gf_pre_words (curglobdata.gd_gf_pre_words) +#define gf_post_words (curglobdata.gd_gf_post_words) + +/* and macros for save/restore */ + +#define save_globstate(N) \ + do { \ + queue_signals(); \ + memcpy(&(N), &curglobdata, sizeof(struct globdata)); \ + (N).gd_pathpos = pathpos; \ + (N).gd_pathbuf = pathbuf; \ + (N).gd_glob_pre = glob_pre; \ + (N).gd_glob_suf = glob_suf; \ + pathbuf = NULL; \ + unqueue_signals(); \ + } while (0) + +#define restore_globstate(N) \ + do { \ + queue_signals(); \ + zfree(pathbuf, pathbufsz); \ + memcpy(&curglobdata, &(N), sizeof(struct globdata)); \ + pathpos = (N).gd_pathpos; \ + pathbuf = (N).gd_pathbuf; \ + glob_pre = (N).gd_glob_pre; \ + glob_suf = (N).gd_glob_suf; \ + unqueue_signals(); \ + } while (0) + +/* pathname component in filename patterns */ + +struct complist { + Complist next; + Patprog pat; + int closure; /* 1 if this is a (foo/)# */ + int follow; /* 1 to go thru symlinks */ +}; + +/* Add a component to pathbuf: This keeps track of how * + * far we are into a file name, since each path component * + * must be matched separately. */ + +/**/ +static void +addpath(char *s, int l) +{ + DPUTS(!pathbuf, "BUG: pathbuf not initialised"); + while (pathpos + l + 1 >= pathbufsz) + pathbuf = zrealloc(pathbuf, pathbufsz *= 2); + while (l--) + pathbuf[pathpos++] = *s++; + pathbuf[pathpos++] = '/'; + pathbuf[pathpos] = '\0'; +} + +/* stat the filename s appended to pathbuf. l should be true for lstat, * + * false for stat. If st is NULL, the file is only checked for existance. * + * s == "" is treated as s == ".". This is necessary since on most systems * + * foo/ can be used to reference a non-directory foo. Returns nonzero if * + * the file does not exists. */ + +/**/ +static int +statfullpath(const char *s, struct stat *st, int l) +{ + char buf[PATH_MAX+1]; + + DPUTS(strlen(s) + !*s + pathpos - pathbufcwd >= PATH_MAX, + "BUG: statfullpath(): pathname too long"); + strcpy(buf, pathbuf + pathbufcwd); + strcpy(buf + pathpos - pathbufcwd, s); + if (!*s && *buf) { + /* + * Don't add the '.' if the path so far is empty, since + * then we get bogus empty strings inserted as files. + */ + buf[pathpos - pathbufcwd] = '.'; + buf[pathpos - pathbufcwd + 1] = '\0'; + l = 0; + } + unmetafy(buf, NULL); + if (!st) { + char lbuf[1]; + return access(buf, F_OK) && (!l || readlink(buf, lbuf, 1) < 0); + } + return l ? lstat(buf, st) : stat(buf, st); +} + +/* This may be set by qualifier functions to an array of strings to insert + * into the list instead of the original string. */ + +static char **inserts; + +/* add a match to the list */ + +/**/ +static void +insert(char *s, int checked) +{ + struct stat buf, buf2, *bp; + char *news = s; + int statted = 0; + + queue_signals(); + inserts = NULL; + + if (gf_listtypes || gf_markdirs) { + /* Add the type marker to the end of the filename */ + mode_t mode; + checked = statted = 1; + if (statfullpath(s, &buf, 1)) { + unqueue_signals(); + return; + } + mode = buf.st_mode; + if (gf_follow) { + if (!S_ISLNK(mode) || statfullpath(s, &buf2, 0)) + memcpy(&buf2, &buf, sizeof(buf)); + statted |= 2; + mode = buf2.st_mode; + } + if (gf_listtypes || S_ISDIR(mode)) { + int ll = strlen(s); + + news = (char *) hcalloc(ll + 2); + strcpy(news, s); + news[ll] = file_type(mode); + news[ll + 1] = '\0'; + } + } + if (qualct || qualorct) { + /* Go through the qualifiers, rejecting the file if appropriate */ + struct qual *qo, *qn; + + if (!statted && statfullpath(s, &buf, 1)) { + unqueue_signals(); + return; + } + news = dyncat(pathbuf, news); + + statted = 1; + qo = quals; + for (qn = qo; qn && qn->func;) { + g_range = qn->range; + g_amc = qn->amc; + g_units = qn->units; + if ((qn->sense & 2) && !(statted & 2)) { + /* If (sense & 2), we're following links */ + if (!S_ISLNK(buf.st_mode) || statfullpath(s, &buf2, 0)) + memcpy(&buf2, &buf, sizeof(buf)); + statted |= 2; + } + bp = (qn->sense & 2) ? &buf2 : &buf; + /* Reject the file if the function returned zero * + * and the sense was positive (sense&1 == 0), or * + * vice versa. */ + if ((!((qn->func) (news, bp, qn->data, qn->sdata)) + ^ qn->sense) & 1) { + /* Try next alternative, or return if there are no more */ + if (!(qo = qo->or)) { + unqueue_signals(); + return; + } + qn = qo; + continue; + } + qn = qn->next; + } + } else if (!checked) { + if (statfullpath(s, &buf, 1)) { + unqueue_signals(); + return; + } + statted = 1; + news = dyncat(pathbuf, news); + } else + news = dyncat(pathbuf, news); + + while (!inserts || (news = dupstring(*inserts++))) { + if (colonmod) { + /* Handle the remainder of the qualifier: e.g. (:r:s/foo/bar/). */ + char *mod = colonmod; + modify(&news, &mod); + } + if (!statted && (gf_sorts & GS_NORMAL)) { + statfullpath(s, &buf, 1); + statted = 1; + } + if (!(statted & 2) && (gf_sorts & GS_LINKED)) { + if (statted) { + if (!S_ISLNK(buf.st_mode) || statfullpath(s, &buf2, 0)) + memcpy(&buf2, &buf, sizeof(buf)); + } else if (statfullpath(s, &buf2, 0)) + statfullpath(s, &buf2, 1); + statted |= 2; + } + matchptr->name = news; + if (statted & 1) { + matchptr->size = buf.st_size; + matchptr->atime = buf.st_atime; + matchptr->mtime = buf.st_mtime; + matchptr->ctime = buf.st_ctime; + matchptr->links = buf.st_nlink; +#ifdef GET_ST_ATIME_NSEC + matchptr->ansec = GET_ST_ATIME_NSEC(buf); +#endif +#ifdef GET_ST_MTIME_NSEC + matchptr->mnsec = GET_ST_MTIME_NSEC(buf); +#endif +#ifdef GET_ST_CTIME_NSEC + matchptr->cnsec = GET_ST_CTIME_NSEC(buf); +#endif + } + if (statted & 2) { + matchptr->_size = buf2.st_size; + matchptr->_atime = buf2.st_atime; + matchptr->_mtime = buf2.st_mtime; + matchptr->_ctime = buf2.st_ctime; + matchptr->_links = buf2.st_nlink; +#ifdef GET_ST_ATIME_NSEC + matchptr->_ansec = GET_ST_ATIME_NSEC(buf2); +#endif +#ifdef GET_ST_MTIME_NSEC + matchptr->_mnsec = GET_ST_MTIME_NSEC(buf2); +#endif +#ifdef GET_ST_CTIME_NSEC + matchptr->_cnsec = GET_ST_CTIME_NSEC(buf2); +#endif + } + matchptr++; + + if (++matchct == matchsz) { + matchbuf = (Gmatch)zrealloc((char *)matchbuf, + sizeof(struct gmatch) * (matchsz *= 2)); + + matchptr = matchbuf + matchct; + } + if (!inserts) + break; + } + unqueue_signals(); + return; +} + +/* Do the globbing: scanner is called recursively * + * with successive bits of the path until we've * + * tried all of it. */ + +/**/ +static void +scanner(Complist q, int shortcircuit) +{ + Patprog p; + int closure; + int pbcwdsav = pathbufcwd; + int errssofar = errsfound; + struct dirsav ds; + + if (!q || errflag) + return; + init_dirsav(&ds); + + if ((closure = q->closure)) { + /* (foo/)# - match zero or more dirs */ + if (q->closure == 2) /* (foo/)## - match one or more dirs */ + q->closure = 1; + else { + scanner(q->next, shortcircuit); + if (shortcircuit && shortcircuit == matchct) + return; + } + } + p = q->pat; + /* Now the actual matching for the current path section. */ + if (p->flags & PAT_PURES) { + /* + * It's a straight string to the end of the path section. + */ + char *str = (char *)p + p->startoff; + int l = p->patmlen; + + if (l + !l + pathpos - pathbufcwd >= PATH_MAX) { + int err; + + if (l >= PATH_MAX) + return; + err = lchdir(unmeta(pathbuf + pathbufcwd), &ds, 0); + if (err == -1) + return; + if (err) { + zerr("current directory lost during glob"); + return; + } + pathbufcwd = pathpos; + } + if (q->next) { + /* Not the last path section. Just add it to the path. */ + int oppos = pathpos; + + if (!errflag) { + int add = 1; + + if (q->closure && *pathbuf) { + if (!strcmp(str, ".")) + add = 0; + else if (!strcmp(str, "..")) { + struct stat sc, sr; + + add = (stat("/", &sr) || stat(unmeta(pathbuf), &sc) || + sr.st_ino != sc.st_ino || + sr.st_dev != sc.st_dev); + } + } + if (add) { + addpath(str, l); + if (!closure || !statfullpath("", NULL, 1)) { + scanner((q->closure) ? q : q->next, shortcircuit); + if (shortcircuit && shortcircuit == matchct) + return; + } + pathbuf[pathpos = oppos] = '\0'; + } + } + } else { + if (str[l]) + str = dupstrpfx(str, l); + insert(str, 0); + if (shortcircuit && shortcircuit == matchct) + return; + } + } else { + /* Do pattern matching on current path section. */ + char *fn = pathbuf[pathbufcwd] ? unmeta(pathbuf + pathbufcwd) : "."; + int dirs = !!q->next; + DIR *lock = opendir(fn); + char *subdirs = NULL; + int subdirlen = 0; + + if (lock == NULL) + return; + while ((fn = zreaddir(lock, 1)) && !errflag) { + /* prefix and suffix are zle trickery */ + if (!dirs && !colonmod && + ((glob_pre && !strpfx(glob_pre, fn)) + || (glob_suf && !strsfx(glob_suf, fn)))) + continue; + errsfound = errssofar; + if (pattry(p, fn)) { + /* if this name matchs the pattern... */ + if (pbcwdsav == pathbufcwd && + strlen(fn) + pathpos - pathbufcwd >= PATH_MAX) { + int err; + + DPUTS(pathpos == pathbufcwd, + "BUG: filename longer than PATH_MAX"); + err = lchdir(unmeta(pathbuf + pathbufcwd), &ds, 0); + if (err == -1) + break; + if (err) { + zerr("current directory lost during glob"); + break; + } + pathbufcwd = pathpos; + } + if (dirs) { + int l; + + /* + * If not the last component in the path: + * + * If we made an approximation in the new path segment, + * then it is possible we made too many errors. For + * example, (ab)#(cb)# will match the directory abcb + * with one error if allowed to, even though it can + * match with none. This will stop later parts of the + * path matching, so we need to check by reducing the + * maximum number of errors and seeing if the directory + * still matches. Luckily, this is not a terribly + * common case, since complex patterns typically occur + * in the last part of the path which is not affected + * by this problem. + */ + if (errsfound > errssofar) { + forceerrs = errsfound - 1; + while (forceerrs >= errssofar) { + errsfound = errssofar; + if (!pattry(p, fn)) + break; + forceerrs = errsfound - 1; + } + errsfound = forceerrs + 1; + forceerrs = -1; + } + if (closure) { + /* if matching multiple directories */ + struct stat buf; + + if (statfullpath(fn, &buf, !q->follow)) { + if (errno != ENOENT && errno != EINTR && + errno != ENOTDIR && !errflag) { + zwarn("%e: %s", errno, fn); + } + continue; + } + if (!S_ISDIR(buf.st_mode)) + continue; + } + l = strlen(fn) + 1; + subdirs = hrealloc(subdirs, subdirlen, subdirlen + l + + sizeof(int)); + strcpy(subdirs + subdirlen, fn); + subdirlen += l; + /* store the count of errors made so far, too */ + memcpy(subdirs + subdirlen, (char *)&errsfound, + sizeof(int)); + subdirlen += sizeof(int); + } else { + /* if the last filename component, just add it */ + insert(fn, 1); + if (shortcircuit && shortcircuit == matchct) { + closedir(lock); + return; + } + } + } + } + closedir(lock); + if (subdirs) { + int oppos = pathpos; + + for (fn = subdirs; fn < subdirs+subdirlen; ) { + int l = strlen(fn); + addpath(fn, l); + fn += l + 1; + memcpy((char *)&errsfound, fn, sizeof(int)); + fn += sizeof(int); + /* scan next level */ + scanner((q->closure) ? q : q->next, shortcircuit); + if (shortcircuit && shortcircuit == matchct) + return; + pathbuf[pathpos = oppos] = '\0'; + } + hrealloc(subdirs, subdirlen, 0); + } + } + if (pbcwdsav < pathbufcwd) { + if (restoredir(&ds)) + zerr("current directory lost during glob"); + zsfree(ds.dirname); + if (ds.dirfd >= 0) + close(ds.dirfd); + pathbufcwd = pbcwdsav; + } + return; +} + +/* This function tokenizes a zsh glob pattern */ + +/**/ +static Complist +parsecomplist(char *instr) +{ + Patprog p1; + Complist l1; + char *str; + int compflags = gf_noglobdots ? (PAT_FILE|PAT_NOGLD) : PAT_FILE; + + if (instr[0] == Star && instr[1] == Star) { + int shortglob = 0; + if (instr[2] == '/' || (instr[2] == Star && instr[3] == '/') + || (shortglob = isset(GLOBSTARSHORT))) { + /* Match any number of directories. */ + int follow; + + /* with three stars, follow symbolic links */ + follow = (instr[2] == Star); + /* + * With GLOBSTARSHORT, leave a star in place for the + * pattern inside the directory. + */ + instr += ((shortglob ? 1 : 3) + follow); + + /* Now get the next path component if there is one. */ + l1 = (Complist) zhalloc(sizeof *l1); + if ((l1->next = parsecomplist(instr)) == NULL) { + errflag |= ERRFLAG_ERROR; + return NULL; + } + l1->pat = patcompile(NULL, compflags | PAT_ANY, NULL); + l1->closure = 1; /* ...zero or more times. */ + l1->follow = follow; + return l1; + } + } + + /* Parse repeated directories such as (dir/)# and (dir/)## */ + if (*(str = instr) == zpc_special[ZPC_INPAR] && + !skipparens(Inpar, Outpar, (char **)&str) && + *str == zpc_special[ZPC_HASH] && str[-2] == '/') { + instr++; + if (!(p1 = patcompile(instr, compflags, &instr))) + return NULL; + if (instr[0] == '/' && instr[1] == Outpar && instr[2] == Pound) { + int pdflag = 0; + + instr += 3; + if (*instr == Pound) { + pdflag = 1; + instr++; + } + l1 = (Complist) zhalloc(sizeof *l1); + l1->pat = p1; + /* special case (/)# to avoid infinite recursion */ + l1->closure = (*((char *)p1 + p1->startoff)) ? 1 + pdflag : 0; + l1->follow = 0; + l1->next = parsecomplist(instr); + return (l1->pat) ? l1 : NULL; + } + } else { + /* parse single path component */ + if (!(p1 = patcompile(instr, compflags|PAT_FILET, &instr))) + return NULL; + /* then do the remaining path components */ + if (*instr == '/' || !*instr) { + int ef = *instr == '/'; + + l1 = (Complist) zhalloc(sizeof *l1); + l1->pat = p1; + l1->closure = 0; + l1->next = ef ? parsecomplist(instr+1) : NULL; + return (ef && !l1->next) ? NULL : l1; + } + } + errflag |= ERRFLAG_ERROR; + return NULL; +} + +/* turn a string into a Complist struct: this has path components */ + +/**/ +static Complist +parsepat(char *str) +{ + long assert; + int ignore; + + patcompstart(); + /* + * Check for initial globbing flags, so that they don't form + * a bogus path component. + */ + if ((*str == zpc_special[ZPC_INPAR] && str[1] == zpc_special[ZPC_HASH]) || + (*str == zpc_special[ZPC_KSH_AT] && str[1] == Inpar && + str[2] == zpc_special[ZPC_HASH])) { + str += (*str == Inpar) ? 2 : 3; + if (!patgetglobflags(&str, &assert, &ignore)) + return NULL; + } + + /* Now there is no (#X) in front, we can check the path. */ + if (!pathbuf) + pathbuf = zalloc(pathbufsz = PATH_MAX+1); + DPUTS(pathbufcwd, "BUG: glob changed directory"); + if (*str == '/') { /* pattern has absolute path */ + str++; + pathbuf[0] = '/'; + pathbuf[pathpos = 1] = '\0'; + } else /* pattern is relative to pwd */ + pathbuf[pathpos = 0] = '\0'; + + return parsecomplist(str); +} + +/* get number after qualifier */ + +/**/ +static off_t +qgetnum(char **s) +{ + off_t v = 0; + + if (!idigit(**s)) { + zerr("number expected"); + return 0; + } + while (idigit(**s)) + v = v * 10 + *(*s)++ - '0'; + return v; +} + +/* get mode spec after qualifier */ + +/**/ +static zlong +qgetmodespec(char **s) +{ + zlong yes = 0, no = 0, val, mask, t; + char *p = *s, c, how, end; + + if ((c = *p) == '=' || c == Equals || c == '+' || c == '-' || + c == '?' || c == Quest || (c >= '0' && c <= '7')) { + end = 0; + c = 0; + } else { + end = (c == '<' ? '>' : + (c == '[' ? ']' : + (c == '{' ? '}' : + (c == Inang ? Outang : + (c == Inbrack ? Outbrack : + (c == Inbrace ? Outbrace : c)))))); + p++; + } + do { + mask = 0; + while (((c = *p) == 'u' || c == 'g' || c == 'o' || c == 'a') && end) { + switch (c) { + case 'o': mask |= 01007; break; + case 'g': mask |= 02070; break; + case 'u': mask |= 04700; break; + case 'a': mask |= 07777; break; + } + p++; + } + how = ((c == '+' || c == '-') ? c : '='); + if (c == '+' || c == '-' || c == '=' || c == Equals) + p++; + val = 0; + if (mask) { + while ((c = *p++) != ',' && c != end) { + switch (c) { + case 'x': val |= 00111; break; + case 'w': val |= 00222; break; + case 'r': val |= 00444; break; + case 's': val |= 06000; break; + case 't': val |= 01000; break; + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + t = ((zlong) c - '0'); + val |= t | (t << 3) | (t << 6); + break; + default: + zerr("invalid mode specification"); + return 0; + } + } + if (how == '=' || how == '+') { + yes |= val & mask; + val = ~val; + } + if (how == '=' || how == '-') + no |= val & mask; + } else if (!(end && c == end) && c != ',' && c) { + t = 07777; + while ((c = *p) == '?' || c == Quest || + (c >= '0' && c <= '7')) { + if (c == '?' || c == Quest) { + t = (t << 3) | 7; + val <<= 3; + } else { + t <<= 3; + val = (val << 3) | ((zlong) c - '0'); + } + p++; + } + if (end && c != end && c != ',') { + zerr("invalid mode specification"); + return 0; + } + if (how == '=') { + yes = (yes & ~t) | val; + no = (no & ~t) | (~val & ~t); + } else if (how == '+') + yes |= val; + else + no |= val; + } else { + zerr("invalid mode specification"); + return 0; + } + } while (end && c != end); + + *s = p; + return ((yes & 07777) | ((no & 07777) << 12)); +} + +static int +gmatchcmp(Gmatch a, Gmatch b) +{ + int i; + off_t r = 0L; + struct globsort *s; + char **asortstrp = NULL, **bsortstrp = NULL; + + for (i = gf_nsorts, s = gf_sortlist; i; i--, s++) { + switch (s->tp & ~GS_DESC) { + case GS_NAME: + r = zstrcmp(b->uname, a->uname, + gf_numsort ? SORTIT_NUMERICALLY : 0); + break; + case GS_DEPTH: + { + char *aptr = a->name, *bptr = b->name; + int slasha = 0, slashb = 0; + /* Count slashes. Trailing slashes don't count. */ + while (*aptr && *aptr == *bptr) + aptr++, bptr++; + /* Like I just said... */ + if ((!*aptr || !*bptr) && aptr > a->name && aptr[-1] == '/') + aptr--, bptr--; + if (*aptr) + for (; aptr[1]; aptr++) + if (*aptr == '/') { + slasha = 1; + break; + } + if (*bptr) + for (; bptr[1]; bptr++) + if (*bptr == '/') { + slashb = 1; + break; + } + r = slasha - slashb; + } + break; + case GS_EXEC: + if (!asortstrp) { + asortstrp = a->sortstrs; + bsortstrp = b->sortstrs; + } else { + asortstrp++; + bsortstrp++; + } + r = zstrcmp(*bsortstrp, *asortstrp, + gf_numsort ? SORTIT_NUMERICALLY : 0); + break; + case GS_SIZE: + r = b->size - a->size; + break; + case GS_ATIME: + r = a->atime - b->atime; +#ifdef GET_ST_ATIME_NSEC + if (!r) + r = a->ansec - b->ansec; +#endif + break; + case GS_MTIME: + r = a->mtime - b->mtime; +#ifdef GET_ST_MTIME_NSEC + if (!r) + r = a->mnsec - b->mnsec; +#endif + break; + case GS_CTIME: + r = a->ctime - b->ctime; +#ifdef GET_ST_CTIME_NSEC + if (!r) + r = a->cnsec - b->cnsec; +#endif + break; + case GS_LINKS: + r = b->links - a->links; + break; + case GS__SIZE: + r = b->_size - a->_size; + break; + case GS__ATIME: + r = a->_atime - b->_atime; +#ifdef GET_ST_ATIME_NSEC + if (!r) + r = a->_ansec - b->_ansec; +#endif + break; + case GS__MTIME: + r = a->_mtime - b->_mtime; +#ifdef GET_ST_MTIME_NSEC + if (!r) + r = a->_mnsec - b->_mnsec; +#endif + break; + case GS__CTIME: + r = a->_ctime - b->_ctime; +#ifdef GET_ST_CTIME_NSEC + if (!r) + r = a->_cnsec - b->_cnsec; +#endif + break; + case GS__LINKS: + r = b->_links - a->_links; + break; + } + if (r) + return (s->tp & GS_DESC) ? + (r < 0L ? 1 : -1) : + (r > 0L ? 1 : -1); + } + return 0; +} + +/* + * Duplicate a list of qualifiers using the `next' linkage (not the + * `or' linkage). Return the head element and set *last (if last non-NULL) + * to point to the last element of the new list. All allocation is on the + * heap (or off the heap?) + */ +static struct qual *dup_qual_list(struct qual *orig, struct qual **lastp) +{ + struct qual *qfirst = NULL, *qlast = NULL; + + while (orig) { + struct qual *qnew = (struct qual *)zhalloc(sizeof(struct qual)); + *qnew = *orig; + qnew->next = qnew->or = NULL; + + if (!qfirst) + qfirst = qnew; + if (qlast) + qlast->next = qnew; + qlast = qnew; + + orig = orig->next; + } + + if (lastp) + *lastp = qlast; + return qfirst; +} + + +/* + * Get a glob string for execution, following e, P or + qualifiers. + * Pointer is character after the e, P or +. + */ + +/**/ +static char * +glob_exec_string(char **sp) +{ + char sav, *tt, *sdata, *s = *sp; + int plus; + + if (s[-1] == '+') { + plus = 0; + tt = itype_end(s, IIDENT, 0); + if (tt == s) + { + zerr("missing identifier after `+'"); + return NULL; + } + } else { + tt = get_strarg(s, &plus); + if (!*tt) + { + zerr("missing end of string"); + return NULL; + } + } + + sav = *tt; + *tt = '\0'; + sdata = dupstring(s + plus); + untokenize(sdata); + *tt = sav; + if (sav) + *sp = tt + plus; + else + *sp = tt; + + return sdata; +} + +/* + * Insert a glob match. + * If there were words to prepend given by the P glob qualifier, do so. + */ +static void +insert_glob_match(LinkList list, LinkNode next, char *data) +{ + if (gf_pre_words) { + LinkNode added; + for (added = firstnode(gf_pre_words); added; incnode(added)) { + next = insertlinknode(list, next, dupstring(getdata(added))); + } + } + + next = insertlinknode(list, next, data); + + if (gf_post_words) { + LinkNode added; + for (added = firstnode(gf_post_words); added; incnode(added)) { + next = insertlinknode(list, next, dupstring(getdata(added))); + } + } +} + +/* + * Return + * 1 if str ends in bare glob qualifiers + * 2 if str ends in non-bare glob qualifiers (#q) + * 0 otherwise. + * + * str is the string to check. + * sl is its length (to avoid recalculation). + * nobareglob is 1 if bare glob qualifiers are not allowed. + * *sp, if sp is not null, will be a pointer to the opening parenthesis. + */ + +/**/ +int +checkglobqual(char *str, int sl, int nobareglob, char **sp) +{ + char *s; + int paren, ret = 1; + + if (str[sl - 1] != Outpar) + return 0; + + /* Check these are really qualifiers, not a set of * + * alternatives or exclusions. We can be more * + * lenient with an explicit (#q) than with a bare * + * set of qualifiers. */ + paren = 0; + for (s = str + sl - 2; *s && (*s != Inpar || paren); s--) { + switch (*s) { + case Outpar: + paren++; /*FALLTHROUGH*/ + case Bar: + if (!zpc_disables[ZPC_BAR]) + nobareglob = 1; + break; + case Tilde: + if (isset(EXTENDEDGLOB) && !zpc_disables[ZPC_TILDE]) + nobareglob = 1; + break; + case Inpar: + paren--; + break; + } + if (s == str) + break; + } + if (*s != Inpar) + return 0; + if (isset(EXTENDEDGLOB) && !zpc_disables[ZPC_HASH] && s[1] == Pound) { + if (s[2] != 'q') + return 0; + ret = 2; + } else if (nobareglob) + return 0; + + if (sp) + *sp = s; + + return ret; +} + +/* Main entry point to the globbing code for filename globbing. * + * np points to a node in the list which will be expanded * + * into a series of nodes. */ + +/**/ +void +zglob(LinkList list, LinkNode np, int nountok) +{ + struct qual *qo, *qn, *ql; + LinkNode node = prevnode(np); + char *str; /* the pattern */ + int sl; /* length of the pattern */ + Complist q; /* pattern after parsing */ + char *ostr = (char *)getdata(np); /* the pattern before the parser */ + /* chops it up */ + int first = 0, end = -1; /* index of first match to return */ + /* and index+1 of the last match */ + struct globdata saved; /* saved glob state */ + int nobareglob = !isset(BAREGLOBQUAL); + int shortcircuit = 0; /* How many files to match; */ + /* 0 means no limit */ + + if (unset(GLOBOPT) || !haswilds(ostr) || unset(EXECOPT)) { + if (!nountok) + untokenize(ostr); + return; + } + save_globstate(saved); + + str = dupstring(ostr); + uremnode(list, np); + + /* quals will hold the complete list of qualifiers (file static). */ + quals = NULL; + /* + * qualct and qualorct indicate we have qualifiers in the last + * alternative, or a set of alternatives, respectively. They + * are not necessarily an accurate count, however. + */ + qualct = qualorct = 0; + /* + * colonmod is a concatenated list of all colon modifiers found in + * all sets of qualifiers. + */ + colonmod = NULL; + /* The gf_* flags are qualifiers which are applied globally. */ + gf_nullglob = isset(NULLGLOB); + gf_markdirs = isset(MARKDIRS); + gf_listtypes = gf_follow = 0; + gf_noglobdots = unset(GLOBDOTS); + gf_numsort = isset(NUMERICGLOBSORT); + gf_sorts = gf_nsorts = 0; + gf_pre_words = gf_post_words = NULL; + + /* Check for qualifiers */ + while (!nobareglob || + (isset(EXTENDEDGLOB) && !zpc_disables[ZPC_HASH])) { + struct qual *newquals; + char *s; + int sense, qualsfound; + off_t data; + char *sdata, *newcolonmod, *ptr; + int (*func) _((char *, Statptr, off_t, char *)); + + /* + * Initialise state variables for current file pattern. + * newquals is the root for the linked list of all qualifiers. + * qo is the root of the current list of alternatives. + * ql is the end of the current alternative where the `next' will go. + * qn is the current qualifier node to be added. + * + * Here is an attempt at a diagram. An `or' is added horizontally + * to the top line, a `next' at the bottom of the right hand line. + * `qn' is usually NULL unless a new `or' has just been added. + * + * quals -> x -> x -> qo + * | | | + * x x x + * | | + * x ql + * + * In fact, after each loop the complete set is in the file static + * `quals'. Then, if we have a second set of qualifiers, we merge + * the lists together. This is only tricky if one or both have an + * `or' in them; then we need to distribute over all alternatives. + */ + newquals = qo = qn = ql = NULL; + + sl = strlen(str); + if (!(qualsfound = checkglobqual(str, sl, nobareglob, &s))) + break; + + /* Real qualifiers found. */ + nobareglob = 1; + sense = 0; /* bit 0 for match (0)/don't match (1) */ + /* bit 1 for follow links (2), don't (0) */ + data = 0; /* Any numerical argument required */ + sdata = NULL; /* Any list argument required */ + newcolonmod = NULL; /* Contains trailing colon modifiers */ + + str[sl-1] = 0; + *s++ = 0; + if (qualsfound == 2) + s += 2; + for (ptr = s; *ptr; ptr++) + if (*ptr == Dash) + *ptr = '-'; + while (*s && !newcolonmod) { + func = (int (*) _((char *, Statptr, off_t, char *)))0; + if (*s == ',') { + /* A comma separates alternative sets of qualifiers */ + s++; + sense = 0; + if (qualct) { + qn = (struct qual *)hcalloc(sizeof *qn); + qo->or = qn; + qo = qn; + qualorct++; + qualct = 0; + ql = NULL; + } + } else { + switch (*s++) { + case ':': + /* Remaining arguments are history-type * + * colon substitutions, handled separately. */ + newcolonmod = s - 1; + untokenize(newcolonmod); + if (colonmod) { + /* remember we're searching backwards */ + colonmod = dyncat(newcolonmod, colonmod); + } else + colonmod = newcolonmod; + break; + case Hat: + case '^': + /* Toggle sense: go from positive to * + * negative match and vice versa. */ + sense ^= 1; + break; + case '-': + case Dash: + /* Toggle matching of symbolic links */ + sense ^= 2; + break; + case '@': + /* Match symbolic links */ + func = qualislnk; + break; + case Equals: + case '=': + /* Match sockets */ + func = qualissock; + break; + case 'p': + /* Match named pipes */ + func = qualisfifo; + break; + case '/': + /* Match directories */ + func = qualisdir; + break; + case '.': + /* Match regular files */ + func = qualisreg; + break; + case '%': + /* Match special files: block, * + * character or any device */ + if (*s == 'b') + s++, func = qualisblk; + else if (*s == 'c') + s++, func = qualischr; + else + func = qualisdev; + break; + case Star: + /* Match executable plain files */ + func = qualiscom; + break; + case 'R': + /* Match world-readable files */ + func = qualflags; + data = 0004; + break; + case 'W': + /* Match world-writeable files */ + func = qualflags; + data = 0002; + break; + case 'X': + /* Match world-executable files */ + func = qualflags; + data = 0001; + break; + case 'A': + func = qualflags; + data = 0040; + break; + case 'I': + func = qualflags; + data = 0020; + break; + case 'E': + func = qualflags; + data = 0010; + break; + case 'r': + /* Match files readable by current process */ + func = qualflags; + data = 0400; + break; + case 'w': + /* Match files writeable by current process */ + func = qualflags; + data = 0200; + break; + case 'x': + /* Match files executable by current process */ + func = qualflags; + data = 0100; + break; + case 's': + /* Match setuid files */ + func = qualflags; + data = 04000; + break; + case 'S': + /* Match setgid files */ + func = qualflags; + data = 02000; + break; + case 't': + func = qualflags; + data = 01000; + break; + case 'd': + /* Match device files by device number * + * (as given by stat's st_dev element). */ + func = qualdev; + data = qgetnum(&s); + break; + case 'l': + /* Match files with the given no. of hard links */ + func = qualnlink; + g_amc = -1; + goto getrange; + case 'U': + /* Match files owned by effective user ID */ + func = qualuid; + data = geteuid(); + break; + case 'G': + /* Match files owned by effective group ID */ + func = qualgid; + data = getegid(); + break; + case 'u': + /* Match files owned by given user id */ + func = qualuid; + /* either the actual uid... */ + if (idigit(*s)) + data = qgetnum(&s); + else { + /* ... or a user name */ + char sav, *tt; + int arglen; + + /* Find matching delimiters */ + tt = get_strarg(s, &arglen); + if (!*tt) { + zerr("missing delimiter for 'u' glob qualifier"); + data = 0; + } else { +#ifdef USE_GETPWNAM + struct passwd *pw; + sav = *tt; + *tt = '\0'; + + if ((pw = getpwnam(s + arglen))) + data = pw->pw_uid; + else { + zerr("unknown username '%s'", s + arglen); + data = 0; + } + *tt = sav; +#else /* !USE_GETPWNAM */ + sav = *tt; + *tt = '\0'; + zerr("unable to resolve non-numeric username '%s'", s + arglen); + *tt = sav; + data = 0; +#endif /* !USE_GETPWNAM */ + if (sav) + s = tt + arglen; + else + s = tt; + } + } + break; + case 'g': + /* Given gid or group id... works like `u' */ + func = qualgid; + /* either the actual gid... */ + if (idigit(*s)) + data = qgetnum(&s); + else { + /* ...or a delimited group name. */ + char sav, *tt; + int arglen; + + tt = get_strarg(s, &arglen); + if (!*tt) { + zerr("missing delimiter for 'g' glob qualifier"); + data = 0; + } else { +#ifdef USE_GETGRNAM + struct group *gr; + sav = *tt; + *tt = '\0'; + + if ((gr = getgrnam(s + arglen))) + data = gr->gr_gid; + else { + zerr("unknown group"); + data = 0; + } + *tt = sav; +#else /* !USE_GETGRNAM */ + sav = *tt; + zerr("unknown group"); + data = 0; +#endif /* !USE_GETGRNAM */ + if (sav) + s = tt + arglen; + else + s = tt; + } + } + break; + case 'f': + /* Match modes with chmod-spec. */ + func = qualmodeflags; + data = qgetmodespec(&s); + break; + case 'F': + func = qualnonemptydir; + break; + case 'M': + /* Mark directories with a / */ + if ((gf_markdirs = !(sense & 1))) + gf_follow = sense & 2; + break; + case 'T': + /* Mark types in a `ls -F' type fashion */ + if ((gf_listtypes = !(sense & 1))) + gf_follow = sense & 2; + break; + case 'N': + /* Nullglob: remove unmatched patterns. */ + gf_nullglob = !(sense & 1); + break; + case 'D': + /* Glob dots: match leading dots implicitly */ + gf_noglobdots = sense & 1; + break; + case 'n': + /* Numeric glob sort */ + gf_numsort = !(sense & 1); + break; + case 'Y': + { + /* Short circuit: limit number of matches */ + const char *s_saved = s; + shortcircuit = !(sense & 1); + if (shortcircuit) { + /* Parse the argument. */ + data = qgetnum(&s); + if ((shortcircuit = data) != data) { + /* Integer overflow */ + zerr("value too big: Y%s", s_saved); + restore_globstate(saved); + return; + } + } + break; + } + case 'a': + /* Access time in given range */ + g_amc = 0; + func = qualtime; + goto getrange; + case 'm': + /* Modification time in given range */ + g_amc = 1; + func = qualtime; + goto getrange; + case 'c': + /* Inode creation time in given range */ + g_amc = 2; + func = qualtime; + goto getrange; + case 'L': + /* File size (Length) in given range */ + func = qualsize; + g_amc = -1; + /* Get size multiplier */ + g_units = TT_BYTES; + if (*s == 'p' || *s == 'P') + g_units = TT_POSIX_BLOCKS, ++s; + else if (*s == 'k' || *s == 'K') + g_units = TT_KILOBYTES, ++s; + else if (*s == 'm' || *s == 'M') + g_units = TT_MEGABYTES, ++s; +#if defined(ZSH_64_BIT_TYPE) || defined(LONG_IS_64_BIT) + else if (*s == 'g' || *s == 'G') + g_units = TT_GIGABYTES, ++s; + else if (*s == 't' || *s == 'T') + g_units = TT_TERABYTES, ++s; +#endif + getrange: + /* Get time multiplier */ + if (g_amc >= 0) { + g_units = TT_DAYS; + if (*s == 'h') + g_units = TT_HOURS, ++s; + else if (*s == 'm') + g_units = TT_MINS, ++s; + else if (*s == 'w') + g_units = TT_WEEKS, ++s; + else if (*s == 'M') + g_units = TT_MONTHS, ++s; + else if (*s == 's') + g_units = TT_SECONDS, ++s; + else if (*s == 'd') + ++s; + } + /* See if it's greater than, equal to, or less than */ + if ((g_range = *s == '+' ? 1 : IS_DASH(*s) ? -1 : 0)) + ++s; + data = qgetnum(&s); + break; + + case 'o': + case 'O': + { + int t; + char *send; + + if (gf_nsorts == MAX_SORTS) { + zerr("too many glob sort specifiers"); + restore_globstate(saved); + return; + } + + /* usually just one character */ + send = s+1; + switch (*s) { + case 'n': t = GS_NAME; break; + case 'L': t = GS_SIZE; break; + case 'l': t = GS_LINKS; break; + case 'a': t = GS_ATIME; break; + case 'm': t = GS_MTIME; break; + case 'c': t = GS_CTIME; break; + case 'd': t = GS_DEPTH; break; + case 'N': t = GS_NONE; break; + case 'e': + case '+': + { + t = GS_EXEC; + if ((gf_sortlist[gf_nsorts].exec = + glob_exec_string(&send)) == NULL) + { + restore_globstate(saved); + return; + } + break; + } + default: + zerr("unknown sort specifier"); + restore_globstate(saved); + return; + } + if ((sense & 2) && + (t & (GS_SIZE|GS_ATIME|GS_MTIME|GS_CTIME|GS_LINKS))) + t <<= GS_SHIFT; /* HERE: GS_EXEC? */ + if (t != GS_EXEC) { + if (gf_sorts & t) { + zerr("doubled sort specifier"); + restore_globstate(saved); + return; + } + } + gf_sorts |= t; + gf_sortlist[gf_nsorts++].tp = t | + (((sense & 1) ^ (s[-1] == 'O')) ? GS_DESC : 0); + s = send; + break; + } + case '+': + case 'e': + { + char *tt; + + tt = glob_exec_string(&s); + + if (tt == NULL) { + data = 0; + } else { + func = qualsheval; + sdata = tt; + } + break; + } + case '[': + case Inbrack: + { + char *os = --s; + struct value v; + + v.isarr = SCANPM_WANTVALS; + v.pm = NULL; + v.end = -1; + v.flags = 0; + if (getindex(&s, &v, 0) || s == os) { + zerr("invalid subscript"); + restore_globstate(saved); + return; + } + first = v.start; + end = v.end; + break; + } + case 'P': + { + char *tt; + tt = glob_exec_string(&s); + + if (tt != NULL) + { + LinkList *words = sense & 1 ? &gf_post_words : &gf_pre_words; + if (!*words) + *words = newlinklist(); + addlinknode(*words, tt); + } + break; + } + default: + untokenize(--s); + zerr("unknown file attribute: %c", *s); + restore_globstate(saved); + return; + } + } + if (func) { + /* Requested test is performed by function func */ + if (!qn) + qn = (struct qual *)hcalloc(sizeof *qn); + if (ql) + ql->next = qn; + ql = qn; + if (!newquals) + newquals = qo = qn; + qn->func = func; + qn->sense = sense; + qn->data = data; + qn->sdata = sdata; + qn->range = g_range; + qn->units = g_units; + qn->amc = g_amc; + + qn = NULL; + qualct++; + } + if (errflag) { + restore_globstate(saved); + return; + } + } + + if (quals && newquals) { + /* Merge previous group of qualifiers with new set. */ + if (quals->or || newquals->or) { + /* The hard case. */ + struct qual *qorhead = NULL, *qortail = NULL; + /* + * Distribute in the most trivial way, by creating + * all possible combinations of the two sets and chaining + * these into one long set of alternatives given + * by qorhead and qortail. + */ + for (qn = newquals; qn; qn = qn->or) { + for (qo = quals; qo; qo = qo->or) { + struct qual *qfirst, *qlast; + int islast = !qn->or && !qo->or; + /* Generate first set of qualifiers... */ + if (islast) { + /* Last time round: don't bother copying. */ + qfirst = qn; + for (qlast = qfirst; qlast->next; + qlast = qlast->next) + ; + } else + qfirst = dup_qual_list(qn, &qlast); + /* ... link into new `or' chain ... */ + if (!qorhead) + qorhead = qfirst; + if (qortail) + qortail->or = qfirst; + qortail = qfirst; + /* ... and concatenate second set. */ + qlast->next = islast ? qo : dup_qual_list(qo, NULL); + } + } + quals = qorhead; + } else { + /* + * Easy: we can just chain the qualifiers together. + * This is an optimisation; the code above will work, too. + * We retain the original left to right ordering --- remember + * we are searching for sets of qualifiers from the right. + */ + qn = newquals; + for ( ; newquals->next; newquals = newquals->next) + ; + newquals->next = quals; + quals = qn; + } + } else if (newquals) + quals = newquals; + } + q = parsepat(str); + if (!q || errflag) { /* if parsing failed */ + restore_globstate(saved); + if (unset(BADPATTERN)) { + if (!nountok) + untokenize(ostr); + insertlinknode(list, node, ostr); + return; + } + errflag &= ~ERRFLAG_ERROR; + zerr("bad pattern: %s", ostr); + return; + } + if (!gf_nsorts) { + gf_sortlist[0].tp = gf_sorts = (shortcircuit ? GS_NONE : GS_NAME); + gf_nsorts = 1; + } + /* Initialise receptacle for matched files, * + * expanded by insert() where necessary. */ + matchptr = matchbuf = (Gmatch)zalloc((matchsz = 16) * + sizeof(struct gmatch)); + matchct = 0; + pattrystart(); + + /* The actual processing takes place here: matches go into * + * matchbuf. This is the only top-level call to scanner(). */ + scanner(q, shortcircuit); + + /* Deal with failures to match depending on options */ + if (matchct) + badcshglob |= 2; /* at least one cmd. line expansion O.K. */ + else if (!gf_nullglob) { + if (isset(CSHNULLGLOB)) { + badcshglob |= 1; /* at least one cmd. line expansion failed */ + } else if (isset(NOMATCH)) { + zerr("no matches found: %s", ostr); + zfree(matchbuf, 0); + restore_globstate(saved); + return; + } else { + /* treat as an ordinary string */ + untokenize(matchptr->name = dupstring(ostr)); + matchptr++; + matchct = 1; + } + } + + if (!(gf_sortlist[0].tp & GS_NONE)) { + /* + * Get the strings to use for sorting by executing + * the code chunk. We allow more than one of these. + */ + int nexecs = 0; + struct globsort *sortp; + struct globsort *lastsortp = gf_sortlist + gf_nsorts; + Gmatch gmptr; + + /* First find out if there are any GS_EXECs, counting them. */ + for (sortp = gf_sortlist; sortp < lastsortp; sortp++) + { + if (sortp->tp & GS_EXEC) + nexecs++; + } + + if (nexecs) { + Gmatch tmpptr; + int iexec = 0; + + /* Yes; allocate enough space for strings for each */ + for (tmpptr = matchbuf; tmpptr < matchptr; tmpptr++) + tmpptr->sortstrs = (char **)zhalloc(nexecs*sizeof(char*)); + + /* Loop over each one, incrementing iexec */ + for (sortp = gf_sortlist; sortp < lastsortp; sortp++) + { + /* Ignore unless this is a GS_EXEC */ + if (sortp->tp & GS_EXEC) { + Eprog prog; + + if ((prog = parse_string(sortp->exec, 0))) { + int ef = errflag, lv = lastval; + + /* Parsed OK, execute for each name */ + for (tmpptr = matchbuf; tmpptr < matchptr; tmpptr++) { + setsparam("REPLY", ztrdup(tmpptr->name)); + execode(prog, 1, 0, "globsort"); + if (!errflag) + tmpptr->sortstrs[iexec] = + dupstring(getsparam("REPLY")); + else + tmpptr->sortstrs[iexec] = tmpptr->name; + } + + /* Retain any user interrupt error status */ + errflag = ef | (errflag & ERRFLAG_INT); + lastval = lv; + } else { + /* Failed, let's be safe */ + for (tmpptr = matchbuf; tmpptr < matchptr; tmpptr++) + tmpptr->sortstrs[iexec] = tmpptr->name; + } + + iexec++; + } + } + } + + /* + * Where necessary, create unmetafied version of names + * for comparison. If no Meta characters just point + * to original string. All on heap. + */ + for (gmptr = matchbuf; gmptr < matchptr; gmptr++) + { + if (strchr(gmptr->name, Meta)) + { + int dummy; + gmptr->uname = dupstring(gmptr->name); + unmetafy(gmptr->uname, &dummy); + } else { + gmptr->uname = gmptr->name; + } + } + + /* Sort arguments in to lexical (and possibly numeric) order. * + * This is reversed to facilitate insertion into the list. */ + qsort((void *) & matchbuf[0], matchct, sizeof(struct gmatch), + (int (*) _((const void *, const void *)))gmatchcmp); + } + + if (first < 0) { + first += matchct; + if (first < 0) + first = 0; + } + if (end < 0) + end += matchct + 1; + else if (end > matchct) + end = matchct; + if ((end -= first) > 0) { + if (gf_sortlist[0].tp & GS_NONE) { + /* Match list was never reversed, so insert back to front. */ + matchptr = matchbuf + matchct - first - 1; + while (end-- > 0) { + /* insert matches in the arg list */ + insert_glob_match(list, node, matchptr->name); + matchptr--; + } + } else { + matchptr = matchbuf + matchct - first - end; + while (end-- > 0) { + /* insert matches in the arg list */ + insert_glob_match(list, node, matchptr->name); + matchptr++; + } + } + } else if (!badcshglob && !isset(NOMATCH) && matchct == 1) { + insert_glob_match(list, node, (--matchptr)->name); + } + zfree(matchbuf, 0); + + restore_globstate(saved); +} + +/* Return the trailing character for marking file types */ + +/**/ +mod_export char +file_type(mode_t filemode) +{ + if(S_ISBLK(filemode)) + return '#'; + else if(S_ISCHR(filemode)) + return '%'; + else if(S_ISDIR(filemode)) + return '/'; + else if(S_ISFIFO(filemode)) + return '|'; + else if(S_ISLNK(filemode)) + return '@'; + else if(S_ISREG(filemode)) + return (filemode & S_IXUGO) ? '*' : ' '; + else if(S_ISSOCK(filemode)) + return '='; + else + return '?'; +} + +/* check to see if str is eligible for brace expansion */ + +/**/ +mod_export int +hasbraces(char *str) +{ + char *lbr, *mbr, *comma; + + if (isset(BRACECCL)) { + /* In this case, any properly formed brace expression * + * will match and expand to the characters in between. */ + int bc, c; + + for (bc = 0; (c = *str); ++str) + if (c == Inbrace) { + if (!bc && str[1] == Outbrace) + *str++ = '{', *str = '}'; + else + bc++; + } else if (c == Outbrace) { + if (!bc) + *str = '}'; + else if (!--bc) + return 1; + } + return 0; + } + /* Otherwise we need to look for... */ + lbr = mbr = comma = NULL; + for (;;) { + switch (*str++) { + case Inbrace: + if (!lbr) { + if (bracechardots(str-1, NULL, NULL)) + return 1; + lbr = str - 1; + if (IS_DASH(*str)) + str++; + while (idigit(*str)) + str++; + if (*str == '.' && str[1] == '.') { + str++; str++; + if (IS_DASH(*str)) + str++; + while (idigit(*str)) + str++; + if (*str == Outbrace && + (idigit(lbr[1]) || idigit(str[-1]))) + return 1; + else if (*str == '.' && str[1] == '.') { + str++; str++; + if (IS_DASH(*str)) + str++; + while (idigit(*str)) + str++; + if (*str == Outbrace && + (idigit(lbr[1]) || idigit(str[-1]))) + return 1; + } + } + } else { + char *s = --str; + + if (skipparens(Inbrace, Outbrace, &str)) { + *lbr = *s = '{'; + if (comma) + str = comma; + if (mbr && mbr < str) + str = mbr; + lbr = mbr = comma = NULL; + } else if (!mbr) + mbr = s; + } + break; + case Outbrace: + if (!lbr) + str[-1] = '}'; + else if (comma) + return 1; + else { + *lbr = '{'; + str[-1] = '}'; + if (mbr) + str = mbr; + mbr = lbr = NULL; + } + break; + case Comma: + if (!lbr) + str[-1] = ','; + else if (!comma) + comma = str - 1; + break; + case '\0': + if (lbr) + *lbr = '{'; + if (!mbr && !comma) + return 0; + if (comma) + str = comma; + if (mbr && mbr < str) + str = mbr; + lbr = mbr = comma = NULL; + break; + } + } +} + +/* expand stuff like >>*.c */ + +/**/ +int +xpandredir(struct redir *fn, LinkList redirtab) +{ + char *nam; + struct redir *ff; + int ret = 0; + local_list1(fake); + + /* Stick the name in a list... */ + init_list1(fake, fn->name); + /* ...which undergoes all the usual shell expansions */ + prefork(&fake, isset(MULTIOS) ? 0 : PREFORK_SINGLE, NULL); + /* Globbing is only done for multios. */ + if (!errflag && isset(MULTIOS)) + globlist(&fake, 0); + if (errflag) + return 0; + if (nonempty(&fake) && !nextnode(firstnode(&fake))) { + /* Just one match, the usual case. */ + char *s = peekfirst(&fake); + fn->name = s; + untokenize(s); + if (fn->type == REDIR_MERGEIN || fn->type == REDIR_MERGEOUT) { + if (IS_DASH(s[0]) && !s[1]) + fn->type = REDIR_CLOSE; + else if (s[0] == 'p' && !s[1]) + fn->fd2 = -2; + else { + while (idigit(*s)) + s++; + if (!*s && s > fn->name) + fn->fd2 = zstrtol(fn->name, NULL, 10); + else if (fn->type == REDIR_MERGEIN) + zerr("file number expected"); + else + fn->type = REDIR_ERRWRITE; + } + } + } else if (fn->type == REDIR_MERGEIN) + zerr("file number expected"); + else { + if (fn->type == REDIR_MERGEOUT) + fn->type = REDIR_ERRWRITE; + while ((nam = (char *)ugetnode(&fake))) { + /* Loop over matches, duplicating the * + * redirection for each file found. */ + ff = (struct redir *) zhalloc(sizeof *ff); + *ff = *fn; + ff->name = nam; + addlinknode(redirtab, ff); + ret = 1; + } + } + return ret; +} + +/* + * Check for a brace expansion of the form {..}. + * On input str must be positioned at an Inbrace, but the sequence + * of characters beyond that has not necessarily been checked. + * Return 1 if found else 0. + * + * The other parameters are optionaland if the function returns 1 are + * used to return: + * - *c1p: the first character in the expansion. + * - *c2p: the final character in the expansion. + */ + +/**/ +static int +bracechardots(char *str, convchar_t *c1p, convchar_t *c2p) +{ + convchar_t cstart, cend; + char *pnext = str + 1, *pconv, convstr[2]; + if (itok(*pnext)) { + if (*pnext == Inbrace) + return 0; + convstr[0] = ztokens[*pnext - Pound]; + convstr[1] = '\0'; + pconv = convstr; + } else + pconv = pnext; + MB_METACHARINIT(); + pnext += MB_METACHARLENCONV(pconv, &cstart); + if ( +#ifdef MULTIBYTE_SUPPORT + cstart == WEOF || +#else + !cstart || +#endif + pnext[0] != '.' || pnext[1] != '.') + return 0; + pnext += 2; + if (!*pnext) + return 0; + if (itok(*pnext)) { + if (*pnext == Inbrace) + return 0; + convstr[0] = ztokens[*pnext - Pound]; + convstr[1] = '\0'; + pconv = convstr; + } else + pconv = pnext; + MB_METACHARINIT(); + pnext += MB_METACHARLENCONV(pconv, &cend); + if ( +#ifdef MULTIBYTE_SUPPORT + cend == WEOF || +#else + !cend || +#endif + *pnext != Outbrace) + return 0; + if (c1p) + *c1p = cstart; + if (c2p) + *c2p = cend; + return 1; +} + +/* brace expansion */ + +/**/ +mod_export void +xpandbraces(LinkList list, LinkNode *np) +{ + LinkNode node = (*np), last = prevnode(node); + char *str = (char *)getdata(node), *str3 = str, *str2; + int prev, bc, comma, dotdot; + + for (; *str != Inbrace; str++); + /* First, match up braces and see what we have. */ + for (str2 = str, bc = comma = dotdot = 0; *str2; ++str2) + if (*str2 == Inbrace) + ++bc; + else if (*str2 == Outbrace) { + if (--bc == 0) + break; + } else if (bc == 1) { + if (*str2 == Comma) + ++comma; /* we have {foo,bar} */ + else if (*str2 == '.' && str2[1] == '.') { + dotdot++; /* we have {num1..num2} */ + ++str2; + } + } + DPUTS(bc, "BUG: unmatched brace in xpandbraces()"); + if (!comma && dotdot) { + /* Expand range like 0..10 numerically: comma or recursive + brace expansion take precedence. */ + char *dots, *p, *dots2 = NULL; + LinkNode olast = last; + /* Get the first number of the range */ + zlong rstart, rend; + int err = 0, rev = 0, rincr = 1; + int wid1, wid2, wid3, strp; + convchar_t cstart, cend; + + if (bracechardots(str, &cstart, &cend)) { + int lenalloc; + /* + * This is a character range. + */ + if (cend < cstart) { + convchar_t ctmp = cend; + cend = cstart; + cstart = ctmp; + rev = 1; + } + uremnode(list, node); + strp = str - str3; + lenalloc = strp + strlen(str2+1) + 1; + do { +#ifdef MULTIBYTE_SUPPORT + char *ncptr; + int nclen; + mb_charinit(); + ncptr = wcs_nicechar(cend, NULL, NULL); + nclen = strlen(ncptr); + p = zhalloc(lenalloc + nclen); + memcpy(p, str3, strp); + memcpy(p + strp, ncptr, nclen); + strcpy(p + strp + nclen, str2 + 1); +#else + p = zhalloc(lenalloc + 1); + memcpy(p, str3, strp); + sprintf(p + strp, "%c", cend); + strcat(p + strp, str2 + 1); +#endif + insertlinknode(list, last, p); + if (rev) /* decreasing: add in reverse order. */ + last = nextnode(last); + } while (cend-- > cstart); + *np = nextnode(olast); + return; + } + + /* Get the first number of the range */ + rstart = zstrtol(str+1,&dots,10); + rend = 0; + wid1 = (dots - str) - 1; + wid2 = (str2 - dots) - 2; + wid3 = 0; + strp = str - str3; + + if (dots == str + 1 || *dots != '.' || dots[1] != '.') + err++; + else { + /* Get the last number of the range */ + rend = zstrtol(dots+2,&p,10); + if (p == dots+2) + err++; + /* check for {num1..num2..incr} */ + if (p != str2) { + wid2 = (p - dots) - 2; + dots2 = p; + if (dotdot == 2 && *p == '.' && p[1] == '.') { + rincr = zstrtol(p+2, &p, 10); + wid3 = p - dots2 - 2; + if (p != str2 || !rincr) + err++; + } else + err++; + } + } + if (!err) { + /* If either no. begins with a zero, pad the output with * + * zeroes. Otherwise, set min width to 0 to suppress them. + * str+1 is the first number in the range, dots+2 the last, + * and dots2+2 is the increment if that's given. */ + /* TODO: sorry about this */ + int minw = (str[1] == '0' || + (IS_DASH(str[1]) && str[2] == '0')) + ? wid1 + : (dots[2] == '0' || + (IS_DASH(dots[2]) && dots[3] == '0')) + ? wid2 + : (dots2 && (dots2[2] == '0' || + (IS_DASH(dots2[2]) && dots2[3] == '0'))) + ? wid3 + : 0; + if (rincr < 0) { + /* Handle negative increment */ + rincr = -rincr; + rev = !rev; + } + if (rstart > rend) { + /* Handle decreasing ranges correctly. */ + zlong rt = rend; + rend = rstart; + rstart = rt; + rev = !rev; + } else if (rincr > 1) { + /* when incr > 1, range is aligned to the highest number of str1, + * compensate for this so that it is aligned to the first number */ + rend -= (rend - rstart) % rincr; + } + uremnode(list, node); + for (; rend >= rstart; rend -= rincr) { + /* Node added in at end, so do highest first */ + p = dupstring(str3); +#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD) + sprintf(p + strp, "%0*lld", minw, rend); +#else + sprintf(p + strp, "%0*ld", minw, (long)rend); +#endif + strcat(p + strp, str2 + 1); + insertlinknode(list, last, p); + if (rev) /* decreasing: add in reverse order. */ + last = nextnode(last); + } + *np = nextnode(olast); + return; + } + } + if (!comma && isset(BRACECCL)) { /* {a-mnop} */ + /* Here we expand each character to a separate node, * + * but also ranges of characters like a-m. ccl is a * + * set of flags saying whether each character is present; * + * the final list is in lexical order. */ + char ccl[256], *p; + unsigned char c1, c2; + unsigned int len, pl; + int lastch = -1; + + uremnode(list, node); + memset(ccl, 0, sizeof(ccl) / sizeof(ccl[0])); + for (p = str + 1; p < str2;) { + if (itok(c1 = *p++)) + c1 = ztokens[c1 - STOUC(Pound)]; + if ((char) c1 == Meta) + c1 = 32 ^ *p++; + if (itok(c2 = *p)) + c2 = ztokens[c2 - STOUC(Pound)]; + if ((char) c2 == Meta) + c2 = 32 ^ p[1]; + if (IS_DASH((char)c1) && lastch >= 0 && + p < str2 && lastch <= (int)c2) { + while (lastch < (int)c2) + ccl[lastch++] = 1; + lastch = -1; + } else + ccl[lastch = c1] = 1; + } + pl = str - str3; + len = pl + strlen(++str2) + 2; + for (p = ccl + 256; p-- > ccl;) + if (*p) { + c1 = p - ccl; + if (imeta(c1)) { + str = hcalloc(len + 1); + str[pl] = Meta; + str[pl+1] = c1 ^ 32; + strcpy(str + pl + 2, str2); + } else { + str = hcalloc(len); + str[pl] = c1; + strcpy(str + pl + 1, str2); + } + memcpy(str, str3, pl); + insertlinknode(list, last, str); + } + *np = nextnode(last); + return; + } + prev = str++ - str3; + str2++; + uremnode(list, node); + node = last; + /* Finally, normal comma expansion * + * str1{foo,bar}str2 -> str1foostr2 str1barstr2. * + * Any number of intervening commas is allowed. */ + for (;;) { + char *zz, *str4; + int cnt; + + for (str4 = str, cnt = 0; cnt || (*str != Comma && *str != + Outbrace); str++) { + if (*str == Inbrace) + cnt++; + else if (*str == Outbrace) + cnt--; + DPUTS(!*str, "BUG: illegal brace expansion"); + } + /* Concatenate the string before the braces (str3), the section * + * just found (str4) and the text after the braces (str2) */ + zz = (char *) hcalloc(prev + (str - str4) + strlen(str2) + 1); + ztrncpy(zz, str3, prev); + strncat(zz, str4, str - str4); + strcat(zz, str2); + /* and add this text to the argument list. */ + insertlinknode(list, node, zz); + incnode(node); + if (*str != Outbrace) + str++; + else + break; + } + *np = nextnode(last); +} + +/* check to see if a matches b (b is not a filename pattern) */ + +/**/ +int +matchpat(char *a, char *b) +{ + Patprog p; + int ret; + + queue_signals(); /* Protect PAT_STATIC */ + + if (!(p = patcompile(b, PAT_STATIC, NULL))) { + zerr("bad pattern: %s", b); + ret = 0; + } else + ret = pattry(p, a); + + unqueue_signals(); + + return ret; +} + +/* do the ${foo%%bar}, ${foo#bar} stuff */ +/* please do not laugh at this code. */ + +/* Having found a match in getmatch, decide what part of string + * to return. The matched part starts b characters into string imd->ustr + * and finishes e characters in: 0 <= b <= e <= imd->ulen on input + * (yes, empty matches should work). + * + * imd->flags is a set of the SUB_* matches defined in zsh.h from + * SUB_MATCH onwards; the lower parts are ignored. + * + * imd->replstr is the replacement string for a substitution + * + * imd->replstr is metafied and the values put in imd->repllist are metafied. + */ + +/**/ +static char * +get_match_ret(Imatchdata imd, int b, int e) +{ + char buf[80], *r, *p, *rr, *replstr = imd->replstr; + int ll = 0, bl = 0, t = 0, add = 0, fl = imd->flags, i; + + /* Account for b and e referring to unmetafied string */ + for (p = imd->ustr; p < imd->ustr + b; p++) + if (imeta(*p)) + add++; + b += add; + for (; p < imd->ustr + e; p++) + if (imeta(*p)) + add++; + e += add; + + /* Everything now refers to metafied lengths. */ + if (replstr || (fl & SUB_LIST)) { + if (fl & SUB_DOSUBST) { + replstr = dupstring(replstr); + singsub(&replstr); + untokenize(replstr); + } + if ((fl & (SUB_GLOBAL|SUB_LIST)) && imd->repllist) { + /* We are replacing the chunk, just add this to the list */ + Repldata rd = (Repldata) + ((fl & SUB_LIST) ? zalloc(sizeof(*rd)) : zhalloc(sizeof(*rd))); + rd->b = b; + rd->e = e; + rd->replstr = replstr; + if (fl & SUB_LIST) + zaddlinknode(imd->repllist, rd); + else + addlinknode(imd->repllist, rd); + return imd->mstr; + } + ll += strlen(replstr); + } + if (fl & SUB_MATCH) /* matched portion */ + ll += 1 + (e - b); + if (fl & SUB_REST) /* unmatched portion */ + ll += 1 + (imd->mlen - (e - b)); + if (fl & SUB_BIND) { + /* position of start of matched portion */ + sprintf(buf, "%d ", MB_METASTRLEN2END(imd->mstr, 0, imd->mstr+b) + 1); + ll += (bl = strlen(buf)); + } + if (fl & SUB_EIND) { + /* position of end of matched portion */ + sprintf(buf + bl, "%d ", + MB_METASTRLEN2END(imd->mstr, 0, imd->mstr+e) + 1); + ll += (bl = strlen(buf)); + } + if (fl & SUB_LEN) { + /* length of matched portion */ + sprintf(buf + bl, "%d ", MB_METASTRLEN2END(imd->mstr+b, 0, + imd->mstr+e)); + ll += (bl = strlen(buf)); + } + if (bl) + buf[bl - 1] = '\0'; + + rr = r = (char *) hcalloc(ll); + + if (fl & SUB_MATCH) { + /* copy matched portion to new buffer */ + for (i = b, p = imd->mstr + b; i < e; i++) + *rr++ = *p++; + t = 1; + } + if (fl & SUB_REST) { + /* Copy unmatched portion to buffer. If both portions * + * requested, put a space in between (why?) */ + if (t) + *rr++ = ' '; + /* there may be unmatched bits at both beginning and end of string */ + for (i = 0, p = imd->mstr; i < b; i++) + *rr++ = *p++; + if (replstr) + for (p = replstr; *p; ) + *rr++ = *p++; + for (i = e, p = imd->mstr + e; i < imd->mlen; i++) + *rr++ = *p++; + t = 1; + } + *rr = '\0'; + if (bl) { + /* if there was a buffer (with a numeric result), add it; * + * if there was other stuff too, stick in a space first. */ + if (t) + *rr++ = ' '; + strcpy(rr, buf); + } + return r; +} + +static Patprog +compgetmatch(char *pat, int *flp, char **replstrp) +{ + Patprog p; + /* + * Flags to pattern compiler: use static buffer since we only + * have one pattern at a time; we will try the must-match test ourselves, + * so tell the pattern compiler we are scanning. + */ + + /* int patflags = PAT_STATIC|PAT_SCAN|PAT_NOANCH;*/ + + /* Unfortunately, PAT_STATIC doesn't work if we have a replstr with + * something like ${x#...} in it which will be singsub()ed below because + * that would overwrite the pattern buffer. */ + + int patflags = PAT_SCAN|PAT_NOANCH | (*replstrp ? 0 : PAT_STATIC); + + /* + * Search is anchored to the end of the string if we want to match + * it all, or if we are matching at the end of the string and not + * using substrings. + */ + if ((*flp & SUB_ALL) || ((*flp & SUB_END) && !(*flp & SUB_SUBSTR))) + patflags &= ~PAT_NOANCH; + p = patcompile(pat, patflags, NULL); + if (!p) { + zerr("bad pattern: %s", pat); + return NULL; + } + if (*replstrp) { + if (p->patnpar || (p->globend & GF_MATCHREF)) { + /* + * Either backreferences or match references, so we + * need to re-substitute replstr each time round. + */ + *flp |= SUB_DOSUBST; + } else { + singsub(replstrp); + untokenize(*replstrp); + } + } + + return p; +} + +/* + * This is called from paramsubst to get the match for ${foo#bar} etc. + * fl is a set of the SUB_* flags defined in zsh.h + * *sp points to the string we have to modify. The n'th match will be + * returned in *sp. The heap is used to get memory for the result string. + * replstr is the replacement string from a ${.../orig/repl}, in + * which case pat is the original. + * + * n is now ignored unless we are looking for a substring, in + * which case the n'th match from the start is counted such that + * there is no more than one match from each position. + */ + +/**/ +int +getmatch(char **sp, char *pat, int fl, int n, char *replstr) +{ + Patprog p; + + if (!(p = compgetmatch(pat, &fl, &replstr))) + return 1; + + return igetmatch(sp, p, fl, n, replstr, NULL); +} + +/* + * This is the corresponding function for array variables. + * Matching is done with the same pattern on each element. + */ + +/**/ +void +getmatcharr(char ***ap, char *pat, int fl, int n, char *replstr) +{ + char **arr = *ap, **pp; + Patprog p; + + if (!(p = compgetmatch(pat, &fl, &replstr))) + return; + + *ap = pp = hcalloc(sizeof(char *) * (arrlen(arr) + 1)); + while ((*pp = *arr++)) + if (igetmatch(pp, p, fl, n, replstr, NULL)) + pp++; +} + +/* + * Match against str using pattern pp; return a list of + * Repldata matches in the linked list *repllistp; this is + * in permanent storage and to be freed by freematchlist() + */ + +/**/ +mod_export int +getmatchlist(char *str, Patprog p, LinkList *repllistp) +{ + char **sp = &str; + + /* + * We don't care if we have longest or shortest match, but SUB_LONG + * is cheaper since the pattern code does that by default. + * We need SUB_GLOBAL to get all matches. + * We need SUB_SUBSTR to scan through for substrings. + * We need SUB_LIST to activate the special handling of the list + * passed in. + */ + return igetmatch(sp, p, SUB_LONG|SUB_GLOBAL|SUB_SUBSTR|SUB_LIST, + 0, NULL, repllistp); +} + +static void +freerepldata(void *ptr) +{ + zfree(ptr, sizeof(struct repldata)); +} + +/**/ +mod_export void +freematchlist(LinkList repllist) +{ + freelinklist(repllist, freerepldata); +} + +/**/ +static void +set_pat_start(Patprog p, int offs) +{ + /* + * If we are messing around with the test string by advancing up + * it from the start, we need to tell the pattern matcher that + * a start-of-string assertion, i.e. (#s), should fail. Hence + * we test whether the offset of the real start of string from + * the actual start, passed as offs, is zero. + */ + if (offs) + p->flags |= PAT_NOTSTART; + else + p->flags &= ~PAT_NOTSTART; +} + +/**/ +static void +set_pat_end(Patprog p, char null_me) +{ + /* + * If we are messing around with the string by shortening it at the + * tail, we need to tell the pattern matcher that an end-of-string + * assertion, i.e. (#e), should fail. Hence we test whether + * the character null_me about to be zapped is or is not already a null. + */ + if (null_me) + p->flags |= PAT_NOTEND; + else + p->flags &= ~PAT_NOTEND; +} + +/**/ +#ifdef MULTIBYTE_SUPPORT + +/* + * Increment *tp over character which may be multibyte. + * Return number of bytes. + * All unmetafied here. + */ + +/**/ +static int iincchar(char **tp, int left) +{ + char *t = *tp; + int mbclen = mb_charlenconv(t, left, NULL); + *tp = t + mbclen; + + return mbclen; +} + +/**/ +static int +igetmatch(char **sp, Patprog p, int fl, int n, char *replstr, + LinkList *repllistp) +{ + char *s = *sp, *t, *tmatch, *send; + /* + * Note that ioff counts (possibly multibyte) characters in the + * character set (Meta's are not included), while l counts characters in + * the metafied string. + * + * umlen is a counter for (unmetafied) byte lengths---neither characters + * nor raw byte indices; this is simply an optimisation for allocation. + * umltot is the full length of the string in this scheme. + * + * l is the raw string length, used together with any pointers into + * the string (typically t). + */ + int ioff, l = strlen(*sp), matched = 1, umltot = ztrlen(*sp); + int umlen, nmatches; + struct patstralloc patstralloc; + struct imatchdata imd; + + (void)patallocstr(p, s, l, umltot, 1, &patstralloc); + s = patstralloc.alloced; + DPUTS(!s, "forced patallocstr failed"); + send = s + umltot; + + imd.mstr = *sp; + imd.mlen = l; + imd.ustr = s; + imd.ulen = umltot; + imd.flags = fl; + imd.replstr = replstr; + imd.repllist = NULL; + + /* perform must-match test for complex closures */ + if (p->mustoff) + { + char *muststr = (char *)p + p->mustoff; + + matched = 0; + if (p->patmlen <= umltot) + { + for (t = s; t <= send - p->patmlen; t++) + { + if (!memcmp(muststr, t, p->patmlen)) { + matched = 1; + break; + } + } + } + } + + /* in case we used the prog before... */ + p->flags &= ~(PAT_NOTSTART|PAT_NOTEND); + + if (fl & SUB_ALL) { + int i = matched && pattrylen(p, s, umltot, 0, &patstralloc, 0); + if (!i) { + /* Perform under no-match conditions */ + umltot = 0; + imd.replstr = NULL; + } + *sp = get_match_ret(&imd, 0, umltot); + if (! **sp && (((fl & SUB_MATCH) && !i) || ((fl & SUB_REST) && i))) + return 0; + return 1; + } + if (matched) { + /* + * The default behaviour is to match at the start; this + * is modified by SUB_END and SUB_SUBSTR. SUB_END matches + * at the end of the string instead of the start. SUB_SUBSTR + * without SUB_END matches substrings searching from the start; + * with SUB_END it matches substrings searching from the end. + * + * The possibilities are further modified by whether we want the + * longest (SUB_LONG) or shortest possible match. + * + * SUB_START is only used in the case where we are also + * forcing a match at the end (SUB_END with no SUB_SUBSTR, + * with or without SUB_LONG), to indicate we should match + * the entire string. + */ + switch (fl & (SUB_END|SUB_LONG|SUB_SUBSTR)) { + case 0: + case SUB_LONG: + /* + * Largest/smallest possible match at head of string. + * First get the longest match... + */ + if (pattrylen(p, s, umltot, 0, &patstralloc, 0)) { + /* patmatchlen returns unmetafied length in this case */ + int mlen = patmatchlen(); + if (!(fl & SUB_LONG) && !(p->flags & PAT_PURES)) { + send = s + mlen; + /* + * ... now we know whether it's worth looking for the + * shortest, which we do by brute force. + */ + mb_charinit(); + for (t = s, umlen = 0; t < send; ) { + set_pat_end(p, *t); + if (pattrylen(p, s, umlen, 0, &patstralloc, 0)) { + mlen = patmatchlen(); + break; + } + umlen += iincchar(&t, send - t); + } + } + *sp = get_match_ret(&imd, 0, mlen); + return 1; + } + break; + + case SUB_END: + /* + * Smallest possible match at tail of string. + * As we can only be sure we've got wide characters right + * when going forwards, we need to match at every point + * until we fail and record the last successful match. + * + * It's important that we return the last successful match + * so that match, mbegin, mend and MATCH, MBEGIN, MEND are + * correct. + */ + mb_charinit(); + tmatch = NULL; + for (ioff = 0, t = s, umlen = umltot; t < send; ioff++) { + set_pat_start(p, t-s); + if (pattrylen(p, t, umlen, 0, &patstralloc, ioff)) + tmatch = t; + if (fl & SUB_START) + break; + umlen -= iincchar(&t, send - t); + } + if (tmatch) { + *sp = get_match_ret(&imd, tmatch - s, umltot); + return 1; + } + if (!(fl & SUB_START) && pattrylen(p, s + umltot, 0, 0, + &patstralloc, ioff)) { + *sp = get_match_ret(&imd, umltot, umltot); + return 1; + } + break; + + case (SUB_END|SUB_LONG): + /* Largest possible match at tail of string: * + * move forward along string until we get a match. * + * Again there's no optimisation. */ + mb_charinit(); + for (ioff = 0, t = s, umlen = umltot; t <= send ; ioff++) { + set_pat_start(p, t-s); + if (pattrylen(p, t, umlen, 0, &patstralloc, ioff)) { + *sp = get_match_ret(&imd, t-s, umltot); + return 1; + } + if (fl & SUB_START) + break; + if (t == send) + break; + umlen -= iincchar(&t, send - t); + } + if (!(fl & SUB_START) && pattrylen(p, send, 0, 0, + &patstralloc, ioff)) { + *sp = get_match_ret(&imd, umltot, umltot); + return 1; + } + break; + + case SUB_SUBSTR: + /* Smallest at start, but matching substrings. */ + set_pat_start(p, l); + if (!(fl & SUB_GLOBAL) && + pattrylen(p, send, 0, 0, &patstralloc, 0) && + !--n) { + *sp = get_match_ret(&imd, 0, 0); + return 1; + } /* fall through */ + case (SUB_SUBSTR|SUB_LONG): + /* longest or smallest at start with substrings */ + t = s; + if (fl & SUB_GLOBAL) { + imd.repllist = (fl & SUB_LIST) ? znewlinklist() : newlinklist(); + if (repllistp) + *repllistp = imd.repllist; + } + ioff = 0; /* offset into string */ + umlen = umltot; + mb_charinit(); + do { + /* loop over all matches for global substitution */ + matched = 0; + for (; t <= send; ioff++) { + /* Find the longest match from this position. */ + set_pat_start(p, t-s); + if (pattrylen(p, t, umlen, 0, &patstralloc, ioff)) { + char *mpos = t + patmatchlen(); + if (!(fl & SUB_LONG) && !(p->flags & PAT_PURES)) { + char *ptr; + int umlen2; + /* + * If searching for the shortest match, + * start with a zero length and increase + * it until we reach the longest possible + * match, accepting the first successful + * match. + */ + for (ptr = t, umlen2 = 0; ptr < mpos;) { + set_pat_end(p, *ptr); + if (pattrylen(p, t, umlen2, 0, + &patstralloc, ioff)) { + mpos = t + patmatchlen(); + break; + } + umlen2 += iincchar(&ptr, mpos - ptr); + } + } + if (!--n || (n <= 0 && (fl & SUB_GLOBAL))) { + *sp = get_match_ret(&imd, t-s, mpos-s); + if (mpos == t) + mpos += mb_charlenconv(mpos, send - mpos, NULL); + } + if (!(fl & SUB_GLOBAL)) { + if (n) { + /* + * Looking for a later match: in this case, + * we can continue looking for matches from + * the next character, even if it overlaps + * with what we just found. + */ + umlen -= iincchar(&t, send - t); + continue; + } else { + return 1; + } + } + /* + * For a global match, we need to skip the stuff + * which is already marked for replacement. + */ + matched = 1; + if (t == send) + break; + while (t < mpos) { + ioff++; + umlen -= iincchar(&t, send - t); + } + break; + } + if (t == send) + break; + umlen -= iincchar(&t, send - t); + } + } while (matched && t < send); + /* + * check if we can match a blank string, if so do it + * at the start. Goodness knows if this is a good idea + * with global substitution, so it doesn't happen. + */ + set_pat_start(p, l); + if ((fl & (SUB_LONG|SUB_GLOBAL)) == SUB_LONG && + pattrylen(p, send, 0, 0, &patstralloc, 0) && !--n) { + *sp = get_match_ret(&imd, 0, 0); + return 1; + } + break; + + case (SUB_END|SUB_SUBSTR): + case (SUB_END|SUB_LONG|SUB_SUBSTR): + /* Longest/shortest at end, matching substrings. */ + if (!(fl & SUB_LONG)) { + set_pat_start(p, l); + if (pattrylen(p, send, 0, 0, &patstralloc, umltot) && + !--n) { + *sp = get_match_ret(&imd, umltot, umltot); + return 1; + } + } + /* + * If multibyte characters are present we need to start from the + * beginning. This is a bit unpleasant because we can't tell in + * advance how many times it will match and from where, so if n is + * greater then 1 we will need to count the number of times it + * matched and then go through again until we reach the right + * point. (Either that or record every single match in a list, + * which isn't stupid; it involves more memory management at this + * level but less use of the pattern matcher.) + */ + nmatches = 0; + tmatch = NULL; + mb_charinit(); + for (ioff = 0, t = s, umlen = umltot; t < send; ioff++) { + set_pat_start(p, t-s); + if (pattrylen(p, t, umlen, 0, &patstralloc, ioff)) { + nmatches++; + tmatch = t; + } + umlen -= iincchar(&t, send - t); + } + if (nmatches) { + char *mpos; + if (n > 1) { + /* + * We need to find the n'th last match. + */ + n = nmatches - n; + mb_charinit(); + for (ioff = 0, t = s, umlen = umltot; t < send; ioff++) { + set_pat_start(p, t-s); + if (pattrylen(p, t, umlen, 0, &patstralloc, ioff) && + !n--) { + tmatch = t; + break; + } + umlen -= iincchar(&t, send - t); + } + } + mpos = tmatch + patmatchlen(); + /* Look for the shortest match if necessary */ + if (!(fl & SUB_LONG) && !(p->flags & PAT_PURES)) { + for (t = tmatch, umlen = 0; t < mpos; ) { + set_pat_end(p, *t); + if (pattrylen(p, tmatch, umlen, 0, + &patstralloc, ioff)) { + mpos = tmatch + patmatchlen(); + break; + } + umlen += iincchar(&t, mpos - t); + } + } + *sp = get_match_ret(&imd, tmatch-s, mpos-s); + return 1; + } + set_pat_start(p, l); + if ((fl & SUB_LONG) && pattrylen(p, send, 0, 0, + &patstralloc, umltot) && + !--n) { + *sp = get_match_ret(&imd, umltot, umltot); + return 1; + } + break; + } + } + + if (imd.repllist && nonempty(imd.repllist)) { + /* Put all the bits of a global search and replace together. */ + LinkNode nd; + Repldata rd; + int lleft; + char *ptr, *start; + int i; + + /* + * Use metafied string again. + * Results from get_match_ret in repllist are all metafied. + */ + s = *sp; + if (!(fl & SUB_LIST)) { + lleft = 0; /* size of returned string */ + i = 0; /* start of last chunk we got from *sp */ + for (nd = firstnode(imd.repllist); nd; incnode(nd)) { + rd = (Repldata) getdata(nd); + lleft += rd->b - i; /* previous chunk of *sp */ + lleft += strlen(rd->replstr); /* the replaced bit */ + i = rd->e; /* start of next chunk of *sp */ + } + lleft += l - i; /* final chunk from *sp */ + start = t = zhalloc(lleft+1); + i = 0; + for (nd = firstnode(imd.repllist); nd; incnode(nd)) { + rd = (Repldata) getdata(nd); + memcpy(t, s + i, rd->b - i); + t += rd->b - i; + ptr = rd->replstr; + while (*ptr) + *t++ = *ptr++; + i = rd->e; + } + memcpy(t, s + i, l - i); + start[lleft] = '\0'; + *sp = (char *)start; + } + return 1; + } + if (fl & SUB_LIST) { /* safety: don't think this can happen */ + return 0; + } + + /* munge the whole string: no match, so no replstr */ + imd.replstr = NULL; + imd.repllist = NULL; + *sp = get_match_ret(&imd, 0, 0); + return (fl & SUB_RETFAIL) ? 0 : 1; +} + +/**/ +#else + +/* + * Increment pointer which may be on a Meta (x is a pointer variable), + * returning the incremented value (i.e. like pre-increment). + */ +#define METAINC(x) ((x) += (*(x) == Meta) ? 2 : 1) + +/**/ +static int +igetmatch(char **sp, Patprog p, int fl, int n, char *replstr, + LinkList *repllistp) +{ + char *s = *sp, *t, *send; + /* + * Note that ioff and uml count characters in the character + * set (Meta's are not included), while l counts characters in the + * metafied string. umlen is a counter for (unmetafied) character + * lengths. + */ + int ioff, l = strlen(*sp), uml = ztrlen(*sp), matched = 1, umlen; + struct patstralloc patstralloc; + struct imatchdata imd; + + (void)patallocstr(p, s, l, uml, 1, &patstralloc); + s = patstralloc.alloced; + DPUTS(!s, "forced patallocstr failed"); + send = s + uml; + + imd.mstr = *sp; + imd.mlen = l; + imd.ustr = s; + imd.ulen = uml; + imd.flags = fl; + imd.replstr = replstr; + imd.repllist = NULL; + + /* perform must-match test for complex closures */ + if (p->mustoff) + { + char *muststr = (char *)p + p->mustoff; + + matched = 0; + if (p->patmlen <= uml) + { + for (t = s; t <= send - p->patmlen; t++) + { + if (!memcmp(muststr, t, p->patmlen)) { + matched = 1; + break; + } + } + } + } + + /* in case we used the prog before... */ + p->flags &= ~(PAT_NOTSTART|PAT_NOTEND); + + if (fl & SUB_ALL) { + int i = matched && pattrylen(p, s, uml, 0, &patstralloc, 0); + if (!i) + imd.replstr = NULL; + *sp = get_match_ret(&imd, 0, i ? l : 0); + if (! **sp && (((fl & SUB_MATCH) && !i) || ((fl & SUB_REST) && i))) + return 0; + return 1; + } + if (matched) { + switch (fl & (SUB_END|SUB_LONG|SUB_SUBSTR)) { + case 0: + case SUB_LONG: + /* + * Largest/smallest possible match at head of string. + * First get the longest match... + */ + if (pattrylen(p, s, uml, 0, &patstralloc, 0)) { + /* patmatchlen returns metafied length, as we need */ + int mlen = patmatchlen(); + if (!(fl & SUB_LONG) && !(p->flags & PAT_PURES)) { + send = s + mlen; + /* + * ... now we know whether it's worth looking for the + * shortest, which we do by brute force. + */ + for (t = s, umlen = 0; t < s + mlen; METAINC(t), umlen++) { + set_pat_end(p, *t); + if (pattrylen(p, s, umlen, 0, &patstralloc, 0)) { + mlen = patmatchlen(); + break; + } + } + } + *sp = get_match_ret(&imd, 0, mlen); + return 1; + } + break; + + case SUB_END: + /* Smallest possible match at tail of string: * + * move back down string until we get a match. * + * There's no optimization here. */ + for (ioff = uml, t = send, umlen = 0; t >= s; + t--, ioff--, umlen++) { + set_pat_start(p, t-s); + if (pattrylen(p, t, umlen, 0, &patstralloc, ioff)) { + *sp = get_match_ret(&imd, t - s, uml); + return 1; + } + } + break; + + case (SUB_END|SUB_LONG): + /* Largest possible match at tail of string: * + * move forward along string until we get a match. * + * Again there's no optimisation. */ + for (ioff = 0, t = s, umlen = uml; t < send; + ioff++, t++, umlen--) { + set_pat_start(p, t-s); + if (pattrylen(p, t, send - t, umlen, &patstralloc, ioff)) { + *sp = get_match_ret(&imd, t-s, uml); + return 1; + } + } + break; + + case SUB_SUBSTR: + /* Smallest at start, but matching substrings. */ + set_pat_start(p, l); + if (!(fl & SUB_GLOBAL) && + pattrylen(p, send, 0, 0, &patstralloc, 0) && !--n) { + *sp = get_match_ret(&imd, 0, 0); + return 1; + } /* fall through */ + case (SUB_SUBSTR|SUB_LONG): + /* longest or smallest at start with substrings */ + t = s; + if (fl & SUB_GLOBAL) { + imd.repllist = newlinklist(); + if (repllistp) + *repllistp = imd.repllist; + } + ioff = 0; /* offset into string */ + umlen = uml; + do { + /* loop over all matches for global substitution */ + matched = 0; + for (; t < send; t++, ioff++, umlen--) { + /* Find the longest match from this position. */ + set_pat_start(p, t-s); + if (pattrylen(p, t, send - t, umlen, &patstralloc, ioff)) { + char *mpos = t + patmatchlen(); + if (!(fl & SUB_LONG) && !(p->flags & PAT_PURES)) { + char *ptr; + int umlen2; + for (ptr = t, umlen2 = 0; ptr < mpos; + ptr++, umlen2++) { + set_pat_end(p, *ptr); + if (pattrylen(p, t, ptr - t, umlen2, + &patstralloc, ioff)) { + mpos = t + patmatchlen(); + break; + } + } + } + if (!--n || (n <= 0 && (fl & SUB_GLOBAL))) { + *sp = get_match_ret(&imd, t-s, mpos-s); + if (mpos == t) + mpos++; + } + if (!(fl & SUB_GLOBAL)) { + if (n) { + /* + * Looking for a later match: in this case, + * we can continue looking for matches from + * the next character, even if it overlaps + * with what we just found. + */ + continue; + } else { + return 1; + } + } + /* + * For a global match, we need to skip the stuff + * which is already marked for replacement. + */ + matched = 1; + while (t < mpos) { + ioff++; + umlen--; + t++; + } + break; + } + } + } while (matched); + /* + * check if we can match a blank string, if so do it + * at the start. Goodness knows if this is a good idea + * with global substitution, so it doesn't happen. + */ + set_pat_start(p, l); + if ((fl & (SUB_LONG|SUB_GLOBAL)) == SUB_LONG && + pattrylen(p, send, 0, 0, &patstralloc, 0) && !--n) { + *sp = get_match_ret(&imd, 0, 0); + return 1; + } + break; + + case (SUB_END|SUB_SUBSTR): + case (SUB_END|SUB_LONG|SUB_SUBSTR): + /* Longest/shortest at end, matching substrings. */ + if (!(fl & SUB_LONG)) { + set_pat_start(p, l); + if (pattrylen(p, send, 0, 0, &patstralloc, uml) && !--n) { + *sp = get_match_ret(&imd, uml, uml); + return 1; + } + } + for (ioff = uml - 1, t = send - 1, umlen = 1; t >= s; + t--, ioff--, umlen++) { + set_pat_start(p, t-s); + if (pattrylen(p, t, send - t, umlen, &patstralloc, ioff) && + !--n) { + /* Found the longest match */ + char *mpos = t + patmatchlen(); + if (!(fl & SUB_LONG) && !(p->flags & PAT_PURES)) { + char *ptr; + int umlen2; + for (ptr = t, umlen2 = 0; ptr < mpos; + ptr++, umlen2++) { + set_pat_end(p, *ptr); + if (pattrylen(p, t, umlen2, 0, &patstralloc, + ioff)) { + mpos = t + patmatchlen(); + break; + } + } + } + *sp = get_match_ret(&imd, t-s, mpos-s); + return 1; + } + } + set_pat_start(p, l); + if ((fl & SUB_LONG) && pattrylen(p, send, 0, 0, + &patstralloc, uml) && + !--n) { + *sp = get_match_ret(&imd, uml, uml); + return 1; + } + break; + } + } + + if (imd.repllist && nonempty(imd.repllist)) { + /* Put all the bits of a global search and replace together. */ + LinkNode nd; + Repldata rd; + int lleft = 0; /* size of returned string */ + char *ptr, *start; + int i; + + /* + * Use metafied string again. + * Results from get_match_ret in repllist are all metafied. + */ + s = *sp; + i = 0; /* start of last chunk we got from *sp */ + for (nd = firstnode(imd.repllist); nd; incnode(nd)) { + rd = (Repldata) getdata(nd); + lleft += rd->b - i; /* previous chunk of *sp */ + lleft += strlen(rd->replstr); /* the replaced bit */ + i = rd->e; /* start of next chunk of *sp */ + } + lleft += l - i; /* final chunk from *sp */ + start = t = zhalloc(lleft+1); + i = 0; + for (nd = firstnode(imd.repllist); nd; incnode(nd)) { + rd = (Repldata) getdata(nd); + memcpy(t, s + i, rd->b - i); + t += rd->b - i; + ptr = rd->replstr; + while (*ptr) + *t++ = *ptr++; + i = rd->e; + } + memcpy(t, s + i, l - i); + start[lleft] = '\0'; + *sp = (char *)start; + return 1; + } + + /* munge the whole string: no match, so no replstr */ + imd.replstr = NULL; + imd.repllist = NULL; + *sp = get_match_ret(&imd, 0, 0); + return 1; +} + +/**/ +#endif /* MULTIBYTE_SUPPORT */ + +/* blindly turn a string into a tokenised expression without lexing */ + +/**/ +mod_export void +tokenize(char *s) +{ + zshtokenize(s, 0); +} + +/* + * shtokenize is used when we tokenize a string with GLOB_SUBST set. + * In that case we need to retain backslashes when we turn the + * pattern back into a string, so that the string is not + * modified if it failed to match a pattern. + * + * It may be modified by the effect of SH_GLOB which turns off + * various zsh-specific options. + */ + +/**/ +mod_export void +shtokenize(char *s) +{ + int flags = ZSHTOK_SUBST; + if (isset(SHGLOB)) + flags |= ZSHTOK_SHGLOB; + zshtokenize(s, flags); +} + +/**/ +static void +zshtokenize(char *s, int flags) +{ + char *t; + int bslash = 0; + + for (; *s; s++) { + cont: + switch (*s) { + case Meta: + /* skip both Meta and following character */ + s++; + break; + case Bnull: + case Bnullkeep: + case '\\': + if (bslash) { + s[-1] = (flags & ZSHTOK_SUBST) ? Bnullkeep : Bnull; + break; + } + bslash = 1; + continue; + case '<': + if (flags & ZSHTOK_SHGLOB) + break; + if (bslash) { + s[-1] = (flags & ZSHTOK_SUBST) ? Bnullkeep : Bnull; + break; + } + t = s; + while (idigit(*++s)); + if (!IS_DASH(*s)) + goto cont; + while (idigit(*++s)); + if (*s != '>') + goto cont; + *t = Inang; + *s = Outang; + break; + case '(': + case '|': + case ')': + if (flags & ZSHTOK_SHGLOB) + break; + /*FALLTHROUGH*/ + case '>': + case '^': + case '#': + case '~': + case '[': + case ']': + case '*': + case '?': + case '=': + case '-': + case '!': + for (t = ztokens; *t; t++) { + if (*t == *s) { + if (bslash) + s[-1] = (flags & ZSHTOK_SUBST) ? Bnullkeep : Bnull; + else + *s = (t - ztokens) + Pound; + break; + } + } + break; + } + bslash = 0; + } +} + +/* remove unnecessary Nulargs */ + +/**/ +mod_export void +remnulargs(char *s) +{ + if (*s) { + char *o = s, c; + + while ((c = *s++)) + if (c == Bnullkeep) { + /* + * An active backslash that needs to be turned back into + * a real backslash for output. However, we don't + * do that yet since we need to ignore it during + * pattern matching. + */ + continue; + } else if (inull(c)) { + char *t = s - 1; + + while ((c = *s++)) { + if (c == Bnullkeep) + *t++ = '\\'; + else if (!inull(c)) + *t++ = c; + } + *t = '\0'; + if (!*o) { + o[0] = Nularg; + o[1] = '\0'; + } + break; + } + } +} + +/* qualifier functions: mostly self-explanatory, see glob(). */ + +/* device number */ + +/**/ +static int +qualdev(UNUSED(char *name), struct stat *buf, off_t dv, UNUSED(char *dummy)) +{ + return (off_t)buf->st_dev == dv; +} + +/* number of hard links to file */ + +/**/ +static int +qualnlink(UNUSED(char *name), struct stat *buf, off_t ct, UNUSED(char *dummy)) +{ + return (g_range < 0 ? buf->st_nlink < ct : + g_range > 0 ? buf->st_nlink > ct : + buf->st_nlink == ct); +} + +/* user ID */ + +/**/ +static int +qualuid(UNUSED(char *name), struct stat *buf, off_t uid, UNUSED(char *dummy)) +{ + return buf->st_uid == uid; +} + +/* group ID */ + +/**/ +static int +qualgid(UNUSED(char *name), struct stat *buf, off_t gid, UNUSED(char *dummy)) +{ + return buf->st_gid == gid; +} + +/* device special file? */ + +/**/ +static int +qualisdev(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy)) +{ + return S_ISBLK(buf->st_mode) || S_ISCHR(buf->st_mode); +} + +/* block special file? */ + +/**/ +static int +qualisblk(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy)) +{ + return S_ISBLK(buf->st_mode); +} + +/* character special file? */ + +/**/ +static int +qualischr(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy)) +{ + return S_ISCHR(buf->st_mode); +} + +/* directory? */ + +/**/ +static int +qualisdir(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy)) +{ + return S_ISDIR(buf->st_mode); +} + +/* FIFO? */ + +/**/ +static int +qualisfifo(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy)) +{ + return S_ISFIFO(buf->st_mode); +} + +/* symbolic link? */ + +/**/ +static int +qualislnk(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy)) +{ + return S_ISLNK(buf->st_mode); +} + +/* regular file? */ + +/**/ +static int +qualisreg(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy)) +{ + return S_ISREG(buf->st_mode); +} + +/* socket? */ + +/**/ +static int +qualissock(UNUSED(char *name), struct stat *buf, UNUSED(off_t junk), UNUSED(char *dummy)) +{ + return S_ISSOCK(buf->st_mode); +} + +/* given flag is set in mode */ + +/**/ +static int +qualflags(UNUSED(char *name), struct stat *buf, off_t mod, UNUSED(char *dummy)) +{ + return mode_to_octal(buf->st_mode) & mod; +} + +/* mode matches specification */ + +/**/ +static int +qualmodeflags(UNUSED(char *name), struct stat *buf, off_t mod, UNUSED(char *dummy)) +{ + long v = mode_to_octal(buf->st_mode), y = mod & 07777, n = mod >> 12; + + return ((v & y) == y && !(v & n)); +} + +/* regular executable file? */ + +/**/ +static int +qualiscom(UNUSED(char *name), struct stat *buf, UNUSED(off_t mod), UNUSED(char *dummy)) +{ + return S_ISREG(buf->st_mode) && (buf->st_mode & S_IXUGO); +} + +/* size in required range? */ + +/**/ +static int +qualsize(UNUSED(char *name), struct stat *buf, off_t size, UNUSED(char *dummy)) +{ +#if defined(ZSH_64_BIT_TYPE) || defined(LONG_IS_64_BIT) +# define QS_CAST_SIZE() + zlong scaled = buf->st_size; +#else +# define QS_CAST_SIZE() (unsigned long) + unsigned long scaled = (unsigned long)buf->st_size; +#endif + + switch (g_units) { + case TT_POSIX_BLOCKS: + scaled += 511l; + scaled /= 512l; + break; + case TT_KILOBYTES: + scaled += 1023l; + scaled /= 1024l; + break; + case TT_MEGABYTES: + scaled += 1048575l; + scaled /= 1048576l; + break; +#if defined(ZSH_64_BIT_TYPE) || defined(LONG_IS_64_BIT) + case TT_GIGABYTES: + scaled += ZLONG_CONST(1073741823); + scaled /= ZLONG_CONST(1073741824); + break; + case TT_TERABYTES: + scaled += ZLONG_CONST(1099511627775); + scaled /= ZLONG_CONST(1099511627776); + break; +#endif + } + + return (g_range < 0 ? scaled < QS_CAST_SIZE() size : + g_range > 0 ? scaled > QS_CAST_SIZE() size : + scaled == QS_CAST_SIZE() size); +#undef QS_CAST_SIZE +} + +/* time in required range? */ + +/**/ +static int +qualtime(UNUSED(char *name), struct stat *buf, off_t days, UNUSED(char *dummy)) +{ + time_t now, diff; + + time(&now); + diff = now - (g_amc == 0 ? buf->st_atime : g_amc == 1 ? buf->st_mtime : + buf->st_ctime); + /* handle multipliers indicating units */ + switch (g_units) { + case TT_DAYS: + diff /= 86400l; + break; + case TT_HOURS: + diff /= 3600l; + break; + case TT_MINS: + diff /= 60l; + break; + case TT_WEEKS: + diff /= 604800l; + break; + case TT_MONTHS: + diff /= 2592000l; + break; + } + + return (g_range < 0 ? diff < days : + g_range > 0 ? diff > days : + diff == days); +} + +/* evaluate a string */ + +/**/ +static int +qualsheval(char *name, UNUSED(struct stat *buf), UNUSED(off_t days), char *str) +{ + Eprog prog; + + if ((prog = parse_string(str, 0))) { + int ef = errflag, lv = lastval, ret; + int cshglob = badcshglob; + + unsetparam("reply"); + setsparam("REPLY", ztrdup(name)); + badcshglob = 0; + + execode(prog, 1, 0, "globqual"); + + if ((ret = lastval)) + badcshglob |= cshglob; + /* Retain any user interrupt error status */ + errflag = ef | (errflag & ERRFLAG_INT); + lastval = lv; + + if (!(inserts = getaparam("reply")) && + !(inserts = gethparam("reply"))) { + char *tmp; + + if ((tmp = getsparam("reply")) || (tmp = getsparam("REPLY"))) { + static char *tmparr[2]; + + tmparr[0] = tmp; + tmparr[1] = NULL; + + inserts = tmparr; + } + } + + return !ret; + } + return 0; +} + +/**/ +static int +qualnonemptydir(char *name, struct stat *buf, UNUSED(off_t days), UNUSED(char *str)) +{ + DIR *dirh; + struct dirent *de; + int unamelen; + char *uname = unmetafy(dupstring(name), &unamelen); + + if (!S_ISDIR(buf->st_mode)) + return 0; + + if (buf->st_nlink > 2) + return 1; + + if (!(dirh = opendir(uname))) + return 0; + + while ((de = readdir(dirh))) { + if (strcmp(de->d_name, ".") && strcmp(de->d_name, "..")) { + closedir(dirh); + return 1; + } + } + + closedir(dirh); + return 0; +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/hashtable.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/hashtable.c new file mode 100644 index 00000000..b7baa314 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/hashtable.c @@ -0,0 +1,1617 @@ +/* + * hashtable.c - hash tables + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "../config.h" + +#ifdef ZSH_HASH_DEBUG +# define HASHTABLE_DEBUG_MEMBERS \ + /* Members of struct hashtable used for debugging hash tables */ \ + HashTable next, last; /* linked list of all hash tables */ \ + char *tablename; /* string containing name of the hash table */ \ + PrintTableStats printinfo; /* pointer to function to print table stats */ +#else /* !ZSH_HASH_DEBUG */ +# define HASHTABLE_DEBUG_MEMBERS +#endif /* !ZSH_HASH_DEBUG */ + +#define HASHTABLE_INTERNAL_MEMBERS \ + ScanStatus scan; /* status of a scan over this hashtable */ \ + HASHTABLE_DEBUG_MEMBERS + +typedef struct scanstatus *ScanStatus; + +#include "zsh.mdh" +#include "hashtable.pro" + +/* Structure for recording status of a hashtable scan in progress. When a * + * scan starts, the .scan member of the hashtable structure points to one * + * of these. That member being non-NULL disables resizing of the * + * hashtable (when adding elements). When elements are deleted, the * + * contents of this structure is used to make sure the scan won't stumble * + * into the deleted element. */ + +struct scanstatus { + int sorted; + union { + struct { + HashNode *hashtab; + int ct; + } s; + HashNode u; + } u; +}; + +/********************************/ +/* Generic Hash Table functions */ +/********************************/ + +#ifdef ZSH_HASH_DEBUG +static HashTable firstht, lastht; +#endif /* ZSH_HASH_DEBUG */ + +/* Generic hash function */ + +/**/ +mod_export unsigned +hasher(const char *str) +{ + unsigned hashval = 0, c; + + while ((c = *((unsigned char *) str++))) + hashval += (hashval << 5) + c; + + return hashval; +} + +/* Get a new hash table */ + +/**/ +mod_export HashTable +newhashtable(int size, UNUSED(char const *name), UNUSED(PrintTableStats printinfo)) +{ + HashTable ht; + + ht = (HashTable) zshcalloc(sizeof *ht); +#ifdef ZSH_HASH_DEBUG + ht->next = NULL; + if(!firstht) + firstht = ht; + ht->last = lastht; + if(lastht) + lastht->next = ht; + lastht = ht; + ht->printinfo = printinfo ? printinfo : printhashtabinfo; + ht->tablename = ztrdup(name); +#endif /* ZSH_HASH_DEBUG */ + ht->nodes = (HashNode *) zshcalloc(size * sizeof(HashNode)); + ht->hsize = size; + ht->ct = 0; + ht->scan = NULL; + ht->scantab = NULL; + return ht; +} + +/* Delete a hash table. After this function has been used, any * + * existing pointers to the hash table are invalid. */ + +/**/ +mod_export void +deletehashtable(HashTable ht) +{ + ht->emptytable(ht); +#ifdef ZSH_HASH_DEBUG + if(ht->next) + ht->next->last = ht->last; + else + lastht = ht->last; + if(ht->last) + ht->last->next = ht->next; + else + firstht = ht->next; + zsfree(ht->tablename); +#endif /* ZSH_HASH_DEBUG */ + zfree(ht->nodes, ht->hsize * sizeof(HashNode)); + zfree(ht, sizeof(*ht)); +} + +/* Add a node to a hash table. * + * nam is the key to use in hashing. nodeptr points * + * to the node to add. If there is already a node in * + * the table with the same key, it is first freed, and * + * then the new node is added. If the number of nodes * + * is now greater than twice the number of hash values, * + * the table is then expanded. */ + +/**/ +mod_export void +addhashnode(HashTable ht, char *nam, void *nodeptr) +{ + HashNode oldnode = addhashnode2(ht, nam, nodeptr); + if (oldnode) + ht->freenode(oldnode); +} + +/* Add a node to a hash table, returning the old node on replacement. */ + +/**/ +HashNode +addhashnode2(HashTable ht, char *nam, void *nodeptr) +{ + unsigned hashval; + HashNode hn, hp, hq; + + hn = (HashNode) nodeptr; + hn->nam = nam; + + hashval = ht->hash(hn->nam) % ht->hsize; + hp = ht->nodes[hashval]; + + /* check if this is the first node for this hash value */ + if (!hp) { + hn->next = NULL; + ht->nodes[hashval] = hn; + if (++ht->ct >= ht->hsize * 2 && !ht->scan) + expandhashtable(ht); + return NULL; + } + + /* else check if the first node contains the same key */ + if (ht->cmpnodes(hp->nam, hn->nam) == 0) { + ht->nodes[hashval] = hn; + replacing: + hn->next = hp->next; + if(ht->scan) { + if(ht->scan->sorted) { + HashNode *hashtab = ht->scan->u.s.hashtab; + int i; + for(i = ht->scan->u.s.ct; i--; ) + if(hashtab[i] == hp) + hashtab[i] = hn; + } else if(ht->scan->u.u == hp) + ht->scan->u.u = hn; + } + return hp; + } + + /* else run through the list and check all the keys */ + hq = hp; + hp = hp->next; + for (; hp; hq = hp, hp = hp->next) { + if (ht->cmpnodes(hp->nam, hn->nam) == 0) { + hq->next = hn; + goto replacing; + } + } + + /* else just add it at the front of the list */ + hn->next = ht->nodes[hashval]; + ht->nodes[hashval] = hn; + if (++ht->ct >= ht->hsize * 2 && !ht->scan) + expandhashtable(ht); + return NULL; +} + +/* Get an enabled entry in a hash table. * + * If successful, it returns a pointer to * + * the hashnode. If the node is DISABLED * + * or isn't found, it returns NULL */ + +/**/ +mod_export HashNode +gethashnode(HashTable ht, const char *nam) +{ + unsigned hashval; + HashNode hp; + + hashval = ht->hash(nam) % ht->hsize; + for (hp = ht->nodes[hashval]; hp; hp = hp->next) { + if (ht->cmpnodes(hp->nam, nam) == 0) { + if (hp->flags & DISABLED) + return NULL; + else + return hp; + } + } + return NULL; +} + +/* Get an entry in a hash table. It will * + * ignore the DISABLED flag and return a * + * pointer to the hashnode if found, else * + * it returns NULL. */ + +/**/ +mod_export HashNode +gethashnode2(HashTable ht, const char *nam) +{ + unsigned hashval; + HashNode hp; + + hashval = ht->hash(nam) % ht->hsize; + for (hp = ht->nodes[hashval]; hp; hp = hp->next) { + if (ht->cmpnodes(hp->nam, nam) == 0) + return hp; + } + return NULL; +} + +/* Remove an entry from a hash table. * + * If successful, it removes the node from the * + * table and returns a pointer to it. If there * + * is no such node, then it returns NULL */ + +/**/ +mod_export HashNode +removehashnode(HashTable ht, const char *nam) +{ + unsigned hashval; + HashNode hp, hq; + + hashval = ht->hash(nam) % ht->hsize; + hp = ht->nodes[hashval]; + + /* if no nodes at this hash value, return NULL */ + if (!hp) + return NULL; + + /* else check if the key in the first one matches */ + if (ht->cmpnodes(hp->nam, nam) == 0) { + ht->nodes[hashval] = hp->next; + gotit: + ht->ct--; + if(ht->scan) { + if(ht->scan->sorted) { + HashNode *hashtab = ht->scan->u.s.hashtab; + int i; + for(i = ht->scan->u.s.ct; i--; ) + if(hashtab[i] == hp) + hashtab[i] = NULL; + } else if(ht->scan->u.u == hp) + ht->scan->u.u = hp->next; + } + return hp; + } + + /* else run through the list and check the rest of the keys */ + hq = hp; + hp = hp->next; + for (; hp; hq = hp, hp = hp->next) { + if (ht->cmpnodes(hp->nam, nam) == 0) { + hq->next = hp->next; + goto gotit; + } + } + + /* else it is not in the list, so return NULL */ + return NULL; +} + +/* Disable a node in a hash table */ + +/**/ +void +disablehashnode(HashNode hn, UNUSED(int flags)) +{ + hn->flags |= DISABLED; +} + +/* Enable a node in a hash table */ + +/**/ +void +enablehashnode(HashNode hn, UNUSED(int flags)) +{ + hn->flags &= ~DISABLED; +} + +/* Compare two hash table entries by name */ + +/**/ +static int +hnamcmp(const void *ap, const void *bp) +{ + HashNode a = *(HashNode *)ap; + HashNode b = *(HashNode *)bp; + return ztrcmp(a->nam, b->nam); +} + +/* Scan the nodes in a hash table and execute scanfunc on nodes based on + * the flags that are set/unset. scanflags is passed unchanged to + * scanfunc (if executed). + * + * If sorted != 0, then sort entries of hash table before scanning. + * If flags1 > 0, then execute scanfunc on a node only if at least one of + * these flags is set. + * If flags2 > 0, then execute scanfunc on a node only if all of + * these flags are NOT set. + * The conditions above for flags1/flags2 must both be true. + * + * It is safe to add, remove or replace hash table elements from within + * the scanfunc. Replaced elements will appear in the scan exactly once, + * the new version if it was not scanned before the replacement was made. + * Added elements might or might not appear in the scan. + * + * pprog, if non-NULL, is a pattern that must match the name + * of the node. + * + * The function returns the number of matches, as reduced by pprog, flags1 + * and flags2. + */ + +/**/ +mod_export int +scanmatchtable(HashTable ht, Patprog pprog, int sorted, + int flags1, int flags2, ScanFunc scanfunc, int scanflags) +{ + int match = 0; + struct scanstatus st; + + /* + * scantab is currently only used by modules to scan + * tables where the contents are generated on the fly from + * other objects. Note the fact that in this case pprog, + * sorted, flags1 and flags2 are ignore. + */ + if (!pprog && ht->scantab) { + ht->scantab(ht, scanfunc, scanflags); + return ht->ct; + } + if (sorted) { + int i, ct = ht->ct; + VARARR(HashNode, hnsorttab, ct); + HashNode *htp, hn; + + /* + * Because the structure might change under our feet, + * we can't apply the flags and the pattern before sorting, + * tempting though that is. + */ + for (htp = hnsorttab, i = 0; i < ht->hsize; i++) + for (hn = ht->nodes[i]; hn; hn = hn->next) + *htp++ = hn; + qsort((void *)hnsorttab, ct, sizeof(HashNode), hnamcmp); + + st.sorted = 1; + st.u.s.hashtab = hnsorttab; + st.u.s.ct = ct; + ht->scan = &st; + + for (htp = hnsorttab, i = 0; i < ct; i++, htp++) { + if ((!flags1 || ((*htp)->flags & flags1)) && + !((*htp)->flags & flags2) && + (!pprog || pattry(pprog, (*htp)->nam))) { + match++; + scanfunc(*htp, scanflags); + } + } + + ht->scan = NULL; + } else { + int i, hsize = ht->hsize; + HashNode *nodes = ht->nodes; + + st.sorted = 0; + ht->scan = &st; + + for (i = 0; i < hsize; i++) + for (st.u.u = nodes[i]; st.u.u; ) { + HashNode hn = st.u.u; + st.u.u = st.u.u->next; + if ((!flags1 || (hn->flags & flags1)) && !(hn->flags & flags2) + && (!pprog || pattry(pprog, hn->nam))) { + match++; + scanfunc(hn, scanflags); + } + } + + ht->scan = NULL; + } + + return match; +} + + +/**/ +mod_export int +scanhashtable(HashTable ht, int sorted, int flags1, int flags2, + ScanFunc scanfunc, int scanflags) +{ + return scanmatchtable(ht, NULL, sorted, flags1, flags2, + scanfunc, scanflags); +} + +/* Expand hash tables when they get too many entries. * + * The new size is 4 times the previous size. */ + +/**/ +static void +expandhashtable(HashTable ht) +{ + struct hashnode **onodes, **ha, *hn, *hp; + int i, osize; + + osize = ht->hsize; + onodes = ht->nodes; + + ht->hsize = osize * 4; + ht->nodes = (HashNode *) zshcalloc(ht->hsize * sizeof(HashNode)); + ht->ct = 0; + + /* scan through the old list of nodes, and * + * rehash them into the new list of nodes */ + for (i = 0, ha = onodes; i < osize; i++, ha++) { + for (hn = *ha; hn;) { + hp = hn->next; + ht->addnode(ht, hn->nam, hn); + hn = hp; + } + } + zfree(onodes, osize * sizeof(HashNode)); +} + +/* Empty the hash table and resize it if necessary */ + +/**/ +static void +resizehashtable(HashTable ht, int newsize) +{ + struct hashnode **ha, *hn, *hp; + int i; + + /* free all the hash nodes */ + ha = ht->nodes; + for (i = 0; i < ht->hsize; i++, ha++) { + for (hn = *ha; hn;) { + hp = hn->next; + ht->freenode(hn); + hn = hp; + } + } + + /* If new size desired is different from current size, * + * we free it and allocate a new nodes array. */ + if (ht->hsize != newsize) { + zfree(ht->nodes, ht->hsize * sizeof(HashNode)); + ht->nodes = (HashNode *) zshcalloc(newsize * sizeof(HashNode)); + ht->hsize = newsize; + } else { + /* else we just re-zero the current nodes array */ + memset(ht->nodes, 0, newsize * sizeof(HashNode)); + } + + ht->ct = 0; +} + +/* Generic method to empty a hash table */ + +/**/ +mod_export void +emptyhashtable(HashTable ht) +{ + resizehashtable(ht, ht->hsize); +} + +/**/ +#ifdef ZSH_HASH_DEBUG + +/* Print info about hash table */ + +#define MAXDEPTH 7 + +/**/ +static void +printhashtabinfo(HashTable ht) +{ + HashNode hn; + int chainlen[MAXDEPTH + 1]; + int i, tmpcount, total; + + printf("name of table : %s\n", ht->tablename); + printf("size of nodes[] : %d\n", ht->hsize); + printf("number of nodes : %d\n\n", ht->ct); + + memset(chainlen, 0, sizeof(chainlen)); + + /* count the number of nodes just to be sure */ + total = 0; + for (i = 0; i < ht->hsize; i++) { + tmpcount = 0; + for (hn = ht->nodes[i]; hn; hn = hn->next) + tmpcount++; + if (tmpcount >= MAXDEPTH) + chainlen[MAXDEPTH]++; + else + chainlen[tmpcount]++; + total += tmpcount; + } + + for (i = 0; i < MAXDEPTH; i++) + printf("number of hash values with chain of length %d : %4d\n", i, chainlen[i]); + printf("number of hash values with chain of length %d+ : %4d\n", MAXDEPTH, chainlen[MAXDEPTH]); + printf("total number of nodes : %4d\n", total); +} + +/**/ +int +bin_hashinfo(UNUSED(char *nam), UNUSED(char **args), UNUSED(Options ops), UNUSED(int func)) +{ + HashTable ht; + + printf("----------------------------------------------------\n"); + queue_signals(); + for(ht = firstht; ht; ht = ht->next) { + ht->printinfo(ht); + printf("----------------------------------------------------\n"); + } + unqueue_signals(); + return 0; +} + +/**/ +#endif /* ZSH_HASH_DEBUG */ + +/********************************/ +/* Command Hash Table Functions */ +/********************************/ + +/* hash table containing external commands */ + +/**/ +mod_export HashTable cmdnamtab; + +/* how far we've hashed the PATH so far */ + +/**/ +mod_export char **pathchecked; + +/* Create a new command hash table */ + +/**/ +void +createcmdnamtable(void) +{ + cmdnamtab = newhashtable(201, "cmdnamtab", NULL); + + cmdnamtab->hash = hasher; + cmdnamtab->emptytable = emptycmdnamtable; + cmdnamtab->filltable = fillcmdnamtable; + cmdnamtab->cmpnodes = strcmp; + cmdnamtab->addnode = addhashnode; + cmdnamtab->getnode = gethashnode2; + cmdnamtab->getnode2 = gethashnode2; + cmdnamtab->removenode = removehashnode; + cmdnamtab->disablenode = NULL; + cmdnamtab->enablenode = NULL; + cmdnamtab->freenode = freecmdnamnode; + cmdnamtab->printnode = printcmdnamnode; + + pathchecked = path; +} + +/**/ +static void +emptycmdnamtable(HashTable ht) +{ + emptyhashtable(ht); + pathchecked = path; +} + +/* Add all commands in a given directory * + * to the command hashtable. */ + +/**/ +void +hashdir(char **dirp) +{ + Cmdnam cn; + DIR *dir; + char *fn, *unmetadir, *pathbuf, *pathptr; + int dirlen; +#if defined(_WIN32) || defined(__CYGWIN__) + char *exe; +#endif /* _WIN32 || _CYGWIN__ */ + + if (isrelative(*dirp)) + return; + unmetadir = unmeta(*dirp); + if (!(dir = opendir(unmetadir))) + return; + + dirlen = strlen(unmetadir); + pathbuf = (char *)zalloc(dirlen + PATH_MAX + 2); + sprintf(pathbuf, "%s/", unmetadir); + pathptr = pathbuf + dirlen + 1; + + while ((fn = zreaddir(dir, 1))) { + if (!cmdnamtab->getnode(cmdnamtab, fn)) { + char *fname = ztrdup(fn); + struct stat statbuf; + int add = 0, dummylen; + + unmetafy(fn, &dummylen); + if (strlen(fn) > PATH_MAX) { + /* Too heavy to do all the allocation */ + add = 1; + } else { + strcpy(pathptr, fn); + /* + * This is the same test as for the glob qualifier for + * executable plain files. + */ + if (unset(HASHEXECUTABLESONLY) || + (access(pathbuf, X_OK) == 0 && + stat(pathbuf, &statbuf) == 0 && + S_ISREG(statbuf.st_mode) && (statbuf.st_mode & S_IXUGO))) + add = 1; + } + if (add) { + cn = (Cmdnam) zshcalloc(sizeof *cn); + cn->node.flags = 0; + cn->u.name = dirp; + cmdnamtab->addnode(cmdnamtab, fname, cn); + } else + zsfree(fname); + } +#if defined(_WIN32) || defined(__CYGWIN__) + /* Hash foo.exe as foo, since when no real foo exists, foo.exe + will get executed by DOS automatically. This quiets + spurious corrections when CORRECT or CORRECT_ALL is set. */ + if ((exe = strrchr(fn, '.')) && + (exe[1] == 'E' || exe[1] == 'e') && + (exe[2] == 'X' || exe[2] == 'x') && + (exe[3] == 'E' || exe[3] == 'e') && exe[4] == 0) { + *exe = 0; + if (!cmdnamtab->getnode(cmdnamtab, fn)) { + cn = (Cmdnam) zshcalloc(sizeof *cn); + cn->node.flags = 0; + cn->u.name = dirp; + cmdnamtab->addnode(cmdnamtab, ztrdup(fn), cn); + } + } +#endif /* _WIN32 || __CYGWIN__ */ + } + closedir(dir); + zfree(pathbuf, dirlen + PATH_MAX + 2); +} + +/* Go through user's PATH and add everything to * + * the command hashtable. */ + +/**/ +static void +fillcmdnamtable(UNUSED(HashTable ht)) +{ + char **pq; + + for (pq = pathchecked; *pq; pq++) + hashdir(pq); + + pathchecked = pq; +} + +/**/ +static void +freecmdnamnode(HashNode hn) +{ + Cmdnam cn = (Cmdnam) hn; + + zsfree(cn->node.nam); + if (cn->node.flags & HASHED) + zsfree(cn->u.cmd); + + zfree(cn, sizeof(struct cmdnam)); +} + +/* Print an element of the cmdnamtab hash table (external command) */ + +/**/ +static void +printcmdnamnode(HashNode hn, int printflags) +{ + Cmdnam cn = (Cmdnam) hn; + + if (printflags & PRINT_WHENCE_WORD) { + printf("%s: %s\n", cn->node.nam, (cn->node.flags & HASHED) ? + "hashed" : "command"); + return; + } + + if ((printflags & PRINT_WHENCE_CSH) || (printflags & PRINT_WHENCE_SIMPLE)) { + if (cn->node.flags & HASHED) { + zputs(cn->u.cmd, stdout); + putchar('\n'); + } else { + zputs(*(cn->u.name), stdout); + putchar('/'); + zputs(cn->node.nam, stdout); + putchar('\n'); + } + return; + } + + if (printflags & PRINT_WHENCE_VERBOSE) { + if (cn->node.flags & HASHED) { + nicezputs(cn->node.nam, stdout); + printf(" is hashed to "); + nicezputs(cn->u.cmd, stdout); + putchar('\n'); + } else { + nicezputs(cn->node.nam, stdout); + printf(" is "); + nicezputs(*(cn->u.name), stdout); + putchar('/'); + nicezputs(cn->node.nam, stdout); + putchar('\n'); + } + return; + } + + if (printflags & PRINT_LIST) { + printf("hash "); + + if(cn->node.nam[0] == '-') + printf("-- "); + } + + if (cn->node.flags & HASHED) { + quotedzputs(cn->node.nam, stdout); + putchar('='); + quotedzputs(cn->u.cmd, stdout); + putchar('\n'); + } else { + quotedzputs(cn->node.nam, stdout); + putchar('='); + quotedzputs(*(cn->u.name), stdout); + putchar('/'); + quotedzputs(cn->node.nam, stdout); + putchar('\n'); + } +} + +/***************************************/ +/* Shell Function Hash Table Functions */ +/***************************************/ + +/* hash table containing the shell functions */ + +/**/ +mod_export HashTable shfunctab; + +/**/ +void +createshfunctable(void) +{ + shfunctab = newhashtable(7, "shfunctab", NULL); + + shfunctab->hash = hasher; + shfunctab->emptytable = NULL; + shfunctab->filltable = NULL; + shfunctab->cmpnodes = strcmp; + shfunctab->addnode = addhashnode; + shfunctab->getnode = gethashnode; + shfunctab->getnode2 = gethashnode2; + shfunctab->removenode = removeshfuncnode; + shfunctab->disablenode = disableshfuncnode; + shfunctab->enablenode = enableshfuncnode; + shfunctab->freenode = freeshfuncnode; + shfunctab->printnode = printshfuncnode; +} + +/* Remove an entry from the shell function hash table. * + * It checks if the function is a signal trap and if so, * + * it will disable the trapping of that signal. */ + +/**/ +static HashNode +removeshfuncnode(UNUSED(HashTable ht), const char *nam) +{ + HashNode hn; + int signum; + + if (!strncmp(nam, "TRAP", 4) && (signum = getsignum(nam + 4)) != -1) + hn = removetrap(signum); + else + hn = removehashnode(shfunctab, nam); + + return hn; +} + +/* Disable an entry in the shell function hash table. * + * It checks if the function is a signal trap and if so, * + * it will disable the trapping of that signal. */ + +/**/ +static void +disableshfuncnode(HashNode hn, UNUSED(int flags)) +{ + hn->flags |= DISABLED; + if (!strncmp(hn->nam, "TRAP", 4)) { + int signum = getsignum(hn->nam + 4); + if (signum != -1) { + sigtrapped[signum] &= ~ZSIG_FUNC; + unsettrap(signum); + } + } +} + +/* Re-enable an entry in the shell function hash table. * + * It checks if the function is a signal trap and if so, * + * it will re-enable the trapping of that signal. */ + +/**/ +static void +enableshfuncnode(HashNode hn, UNUSED(int flags)) +{ + Shfunc shf = (Shfunc) hn; + + shf->node.flags &= ~DISABLED; + if (!strncmp(shf->node.nam, "TRAP", 4)) { + int signum = getsignum(shf->node.nam + 4); + if (signum != -1) { + settrap(signum, NULL, ZSIG_FUNC); + } + } +} + +/**/ +static void +freeshfuncnode(HashNode hn) +{ + Shfunc shf = (Shfunc) hn; + + zsfree(shf->node.nam); + if (shf->funcdef) + freeeprog(shf->funcdef); + if (shf->redir) + freeeprog(shf->redir); + dircache_set(&shf->filename, NULL); + if (shf->sticky) { + if (shf->sticky->n_on_opts) + zfree(shf->sticky->on_opts, + shf->sticky->n_on_opts * sizeof(*shf->sticky->on_opts)); + if (shf->sticky->n_off_opts) + zfree(shf->sticky->off_opts, + shf->sticky->n_off_opts * sizeof(*shf->sticky->off_opts)); + zfree(shf->sticky, sizeof(*shf->sticky)); + } + zfree(shf, sizeof(struct shfunc)); +} + +/* Print a shell function */ + +/**/ +static void +printshfuncnode(HashNode hn, int printflags) +{ + Shfunc f = (Shfunc) hn; + char *t = 0; + + if ((printflags & PRINT_NAMEONLY) || + ((printflags & PRINT_WHENCE_SIMPLE) && + !(printflags & PRINT_WHENCE_FUNCDEF))) { + zputs(f->node.nam, stdout); + putchar('\n'); + return; + } + + if ((printflags & (PRINT_WHENCE_VERBOSE|PRINT_WHENCE_WORD)) && + !(printflags & PRINT_WHENCE_FUNCDEF)) { + nicezputs(f->node.nam, stdout); + printf((printflags & PRINT_WHENCE_WORD) ? ": function" : + (f->node.flags & PM_UNDEFINED) ? + " is an autoload shell function" : + " is a shell function"); + if ((printflags & PRINT_WHENCE_VERBOSE) && f->filename) { + printf(" from "); + quotedzputs(f->filename, stdout); + if (f->node.flags & PM_LOADDIR) { + printf("/"); + quotedzputs(f->node.nam, stdout); + } + } + putchar('\n'); + return; + } + + quotedzputs(f->node.nam, stdout); + if (f->funcdef || f->node.flags & PM_UNDEFINED) { + printf(" () {\n"); + zoutputtab(stdout); + if (f->node.flags & PM_UNDEFINED) { + printf("%c undefined\n", hashchar); + zoutputtab(stdout); + } else + t = getpermtext(f->funcdef, NULL, 1); + if (f->node.flags & (PM_TAGGED|PM_TAGGED_LOCAL)) { + printf("%c traced\n", hashchar); + zoutputtab(stdout); + } + if (!t) { + char *fopt = "UtTkzc"; + int flgs[] = { + PM_UNALIASED, PM_TAGGED, PM_TAGGED_LOCAL, + PM_KSHSTORED, PM_ZSHSTORED, PM_CUR_FPATH, 0 + }; + int fl;; + + zputs("builtin autoload -X", stdout); + for (fl=0;fopt[fl];fl++) + if (f->node.flags & flgs[fl]) putchar(fopt[fl]); + if (f->filename && (f->node.flags & PM_LOADDIR)) { + putchar(' '); + zputs(f->filename, stdout); + } + } else { + zputs(t, stdout); + zsfree(t); + if (f->funcdef->flags & EF_RUN) { + printf("\n"); + zoutputtab(stdout); + quotedzputs(f->node.nam, stdout); + printf(" \"$@\""); + } + } + printf("\n}"); + } else { + printf(" () { }"); + } + if (f->redir) { + t = getpermtext(f->redir, NULL, 1); + if (t) { + zputs(t, stdout); + zsfree(t); + } + } + + putchar('\n'); +} + +/* + * Wrap scanmatchtable for shell functions with optional + * expansion of leading tabs. + * expand = 0 is standard: use hard tabs. + * expand > 0 uses that many spaces. + * expand < 0 uses no identation. + * + * Note this function and the following two are called with + * interrupts queued, so saving and restoring text_expand_tabs + * is safe. + */ + +/**/ +mod_export int +scanmatchshfunc(Patprog pprog, int sorted, int flags1, int flags2, + ScanFunc scanfunc, int scanflags, int expand) +{ + int ret, save_expand; + + save_expand = text_expand_tabs; + text_expand_tabs = expand; + ret = scanmatchtable(shfunctab, pprog, sorted, flags1, flags2, + scanfunc, scanflags); + text_expand_tabs = save_expand; + + return ret; +} + +/* Wrap scanhashtable to expand tabs for shell functions */ + +/**/ +mod_export int +scanshfunc(int sorted, int flags1, int flags2, + ScanFunc scanfunc, int scanflags, int expand) +{ + return scanmatchshfunc(NULL, sorted, flags1, flags2, + scanfunc, scanflags, expand); +} + +/* Wrap shfunctab->printnode to expand tabs */ + +/**/ +mod_export void +printshfuncexpand(HashNode hn, int printflags, int expand) +{ + int save_expand; + + save_expand = text_expand_tabs; + text_expand_tabs = expand; + shfunctab->printnode(hn, printflags); + text_expand_tabs = save_expand; +} + +/* + * Get a heap-duplicated name of the shell function, for + * use in tracing. + */ + +/**/ +mod_export char * +getshfuncfile(Shfunc shf) +{ + if (shf->node.flags & PM_LOADDIR) { + return zhtricat(shf->filename, "/", shf->node.nam); + } else if (shf->filename) { + return dupstring(shf->filename); + } else { + return NULL; + } +} + +/**************************************/ +/* Reserved Word Hash Table Functions */ +/**************************************/ + +/* Nodes for reserved word hash table */ + +static struct reswd reswds[] = { + {{NULL, "!", 0}, BANG}, + {{NULL, "[[", 0}, DINBRACK}, + {{NULL, "{", 0}, INBRACE}, + {{NULL, "}", 0}, OUTBRACE}, + {{NULL, "case", 0}, CASE}, + {{NULL, "coproc", 0}, COPROC}, + {{NULL, "declare", 0}, TYPESET}, + {{NULL, "do", 0}, DOLOOP}, + {{NULL, "done", 0}, DONE}, + {{NULL, "elif", 0}, ELIF}, + {{NULL, "else", 0}, ELSE}, + {{NULL, "end", 0}, ZEND}, + {{NULL, "esac", 0}, ESAC}, + {{NULL, "export", 0}, TYPESET}, + {{NULL, "fi", 0}, FI}, + {{NULL, "float", 0}, TYPESET}, + {{NULL, "for", 0}, FOR}, + {{NULL, "foreach", 0}, FOREACH}, + {{NULL, "function", 0}, FUNC}, + {{NULL, "if", 0}, IF}, + {{NULL, "integer", 0}, TYPESET}, + {{NULL, "local", 0}, TYPESET}, + {{NULL, "nocorrect", 0}, NOCORRECT}, + {{NULL, "readonly", 0}, TYPESET}, + {{NULL, "repeat", 0}, REPEAT}, + {{NULL, "select", 0}, SELECT}, + {{NULL, "then", 0}, THEN}, + {{NULL, "time", 0}, TIME}, + {{NULL, "typeset", 0}, TYPESET}, + {{NULL, "until", 0}, UNTIL}, + {{NULL, "while", 0}, WHILE}, + {{NULL, NULL, 0}, 0} +}; + +/* hash table containing the reserved words */ + +/**/ +mod_export HashTable reswdtab; + +/* Build the hash table containing zsh's reserved words. */ + +/**/ +void +createreswdtable(void) +{ + Reswd rw; + + reswdtab = newhashtable(23, "reswdtab", NULL); + + reswdtab->hash = hasher; + reswdtab->emptytable = NULL; + reswdtab->filltable = NULL; + reswdtab->cmpnodes = strcmp; + reswdtab->addnode = addhashnode; + reswdtab->getnode = gethashnode; + reswdtab->getnode2 = gethashnode2; + reswdtab->removenode = NULL; + reswdtab->disablenode = disablehashnode; + reswdtab->enablenode = enablehashnode; + reswdtab->freenode = NULL; + reswdtab->printnode = printreswdnode; + + for (rw = reswds; rw->node.nam; rw++) + reswdtab->addnode(reswdtab, rw->node.nam, rw); +} + +/* Print a reserved word */ + +/**/ +static void +printreswdnode(HashNode hn, int printflags) +{ + Reswd rw = (Reswd) hn; + + if (printflags & PRINT_WHENCE_WORD) { + printf("%s: reserved\n", rw->node.nam); + return; + } + + if (printflags & PRINT_WHENCE_CSH) { + printf("%s: shell reserved word\n", rw->node.nam); + return; + } + + if (printflags & PRINT_WHENCE_VERBOSE) { + printf("%s is a reserved word\n", rw->node.nam); + return; + } + + /* default is name only */ + printf("%s\n", rw->node.nam); +} + +/********************************/ +/* Aliases Hash Table Functions */ +/********************************/ + +/* hash table containing the aliases */ + +/**/ +mod_export HashTable aliastab; + +/* has table containing suffix aliases */ + +/**/ +mod_export HashTable sufaliastab; + +/* Create new hash tables for aliases */ + +/**/ +void +createaliastable(HashTable ht) +{ + ht->hash = hasher; + ht->emptytable = NULL; + ht->filltable = NULL; + ht->cmpnodes = strcmp; + ht->addnode = addhashnode; + ht->getnode = gethashnode; + ht->getnode2 = gethashnode2; + ht->removenode = removehashnode; + ht->disablenode = disablehashnode; + ht->enablenode = enablehashnode; + ht->freenode = freealiasnode; + ht->printnode = printaliasnode; +} + +/**/ +void +createaliastables(void) +{ + /* Table for regular and global aliases */ + + aliastab = newhashtable(23, "aliastab", NULL); + + createaliastable(aliastab); + + /* add the default aliases */ + aliastab->addnode(aliastab, ztrdup("run-help"), createaliasnode(ztrdup("man"), 0)); + aliastab->addnode(aliastab, ztrdup("which-command"), createaliasnode(ztrdup("whence"), 0)); + + + /* Table for suffix aliases --- make this smaller */ + + sufaliastab = newhashtable(11, "sufaliastab", NULL); + + createaliastable(sufaliastab); +} + +/* Create a new alias node */ + +/**/ +mod_export Alias +createaliasnode(char *txt, int flags) +{ + Alias al; + + al = (Alias) zshcalloc(sizeof *al); + al->node.flags = flags; + al->text = txt; + al->inuse = 0; + return al; +} + +/**/ +static void +freealiasnode(HashNode hn) +{ + Alias al = (Alias) hn; + + zsfree(al->node.nam); + zsfree(al->text); + zfree(al, sizeof(struct alias)); +} + +/* Print an alias */ + +/**/ +static void +printaliasnode(HashNode hn, int printflags) +{ + Alias a = (Alias) hn; + + if (printflags & PRINT_NAMEONLY) { + zputs(a->node.nam, stdout); + putchar('\n'); + return; + } + + if (printflags & PRINT_WHENCE_WORD) { + if (a->node.flags & ALIAS_SUFFIX) + printf("%s: suffix alias\n", a->node.nam); + else if (a->node.flags & ALIAS_GLOBAL) + printf("%s: global alias\n", a->node.nam); + else + printf("%s: alias\n", a->node.nam); + return; + } + + if (printflags & PRINT_WHENCE_SIMPLE) { + zputs(a->text, stdout); + putchar('\n'); + return; + } + + if (printflags & PRINT_WHENCE_CSH) { + nicezputs(a->node.nam, stdout); + printf(": "); + if (a->node.flags & ALIAS_SUFFIX) + printf("suffix "); + else if (a->node.flags & ALIAS_GLOBAL) + printf("globally "); + printf ("aliased to "); + nicezputs(a->text, stdout); + putchar('\n'); + return; + } + + if (printflags & PRINT_WHENCE_VERBOSE) { + nicezputs(a->node.nam, stdout); + printf(" is a"); + if (a->node.flags & ALIAS_SUFFIX) + printf(" suffix"); + else if (a->node.flags & ALIAS_GLOBAL) + printf(" global"); + else + printf("n"); + printf(" alias for "); + nicezputs(a->text, stdout); + putchar('\n'); + return; + } + + if (printflags & PRINT_LIST) { + /* Fast fail on unrepresentable values. */ + if (strchr(a->node.nam, '=')) { + zwarn("invalid alias '%s' encountered while printing aliases", + a->node.nam); + /* ### TODO: Return an error status to the C caller */ + return; + } + + /* Normal path. */ + printf("alias "); + if (a->node.flags & ALIAS_SUFFIX) + printf("-s "); + else if (a->node.flags & ALIAS_GLOBAL) + printf("-g "); + + /* If an alias begins with `-' or `+', then we must output `-- ' + * first, so that it is not interpreted as an option. */ + if(a->node.nam[0] == '-' || a->node.nam[0] == '+') + printf("-- "); + } + + quotedzputs(a->node.nam, stdout); + putchar('='); + quotedzputs(a->text, stdout); + + putchar('\n'); +} + +/*************************************/ +/* History Line Hash Table Functions */ +/*************************************/ + +/**/ +void +createhisttable(void) +{ + histtab = newhashtable(599, "histtab", NULL); + + histtab->hash = histhasher; + histtab->emptytable = emptyhisttable; + histtab->filltable = NULL; + histtab->cmpnodes = histstrcmp; + histtab->addnode = addhistnode; + histtab->getnode = gethashnode2; + histtab->getnode2 = gethashnode2; + histtab->removenode = removehashnode; + histtab->disablenode = NULL; + histtab->enablenode = NULL; + histtab->freenode = freehistnode; + histtab->printnode = NULL; +} + +/**/ +unsigned +histhasher(const char *str) +{ + unsigned hashval = 0; + + while (inblank(*str)) str++; + + while (*str) { + if (inblank(*str)) { + do str++; while (inblank(*str)); + if (*str) + hashval += (hashval << 5) + ' '; + } + else + hashval += (hashval << 5) + *(unsigned char *)str++; + } + return hashval; +} + +/**/ +void +emptyhisttable(HashTable ht) +{ + emptyhashtable(ht); + if (hist_ring) + histremovedups(); +} + +/* Compare two strings with normalized white-space */ + +/**/ +int +histstrcmp(const char *str1, const char *str2) +{ + while (inblank(*str1)) str1++; + while (inblank(*str2)) str2++; + while (*str1 && *str2) { + if (inblank(*str1)) { + if (!inblank(*str2)) + break; + do str1++; while (inblank(*str1)); + do str2++; while (inblank(*str2)); + } + else { + if (*str1 != *str2) + break; + str1++; + str2++; + } + } + return *str1 - *str2; +} + +/**/ +void +addhistnode(HashTable ht, char *nam, void *nodeptr) +{ + HashNode oldnode = addhashnode2(ht, nam, nodeptr); + Histent he = (Histent)nodeptr; + if (oldnode && oldnode != (HashNode)nodeptr) { + if (he->node.flags & HIST_MAKEUNIQUE + || (he->node.flags & HIST_FOREIGN && (Histent)oldnode == he->up)) { + (void) addhashnode2(ht, oldnode->nam, oldnode); /* restore hash */ + he->node.flags |= HIST_DUP; + he->node.flags &= ~HIST_MAKEUNIQUE; + } + else { + oldnode->flags |= HIST_DUP; + if (hist_ignore_all_dups) + freehistnode(oldnode); /* Remove the old dup */ + } + } + else + he->node.flags &= ~HIST_MAKEUNIQUE; +} + +/**/ +void +freehistnode(HashNode nodeptr) +{ + freehistdata((Histent)nodeptr, 1); + zfree(nodeptr, sizeof (struct histent)); +} + +/**/ +void +freehistdata(Histent he, int unlink) +{ + if (!he) + return; + + if (he == &curline) + return; + + if (!(he->node.flags & (HIST_DUP | HIST_TMPSTORE))) + removehashnode(histtab, he->node.nam); + + zsfree(he->node.nam); + if (he->nwords) + zfree(he->words, he->nwords*2*sizeof(short)); + + if (unlink) { + if (!--histlinect) + hist_ring = NULL; + else { + if (he == hist_ring) + hist_ring = hist_ring->up; + he->up->down = he->down; + he->down->up = he->up; + } + } +} + + +/*********************************************************************** + * Directory name cache mechanism + * + * The idea of this is that there are various shell structures, + * notably functions, that record the directories with which they + * are associated. Rather than store the full string each time, + * we store a pointer to the same location and count the references. + * This is optimised so that retrieval is quick at the expense of + * searching the list when setting up the structure, which is a much + * rarer operation. + * + * There is nothing special about the fact that the strings are + * directories, except for the assumptions for efficiency that many + * structures will point to the same one, and that there are not too + * many different directories associated with the shell. + **********************************************************************/ + +struct dircache_entry +{ + /* Name of directory in cache */ + char *name; + /* Number of references to it */ + int refs; +}; + +/* + * dircache is the cache, of length dircache_size. + * dircache_lastentry is the last entry used, an optimisation + * for multiple references to the same directory, e.g + * "autoload /blah/blah/\*". + */ +static struct dircache_entry *dircache, *dircache_lastentry; +static int dircache_size; + +/* + * Set *name to point to a cached version of value. + * value is copied so may come from any source. + * + * If value is NULL, look for the existing value of *name (safe if this + * too is NULL) and remove a reference to it from the cache. If it's + * not found in the cache, it's assumed to be an allocated string and + * freed --- this currently occurs for a shell function that's been + * loaded as the filename is now a full path, not just a directory, + * though we may one day optimise this to a cached directory plus a + * name, too. Note --- the function does *not* otherwise check + * if *name points to something already cached, so this is + * necessary any time *name may already be in the cache. + */ + +/**/ +mod_export void +dircache_set(char **name, char *value) +{ + struct dircache_entry *dcptr, *dcnew; + + if (!value) { + if (!*name) + return; + if (!dircache_size) { + zsfree(*name); + *name = NULL; + return; + } + + for (dcptr = dircache; dcptr < dircache + dircache_size; dcptr++) + { + /* Must be a pointer much, not a string match */ + if (*name == dcptr->name) + { + --dcptr->refs; + if (!dcptr->refs) { + ptrdiff_t ind = dcptr - dircache; + zsfree(dcptr->name); + --dircache_size; + + if (!dircache_size) { + zfree(dircache, sizeof(*dircache)); + dircache = NULL; + dircache_lastentry = NULL; + *name = NULL; + return; + } + dcnew = (struct dircache_entry *) + zalloc(dircache_size * sizeof(*dcnew)); + if (ind) + memcpy(dcnew, dircache, ind * sizeof(*dcnew)); + if (ind < dircache_size) + memcpy(dcnew + ind, dcptr + 1, + (dircache_size - ind) * sizeof(*dcnew)); + zfree(dircache, (dircache_size+1)*sizeof(*dcnew)); + dircache = dcnew; + dircache_lastentry = NULL; + } + *name = NULL; + return; + } + } + zsfree(*name); + *name = NULL; + } else { + /* + * As the function path has been resolved to a particular + * location, we'll store it as an absolute path. + */ + if (*value != '/') { + value = zhtricat(metafy(zgetcwd(), -1, META_HEAPDUP), + "/", value); + value = xsymlink(value, 1); + } + /* + * We'll maintain the cache at exactly the right size rather + * than overallocating. The rationale here is that typically + * we'll get a lot of functions in a small number of directories + * so the complexity overhead of maintaining a separate count + * isn't really matched by the efficiency gain. + */ + if (dircache_lastentry && + !strcmp(value, dircache_lastentry->name)) { + *name = dircache_lastentry->name; + ++dircache_lastentry->refs; + return; + } else if (!dircache_size) { + dircache_size = 1; + dcptr = dircache = + (struct dircache_entry *)zalloc(sizeof(*dircache)); + } else { + for (dcptr = dircache; dcptr < dircache + dircache_size; dcptr++) + { + if (!strcmp(value, dcptr->name)) { + *name = dcptr->name; + ++dcptr->refs; + return; + } + } + ++dircache_size; + dircache = (struct dircache_entry *) + zrealloc(dircache, sizeof(*dircache) * dircache_size); + dcptr = dircache + dircache_size - 1; + } + dcptr->name = ztrdup(value); + *name = dcptr->name; + dcptr->refs = 1; + dircache_lastentry = dcptr; + } +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/hashtable.h b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/hashtable.h new file mode 100644 index 00000000..21398e17 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/hashtable.h @@ -0,0 +1,69 @@ +/* + * hashtable.h - header file for hash table handling code + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +/* Builtin function numbers; used by handler functions that handle more * + * than one builtin. Note that builtins such as compctl, that are not * + * overloaded, don't get a number. */ + +#define BIN_TYPESET 0 +#define BIN_BG 1 +#define BIN_FG 2 +#define BIN_JOBS 3 +#define BIN_WAIT 4 +#define BIN_DISOWN 5 +#define BIN_BREAK 6 +#define BIN_CONTINUE 7 +#define BIN_EXIT 8 +#define BIN_RETURN 9 +#define BIN_CD 10 +#define BIN_POPD 11 +#define BIN_PUSHD 12 +#define BIN_PRINT 13 +#define BIN_EVAL 14 +#define BIN_SCHED 15 +#define BIN_FC 16 +#define BIN_R 17 +#define BIN_PUSHLINE 18 +#define BIN_LOGOUT 19 +#define BIN_TEST 20 +#define BIN_BRACKET 21 +#define BIN_READONLY 22 +#define BIN_ECHO 23 +#define BIN_DISABLE 24 +#define BIN_ENABLE 25 +#define BIN_PRINTF 26 +#define BIN_COMMAND 27 +#define BIN_UNHASH 28 +#define BIN_UNALIAS 29 +#define BIN_UNFUNCTION 30 +#define BIN_UNSET 31 + +/* These currently depend on being 0 and 1. */ +#define BIN_SETOPT 0 +#define BIN_UNSETOPT 1 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/init.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/init.c new file mode 100644 index 00000000..e9e6be9b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/init.c @@ -0,0 +1,1792 @@ +/* + * init.c - main loop and initialization routines + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" + +#include "zshpaths.h" +#include "zshxmods.h" + +#include "init.pro" + +#include "version.h" + +/**/ +int noexitct = 0; + +/* buffer for $_ and its length */ + +/**/ +char *zunderscore; + +/**/ +int underscorelen, underscoreused; + +/* what level of sourcing we are at */ + +/**/ +int sourcelevel; + +/* the shell tty fd */ + +/**/ +mod_export int SHTTY; + +/* the FILE attached to the shell tty */ + +/**/ +mod_export FILE *shout; + +/* termcap strings */ + +/**/ +mod_export char *tcstr[TC_COUNT]; + +/* lengths of each termcap string */ + +/**/ +mod_export int tclen[TC_COUNT]; + +/* Values of the li, co and am entries */ + +/**/ +int tclines, tccolumns; +/**/ +mod_export int hasam, hasbw, hasxn, hasye; + +/* Value of the Co (max_colors) entry: may not be set */ + +/**/ +mod_export int tccolours; + +/* SIGCHLD mask */ + +/**/ +mod_export sigset_t sigchld_mask; + +/**/ +mod_export struct hookdef zshhooks[] = { + HOOKDEF("exit", NULL, HOOKF_ALL), + HOOKDEF("before_trap", NULL, HOOKF_ALL), + HOOKDEF("after_trap", NULL, HOOKF_ALL), +}; + +/* keep executing lists until EOF found */ + +/**/ +enum loop_return +loop(int toplevel, int justonce) +{ + Eprog prog; + int err, non_empty = 0; + + queue_signals(); + pushheap(); + if (!toplevel) + zcontext_save(); + for (;;) { + freeheap(); + if (stophist == 3) /* re-entry via preprompt() */ + hend(NULL); + hbegin(1); /* init history mech */ + if (isset(SHINSTDIN)) { + setblock_stdin(); + if (interact && toplevel) { + int hstop = stophist; + stophist = 3; + /* + * Reset all errors including the interrupt error status + * immediately, so preprompt runs regardless of what + * just happened. We'll reset again below as a + * precaution to ensure we get back to the command line + * no matter what. + */ + errflag = 0; + preprompt(); + if (stophist != 3) + hbegin(1); + else + stophist = hstop; + /* + * Reset all errors, including user interupts. + * This is what allows ^C in an interactive shell + * to return us to the command line. + */ + errflag = 0; + } + } + use_exit_printed = 0; + intr(); /* interrupts on */ + lexinit(); /* initialize lexical state */ + if (!(prog = parse_event(ENDINPUT))) { + /* if we couldn't parse a list */ + hend(NULL); + if ((tok == ENDINPUT && !errflag) || + (tok == LEXERR && (!isset(SHINSTDIN) || !toplevel)) || + justonce) + break; + if (exit_pending) { + /* + * Something down there (a ZLE function?) decided + * to exit when there was stuff to clear up. + * Handle that now. + */ + stopmsg = 1; + zexit(exit_pending >> 1, 0); + } + if (tok == LEXERR && !lastval) + lastval = 1; + continue; + } + if (hend(prog)) { + enum lextok toksav = tok; + + non_empty = 1; + if (toplevel && + (getshfunc("preexec") || + paramtab->getnode(paramtab, "preexec" HOOK_SUFFIX))) { + LinkList args; + char *cmdstr; + + /* + * As we're about to freeheap() or popheap() + * anyway, there's no gain in using permanent + * storage here. + */ + args = newlinklist(); + addlinknode(args, "preexec"); + /* If curline got dumped from the history, we don't know + * what the user typed. */ + if (hist_ring && curline.histnum == curhist) + addlinknode(args, hist_ring->node.nam); + else + addlinknode(args, ""); + addlinknode(args, dupstring(getjobtext(prog, NULL))); + addlinknode(args, cmdstr = getpermtext(prog, NULL, 0)); + + callhookfunc("preexec", args, 1, NULL); + + /* The only permanent storage is from getpermtext() */ + zsfree(cmdstr); + /* + * Note this does *not* remove a user interrupt error + * condition, even though we're at the top level loop: + * that would be inconsistent with the case where + * we didn't execute a preexec function. This is + * an implementation detail that an interrupting user + * does't care about. + */ + errflag &= ~ERRFLAG_ERROR; + } + if (stopmsg) /* unset 'you have stopped jobs' flag */ + stopmsg--; + execode(prog, 0, 0, toplevel ? "toplevel" : "file"); + tok = toksav; + if (toplevel) + noexitct = 0; + } + if (ferror(stderr)) { + zerr("write error"); + clearerr(stderr); + } + if (subsh) /* how'd we get this far in a subshell? */ + exit(lastval); + if (((!interact || sourcelevel) && errflag) || retflag) + break; + if (isset(SINGLECOMMAND) && toplevel) { + dont_queue_signals(); + if (sigtrapped[SIGEXIT]) + dotrap(SIGEXIT); + exit(lastval); + } + if (justonce) + break; + } + err = errflag; + if (!toplevel) + zcontext_restore(); + popheap(); + unqueue_signals(); + + if (err) + return LOOP_ERROR; + if (!non_empty) + return LOOP_EMPTY; + return LOOP_OK; +} + +static int restricted; + +/**/ +static void +parseargs(char *zsh_name, char **argv, char **runscript, char **cmdptr) +{ + char **x; + LinkList paramlist; + int flags = PARSEARGS_TOPLEVEL; + if (**argv == '-') + flags |= PARSEARGS_LOGIN; + + argzero = posixzero = *argv++; + SHIN = 0; + + /* + * parseopts sets up some options after we deal with emulation in + * order to be consistent --- the code in parseopts_setemulate() is + * matched by code at the end of the present function. + */ + + if (parseopts(zsh_name, &argv, opts, cmdptr, NULL, flags)) + exit(1); + + /* + * USEZLE remains set if the shell has access to a terminal and + * is not reading from some other source as indicated by SHINSTDIN. + * SHINSTDIN becomes set below if there is no command argument, + * but it is the explicit setting (or not) that matters to USEZLE. + * USEZLE may also become unset in init_io() if the shell is not + * interactive or the terminal cannot be re-opened read/write. + */ + if (opts[SHINSTDIN]) + opts[USEZLE] = (opts[USEZLE] && isatty(0)); + + paramlist = znewlinklist(); + if (*argv) { + if (unset(SHINSTDIN)) { + posixzero = *argv; + if (*cmdptr) + argzero = *argv; + else + *runscript = *argv; + opts[INTERACTIVE] &= 1; + argv++; + } + while (*argv) + zaddlinknode(paramlist, ztrdup(*argv++)); + } else if (!*cmdptr) + opts[SHINSTDIN] = 1; + if(isset(SINGLECOMMAND)) + opts[INTERACTIVE] &= 1; + opts[INTERACTIVE] = !!opts[INTERACTIVE]; + if (opts[MONITOR] == 2) + opts[MONITOR] = opts[INTERACTIVE]; + if (opts[HASHDIRS] == 2) + opts[HASHDIRS] = opts[INTERACTIVE]; + pparams = x = (char **) zshcalloc((countlinknodes(paramlist) + 1) * sizeof(char *)); + + while ((*x++ = (char *)getlinknode(paramlist))); + free(paramlist); + argzero = ztrdup(argzero); + posixzero = ztrdup(posixzero); +} + +/* Insert into list in order of pointer value */ + +/**/ +static void +parseopts_insert(LinkList optlist, char *base, int optno) +{ + LinkNode node; + void *ptr = base + (optno < 0 ? -optno : optno); + + for (node = firstnode(optlist); node; incnode(node)) { + if (ptr < getdata(node)) { + insertlinknode(optlist, prevnode(node), ptr); + return; + } + } + + addlinknode(optlist, ptr); +} + +/* + * This sets the global emulation plus the options we traditionally + * set immediately after that. This is just for historical consistency + * --- I don't think those options actually need to be set here. + */ +static void parseopts_setemulate(char *nam, int flags) +{ + emulate(nam, 1, &emulation, opts); /* initialises most options */ + opts[LOGINSHELL] = ((flags & PARSEARGS_LOGIN) != 0); + opts[PRIVILEGED] = (getuid() != geteuid() || getgid() != getegid()); + + /* There's a bit of trickery with opts[INTERACTIVE] here. It starts * + * at a value of 2 (instead of 1) or 0. If it is explicitly set on * + * the command line, it goes to 1 or 0. If input is coming from * + * somewhere that normally makes the shell non-interactive, we do * + * "opts[INTERACTIVE] &= 1", so that only a *default* on state will * + * be changed. At the end of the function, a value of 2 gets * + * changed to 1. */ + opts[INTERACTIVE] = isatty(0) ? 2 : 0; + /* + * MONITOR is similar: we initialise it to 2, and if it's + * still 2 at the end, we set it to the value of INTERACTIVE. + */ + opts[MONITOR] = 2; /* may be unset in init_io() */ + opts[HASHDIRS] = 2; /* same relationship to INTERACTIVE */ + opts[USEZLE] = 1; /* see below, related to SHINSTDIN */ + opts[SHINSTDIN] = 0; + opts[SINGLECOMMAND] = 0; +} + +/* + * Parse shell options. + * + * If (flags & PARSEARGS_TOPLEVEL): + * - we are doing shell initilisation + * - nam is the name under which the shell was started + * - set up emulation and standard options based on that. + * Otherwise: + * - nam is a command name + * - don't exit on failure. + * + * If optlist is not NULL, it used to form a list of pointers + * into new_opts indicating which options have been changed. + */ + +/**/ +mod_export int +parseopts(char *nam, char ***argvp, char *new_opts, char **cmdp, + LinkList optlist, int flags) +{ + int optionbreak = 0; + int action, optno; + char **argv = *argvp; + int toplevel = ((flags & PARSEARGS_TOPLEVEL) != 0u); + int emulate_required = toplevel; + char *top_emulation = nam; + + *cmdp = 0; +#define WARN_OPTION(F, S) \ + do { \ + if (!toplevel) \ + zwarnnam(nam, F, S); \ + else \ + zerr(F, S); \ + } while (0) +#define LAST_OPTION(N) \ + do { \ + if (!toplevel) { \ + if (*argv) \ + argv++; \ + goto doneargv; \ + } else exit(N); \ + } while(0) + + /* loop through command line options (begins with "-" or "+") */ + while (!optionbreak && *argv && (**argv == '-' || **argv == '+')) { + char *args = *argv; + action = (**argv == '-'); + if (!argv[0][1]) + *argv = "--"; + while (*++*argv) { + if (**argv == '-') { + if (!argv[0][1]) { + /* The pseudo-option `--' signifies the end of options. */ + argv++; + goto doneoptions; + } + if (!toplevel || *argv != args+1 || **argv != '-') + goto badoptionstring; + /* GNU-style long options */ + ++*argv; + if (!strcmp(*argv, "version")) { + printf("zsh %s (%s-%s-%s)\n", + ZSH_VERSION, MACHTYPE, VENDOR, OSTYPE); + LAST_OPTION(0); + } + if (!strcmp(*argv, "help")) { + printhelp(); + LAST_OPTION(0); + } + if (!strcmp(*argv, "emulate")) { + ++argv; + if (!*argv) { + zerr("--emulate: argument required"); + exit(1); + } + if (!emulate_required) { + zerr("--emulate: must precede other options"); + exit(1); + } + top_emulation = *argv; + break; + } + /* `-' characters are allowed in long options */ + for(args = *argv; *args; args++) + if(*args == '-') + *args = '_'; + goto longoptions; + } + + if (unset(SHOPTIONLETTERS) && **argv == 'b') { + if (emulate_required) { + parseopts_setemulate(top_emulation, flags); + emulate_required = 0; + } + /* -b ends options at the end of this argument */ + optionbreak = 1; + } else if (**argv == 'c') { + if (emulate_required) { + parseopts_setemulate(top_emulation, flags); + emulate_required = 0; + } + /* -c command */ + *cmdp = *argv; + new_opts[INTERACTIVE] &= 1; + if (toplevel) + scriptname = scriptfilename = ztrdup("zsh"); + } else if (**argv == 'o') { + if (!*++*argv) + argv++; + if (!*argv) { + WARN_OPTION("string expected after -o", NULL); + return 1; + } + longoptions: + if (emulate_required) { + parseopts_setemulate(top_emulation, flags); + emulate_required = 0; + } + if (!(optno = optlookup(*argv))) { + WARN_OPTION("no such option: %s", *argv); + return 1; + } else if (optno == RESTRICTED && toplevel) { + restricted = action; + } else if ((optno == EMACSMODE || optno == VIMODE) && !toplevel) { + WARN_OPTION("can't change option: %s", *argv); + } else { + if (dosetopt(optno, action, toplevel, new_opts) && + !toplevel) { + WARN_OPTION("can't change option: %s", *argv); + } else if (optlist) { + parseopts_insert(optlist, new_opts, optno); + } + } + break; + } else if (isspace(STOUC(**argv))) { + /* zsh's typtab not yet set, have to use ctype */ + while (*++*argv) + if (!isspace(STOUC(**argv))) { + badoptionstring: + WARN_OPTION("bad option string: '%s'", args); + return 1; + } + break; + } else { + if (emulate_required) { + parseopts_setemulate(top_emulation, flags); + emulate_required = 0; + } + if (!(optno = optlookupc(**argv))) { + WARN_OPTION("bad option: -%c", **argv); + return 1; + } else if (optno == RESTRICTED && toplevel) { + restricted = action; + } else if ((optno == EMACSMODE || optno == VIMODE) && + !toplevel) { + WARN_OPTION("can't change option: %s", *argv); + } else { + if (dosetopt(optno, action, toplevel, new_opts) && + !toplevel) { + WARN_OPTION("can't change option: -%c", **argv); + } else if (optlist) { + parseopts_insert(optlist, new_opts, optno); + } + } + } + } + argv++; + } + doneoptions: + if (*cmdp) { + if (!*argv) { + WARN_OPTION("string expected after -%s", *cmdp); + return 1; + } + *cmdp = *argv++; + } + doneargv: + *argvp = argv; + if (emulate_required) { + parseopts_setemulate(top_emulation, flags); + emulate_required = 0; + } + return 0; +} + +/**/ +static void +printhelp(void) +{ + printf("Usage: %s [] [ ...]\n", argzero); + printf("\nSpecial options:\n"); + printf(" --help show this message, then exit\n"); + printf(" --version show zsh version number, then exit\n"); + if(unset(SHOPTIONLETTERS)) + printf(" -b end option processing, like --\n"); + printf(" -c take first argument as a command to execute\n"); + printf(" -o OPTION set an option by name (see below)\n"); + printf("\nNormal options are named. An option may be turned on by\n"); + printf("`-o OPTION', `--OPTION', `+o no_OPTION' or `+-no-OPTION'. An\n"); + printf("option may be turned off by `-o no_OPTION', `--no-OPTION',\n"); + printf("`+o OPTION' or `+-OPTION'. Options are listed below only in\n"); + printf("`--OPTION' or `--no-OPTION' form.\n"); + printoptionlist(); +} + +/**/ +mod_export void +init_io(char *cmd) +{ + static char outbuf[BUFSIZ], errbuf[BUFSIZ]; + +#ifdef RSH_BUG_WORKAROUND + int i; +#endif + +/* stdout, stderr fully buffered */ +#ifdef _IOFBF + setvbuf(stdout, outbuf, _IOFBF, BUFSIZ); + setvbuf(stderr, errbuf, _IOFBF, BUFSIZ); +#else + setbuffer(stdout, outbuf, BUFSIZ); + setbuffer(stderr, errbuf, BUFSIZ); +#endif + +/* This works around a bug in some versions of in.rshd. * + * Currently this is not defined by default. */ +#ifdef RSH_BUG_WORKAROUND + if (cmd) { + for (i = 3; i < 10; i++) + close(i); + } +#else + (void)cmd; +#endif + + if (shout) { + /* + * Check if shout was set to stderr, if so don't close it. + * We do this if we are interactive but don't have a + * terminal. + */ + if (shout != stderr) + fclose(shout); + shout = 0; + } + if (SHTTY != -1) { + zclose(SHTTY); + SHTTY = -1; + } + + /* Send xtrace output to stderr -- see execcmd() */ + xtrerr = stderr; + + /* Make sure the tty is opened read/write. */ + if (isatty(0)) { + zsfree(ttystrname); + if ((ttystrname = ztrdup(ttyname(0)))) { + SHTTY = movefd(open(ttystrname, O_RDWR | O_NOCTTY)); +#ifdef TIOCNXCL + /* + * See if the terminal claims to be busy. If so, and fd 0 + * is a terminal, try and set non-exclusive use for that. + * This is something to do with Solaris over-cleverness. + */ + if (SHTTY == -1 && errno == EBUSY) + ioctl(0, TIOCNXCL, 0); +#endif + } + /* + * xterm, rxvt and probably all terminal emulators except + * dtterm on Solaris 2.6 & 7 have a bug. Applications are + * unable to open /dev/tty or /dev/pts/ + * because something in Sun's STREAMS modules doesn't like + * it. The open() call fails with EBUSY which is not even + * listed as a possibility in the open(2) man page. So we'll + * try to outsmart The Company. -- + * + * Presumably there's no harm trying this on any OS, given that + * isatty(0) worked but opening the tty didn't. Possibly we won't + * get the tty read/write, but it's the best we can do -- pws + * + * Try both stdin and stdout before trying /dev/tty. -- Bart + */ +#if defined(HAVE_FCNTL_H) && defined(F_GETFL) +#define rdwrtty(fd) ((fcntl(fd, F_GETFL, 0) & O_RDWR) == O_RDWR) +#else +#define rdwrtty(fd) 1 +#endif + if (SHTTY == -1 && rdwrtty(0)) { + SHTTY = movefd(dup(0)); + } + } + if (SHTTY == -1 && isatty(1) && rdwrtty(1) && + (SHTTY = movefd(dup(1))) != -1) { + zsfree(ttystrname); + ttystrname = ztrdup(ttyname(1)); + } + if (SHTTY == -1 && + (SHTTY = movefd(open("/dev/tty", O_RDWR | O_NOCTTY))) != -1) { + zsfree(ttystrname); + ttystrname = ztrdup(ttyname(SHTTY)); + } + if (SHTTY == -1) { + zsfree(ttystrname); + ttystrname = ztrdup(""); + } else { +#ifdef FD_CLOEXEC + long fdflags = fcntl(SHTTY, F_GETFD, 0); + if (fdflags != (long)-1) { + fdflags |= FD_CLOEXEC; + fcntl(SHTTY, F_SETFD, fdflags); + } +#endif + if (!ttystrname) + ttystrname = ztrdup("/dev/tty"); + } + + /* We will only use zle if shell is interactive, * + * SHTTY != -1, and shout != 0 */ + if (interact) { + init_shout(); + if(!SHTTY || !shout) + opts[USEZLE] = 0; + } else + opts[USEZLE] = 0; + +#ifdef JOB_CONTROL + /* If interactive, make sure the shell is in the foreground and is the + * process group leader. + */ + mypid = (zlong)getpid(); + if (opts[MONITOR] && (SHTTY != -1)) { + origpgrp = GETPGRP(); + acquire_pgrp(); /* might also clear opts[MONITOR] */ + } else + opts[MONITOR] = 0; +#else + opts[MONITOR] = 0; +#endif +} + +/**/ +mod_export void +init_shout(void) +{ + static char shoutbuf[BUFSIZ]; +#if defined(JOB_CONTROL) && defined(TIOCSETD) && defined(NTTYDISC) + int ldisc; +#endif + + if (SHTTY == -1) + { + /* Since we're interactive, it's nice to have somewhere to write. */ + shout = stderr; + return; + } + +#if defined(JOB_CONTROL) && defined(TIOCSETD) && defined(NTTYDISC) + ldisc = NTTYDISC; + ioctl(SHTTY, TIOCSETD, (char *)&ldisc); +#endif + + /* Associate terminal file descriptor with a FILE pointer */ + shout = fdopen(SHTTY, "w"); +#ifdef _IOFBF + if (shout) + setvbuf(shout, shoutbuf, _IOFBF, BUFSIZ); +#endif + + gettyinfo(&shttyinfo); /* get tty state */ +#if defined(__sgi) + if (shttyinfo.tio.c_cc[VSWTCH] <= 0) /* hack for irises */ + shttyinfo.tio.c_cc[VSWTCH] = CSWTCH; +#endif +} + +/* names of the termcap strings we want */ + +static char *tccapnams[TC_COUNT] = { + "cl", "le", "LE", "nd", "RI", "up", "UP", "do", + "DO", "dc", "DC", "ic", "IC", "cd", "ce", "al", "dl", "ta", + "md", "so", "us", "me", "se", "ue", "ch", + "ku", "kd", "kl", "kr", "sc", "rc", "bc", "AF", "AB" +}; + +/**/ +mod_export char * +tccap_get_name(int cap) +{ + if (cap >= TC_COUNT) { +#ifdef DEBUG + dputs("name of invalid capability %d requested", cap); +#endif + return ""; + } + return tccapnams[cap]; +} + +/* Initialise termcap */ + +/**/ +mod_export int +init_term(void) +{ +#ifndef TGETENT_ACCEPTS_NULL + static char termbuf[2048]; /* the termcap buffer */ +#endif + + if (!*term) { + termflags |= TERM_UNKNOWN; + return 0; + } + + /* unset zle if using zsh under emacs */ + if (!strcmp(term, "emacs")) + opts[USEZLE] = 0; + +#ifdef TGETENT_ACCEPTS_NULL + /* If possible, we let tgetent allocate its own termcap buffer */ + if (tgetent(NULL, term) != TGETENT_SUCCESS) +#else + if (tgetent(termbuf, term) != TGETENT_SUCCESS) +#endif + { + if (interact) + zerr("can't find terminal definition for %s", term); + errflag &= ~ERRFLAG_ERROR; + termflags |= TERM_BAD; + return 0; + } else { + char tbuf[1024], *pp; + int t0; + + termflags &= ~TERM_BAD; + termflags &= ~TERM_UNKNOWN; + for (t0 = 0; t0 != TC_COUNT; t0++) { + pp = tbuf; + zsfree(tcstr[t0]); + /* AIX tgetstr() ignores second argument */ + if (!(pp = tgetstr(tccapnams[t0], &pp))) + tcstr[t0] = NULL, tclen[t0] = 0; + else { + tclen[t0] = strlen(pp); + tcstr[t0] = (char *) zalloc(tclen[t0] + 1); + memcpy(tcstr[t0], pp, tclen[t0] + 1); + } + } + + /* check whether terminal has automargin (wraparound) capability */ + hasam = tgetflag("am"); + hasbw = tgetflag("bw"); + hasxn = tgetflag("xn"); /* also check for newline wraparound glitch */ + hasye = tgetflag("YE"); /* print in last column does carriage return */ + + tclines = tgetnum("li"); + tccolumns = tgetnum("co"); + tccolours = tgetnum("Co"); + + /* if there's no termcap entry for cursor up, use single line mode: * + * this is flagged by termflags which is examined in zle_refresh.c * + */ + if (tccan(TCUP)) + termflags &= ~TERM_NOUP; + else { + zsfree(tcstr[TCUP]); + tcstr[TCUP] = NULL; + termflags |= TERM_NOUP; + } + + /* most termcaps don't define "bc" because they use \b. */ + if (!tccan(TCBACKSPACE)) { + zsfree(tcstr[TCBACKSPACE]); + tcstr[TCBACKSPACE] = ztrdup("\b"); + tclen[TCBACKSPACE] = 1; + } + + /* if there's no termcap entry for cursor left, use backspace. */ + if (!tccan(TCLEFT)) { + zsfree(tcstr[TCLEFT]); + tcstr[TCLEFT] = ztrdup(tcstr[TCBACKSPACE]); + tclen[TCLEFT] = tclen[TCBACKSPACE]; + } + + if (tccan(TCSAVECURSOR) && !tccan(TCRESTRCURSOR)) { + tclen[TCSAVECURSOR] = 0; + zsfree(tcstr[TCSAVECURSOR]); + tcstr[TCSAVECURSOR] = NULL; + } + + /* if the termcap entry for down is \n, don't use it. */ + if (tccan(TCDOWN) && tcstr[TCDOWN][0] == '\n') { + tclen[TCDOWN] = 0; + zsfree(tcstr[TCDOWN]); + tcstr[TCDOWN] = NULL; + } + + /* if there's no termcap entry for clear, use ^L. */ + if (!tccan(TCCLEARSCREEN)) { + zsfree(tcstr[TCCLEARSCREEN]); + tcstr[TCCLEARSCREEN] = ztrdup("\14"); + tclen[TCCLEARSCREEN] = 1; + } + rprompt_indent = 1; /* If you change this, update rprompt_indent_unsetfn() */ + /* The following is an attempt at a heuristic, + * but it fails in some cases */ + /* rprompt_indent = ((hasam && !hasbw) || hasye || !tccan(TCLEFT)); */ + } + return 1; +} + +/* Initialize lots of global variables and hash tables */ + +/**/ +void +setupvals(char *cmd, char *runscript, char *zsh_name) +{ +#ifdef USE_GETPWUID + struct passwd *pswd; +#endif + struct timezone dummy_tz; + char *ptr; + int i, j; +#if defined(SITEFPATH_DIR) || defined(FPATH_DIR) || defined (ADDITIONAL_FPATH) || defined(FIXED_FPATH_DIR) +#define FPATH_NEEDS_INIT 1 + char **fpathptr; +# if defined(FPATH_DIR) && defined(FPATH_SUBDIRS) + char *fpath_subdirs[] = FPATH_SUBDIRS; +# endif +# if defined(ADDITIONAL_FPATH) + char *more_fndirs[] = ADDITIONAL_FPATH; + int more_fndirs_len; +# endif +# ifdef FIXED_FPATH_DIR +# define FIXED_FPATH_LEN 1 +# else +# define FIXED_FPATH_LEN 0 +# endif +# ifdef SITEFPATH_DIR +# define SITE_FPATH_LEN 1 +# else +# define SITE_FPATH_LEN 0 +# endif + int fpathlen = FIXED_FPATH_LEN + SITE_FPATH_LEN; +#endif + int close_fds[10], tmppipe[2]; + + /* + * Workaround a problem with NIS (in one guise or another) which + * grabs file descriptors and keeps them for future reference. + * We don't want these to be in the range where the user can + * open fd's, i.e. 0 to 9 inclusive. So we make sure all + * fd's in that range are in use. + */ + memset(close_fds, 0, 10*sizeof(int)); + if (pipe(tmppipe) == 0) { + /* + * Strategy: Make sure we have at least fd 0 open (hence + * the pipe). From then on, keep dup'ing until we are + * up to 9. If we go over the top, close immediately, else + * mark for later closure. + */ + i = -1; /* max fd we have checked */ + while (i < 9) { + /* j is current fd */ + if (i < tmppipe[0]) + j = tmppipe[0]; + else if (i < tmppipe[1]) + j = tmppipe[1]; + else { + j = dup(0); + if (j == -1) + break; + } + if (j < 10) + close_fds[j] = 1; + else + close(j); + if (i < j) + i = j; + } + if (i < tmppipe[0]) + close(tmppipe[0]); + if (i < tmppipe[1]) + close(tmppipe[1]); + } + + (void)addhookdefs(NULL, zshhooks, sizeof(zshhooks)/sizeof(*zshhooks)); + + init_eprog(); + + zero_mnumber.type = MN_INTEGER; + zero_mnumber.u.l = 0; + + noeval = 0; + curhist = 0; + histsiz = DEFAULT_HISTSIZE; + inithist(); + + cmdstack = (unsigned char *) zalloc(CMDSTACKSZ); + cmdsp = 0; + + bangchar = '!'; + hashchar = '#'; + hatchar = '^'; + termflags = TERM_UNKNOWN; + curjob = prevjob = coprocin = coprocout = -1; + gettimeofday(&shtimer, &dummy_tz); /* init $SECONDS */ + srand((unsigned int)(shtimer.tv_sec + shtimer.tv_usec)); /* seed $RANDOM */ + + /* Set default path */ + path = (char **) zalloc(sizeof(*path) * 5); + path[0] = ztrdup("/bin"); + path[1] = ztrdup("/usr/bin"); + path[2] = ztrdup("/usr/ucb"); + path[3] = ztrdup("/usr/local/bin"); + path[4] = NULL; + + cdpath = mkarray(NULL); + manpath = mkarray(NULL); + fignore = mkarray(NULL); + +#ifdef FPATH_NEEDS_INIT +# ifdef FPATH_DIR +# ifdef FPATH_SUBDIRS + fpathlen += sizeof(fpath_subdirs)/sizeof(char *); +# else /* FPATH_SUBDIRS */ + fpathlen++; +# endif /* FPATH_SUBDIRS */ +# endif /* FPATH_DIR */ +# if defined(ADDITIONAL_FPATH) + more_fndirs_len = sizeof(more_fndirs)/sizeof(char *); + fpathlen += more_fndirs_len; +# endif /* ADDITONAL_FPATH */ + fpath = fpathptr = (char **)zalloc((fpathlen+1)*sizeof(char *)); +# ifdef FIXED_FPATH_DIR + *fpathptr++ = ztrdup(FIXED_FPATH_DIR); + fpathlen--; +# endif +# ifdef SITEFPATH_DIR + *fpathptr++ = ztrdup(SITEFPATH_DIR); + fpathlen--; +# endif /* SITEFPATH_DIR */ +# if defined(ADDITIONAL_FPATH) + for (j = 0; j < more_fndirs_len; j++) + *fpathptr++ = ztrdup(more_fndirs[j]); +# endif +# ifdef FPATH_DIR +# ifdef FPATH_SUBDIRS +# ifdef ADDITIONAL_FPATH + for (j = more_fndirs_len; j < fpathlen; j++) + *fpathptr++ = tricat(FPATH_DIR, "/", fpath_subdirs[j - more_fndirs_len]); +# else + for (j = 0; j < fpathlen; j++) + *fpathptr++ = tricat(FPATH_DIR, "/", fpath_subdirs[j]); +#endif +# else + *fpathptr++ = ztrdup(FPATH_DIR); +# endif +# endif + *fpathptr = NULL; +#else /* FPATH_NEEDS_INIT */ + fpath = mkarray(NULL); +#endif /* FPATH_NEEDS_INIT */ + + mailpath = mkarray(NULL); + watch = mkarray(NULL); + psvar = mkarray(NULL); + module_path = mkarray(ztrdup(MODULE_DIR)); + modulestab = newmoduletable(17, "modules"); + linkedmodules = znewlinklist(); + + /* Set default prompts */ + if(unset(INTERACTIVE)) { + prompt = ztrdup(""); + prompt2 = ztrdup(""); + } else if (EMULATION(EMULATE_KSH|EMULATE_SH)) { + prompt = ztrdup(privasserted() ? "# " : "$ "); + prompt2 = ztrdup("> "); + } else { + prompt = ztrdup("%m%# "); + prompt2 = ztrdup("%_> "); + } + prompt3 = ztrdup("?# "); + prompt4 = EMULATION(EMULATE_KSH|EMULATE_SH) + ? ztrdup("+ ") : ztrdup("+%N:%i> "); + sprompt = ztrdup("zsh: correct '%R' to '%r' [nyae]? "); + + ifs = EMULATION(EMULATE_KSH|EMULATE_SH) ? + ztrdup(DEFAULT_IFS_SH) : ztrdup(DEFAULT_IFS); + wordchars = ztrdup(DEFAULT_WORDCHARS); + postedit = ztrdup(""); + zunderscore = (char *) zalloc(underscorelen = 32); + underscoreused = 1; + *zunderscore = '\0'; + + zoptarg = ztrdup(""); + zoptind = 1; + + ppid = (zlong) getppid(); + mypid = (zlong) getpid(); + term = ztrdup(""); + + nullcmd = ztrdup("cat"); + readnullcmd = ztrdup(DEFAULT_READNULLCMD); + + /* We cache the uid so we know when to * + * recheck the info for `USERNAME' */ + cached_uid = getuid(); + + /* Get password entry and set info for `USERNAME' */ +#ifdef USE_GETPWUID + if ((pswd = getpwuid(cached_uid))) { + if (EMULATION(EMULATE_ZSH)) + home = metafy(pswd->pw_dir, -1, META_DUP); + cached_username = ztrdup(pswd->pw_name); + } + else +#endif /* USE_GETPWUID */ + { + if (EMULATION(EMULATE_ZSH)) + home = ztrdup("/"); + cached_username = ztrdup(""); + } + + /* + * Try a cheap test to see if we can initialize `PWD' from `HOME'. + * In non-native emulations HOME must come from the environment; + * we're not allowed to set it locally. + */ + if (EMULATION(EMULATE_ZSH)) + ptr = home; + else + ptr = zgetenv("HOME"); + if (ptr && ispwd(ptr)) + pwd = ztrdup(ptr); + else if ((ptr = zgetenv("PWD")) && (strlen(ptr) < PATH_MAX) && + (ptr = metafy(ptr, -1, META_STATIC), ispwd(ptr))) + pwd = ztrdup(ptr); + else { + pwd = NULL; + pwd = metafy(zgetcwd(), -1, META_DUP); + } + + oldpwd = ztrdup(pwd); /* initialize `OLDPWD' = `PWD' */ + + inittyptab(); /* initialize the ztypes table */ + initlextabs(); /* initialize lexing tables */ + + createreswdtable(); /* create hash table for reserved words */ + createaliastables(); /* create hash tables for aliases */ + createcmdnamtable(); /* create hash table for external commands */ + createshfunctable(); /* create hash table for shell functions */ + createbuiltintable(); /* create hash table for builtin commands */ + createnameddirtable(); /* create hash table for named directories */ + createparamtable(); /* create parameter hash table */ + + condtab = NULL; + wrappers = NULL; + +#ifdef TIOCGWINSZ + adjustwinsize(0); +#else + /* columns and lines are normally zero, unless something different * + * was inhereted from the environment. If either of them are zero * + * the setiparam calls below set them to the defaults from termcap */ + setiparam("COLUMNS", zterm_columns); + setiparam("LINES", zterm_lines); +#endif + +#ifdef HAVE_GETRLIMIT + for (i = 0; i != RLIM_NLIMITS; i++) { + getrlimit(i, current_limits + i); + limits[i] = current_limits[i]; + } +#endif + + breaks = loops = 0; + lastmailcheck = time(NULL); + locallevel = sourcelevel = 0; + sfcontext = SFC_NONE; + trap_return = 0; + trap_state = TRAP_STATE_INACTIVE; + noerrexit = NOERREXIT_EXIT | NOERREXIT_RETURN | NOERREXIT_SIGNAL; + nohistsave = 1; + dirstack = znewlinklist(); + bufstack = znewlinklist(); + hsubl = hsubr = NULL; + lastpid = 0; + + get_usage(); + + /* Close the file descriptors we opened to block off 0 to 9 */ + for (i = 0; i < 10; i++) + if (close_fds[i]) + close(i); + + /* Colour sequences for outputting colours in prompts and zle */ + set_default_colour_sequences(); + + if (cmd) + setsparam("ZSH_EXECUTION_STRING", ztrdup(cmd)); + if (runscript) + setsparam("ZSH_SCRIPT", ztrdup(runscript)); + setsparam("ZSH_NAME", ztrdup(zsh_name)); /* NOTE: already metafied early in zsh_main() */ +} + +/* + * Setup shell input, opening any script file (runscript, may be NULL). + * This is deferred until we have a path to search, in case + * PATHSCRIPT is set for sh-compatible behaviour. + */ +static void +setupshin(char *runscript) +{ + if (runscript) { + char *funmeta, *sfname = NULL; + struct stat st; + + funmeta = unmeta(runscript); + /* + * Always search the current directory first. + */ + if (access(funmeta, F_OK) == 0 && + stat(funmeta, &st) >= 0 && + !S_ISDIR(st.st_mode)) + sfname = runscript; + else if (isset(PATHSCRIPT) && !strchr(runscript, '/')) { + /* + * With the PATHSCRIPT option, search the path if no + * path was given in the script name. + */ + funmeta = pathprog(runscript, &sfname); + } + if (!sfname || + (SHIN = movefd(open(funmeta, O_RDONLY | O_NOCTTY))) + == -1) { + zerr("can't open input file: %s", runscript); + exit(127); + } + scriptfilename = sfname; + sfname = argzero; /* copy to avoid race condition */ + argzero = ztrdup(runscript); + zsfree(sfname); /* argzero ztrdup'd in parseargs */ + } + /* + * We only initialise line numbering once there is a script to + * read commands from. + */ + lineno = 1; + /* + * Finish setting up SHIN and its relatives. + */ + bshin = SHIN ? fdopen(SHIN, "r") : stdin; + if (isset(SHINSTDIN) && !SHIN && unset(INTERACTIVE)) { +#ifdef _IONBF + setvbuf(stdin, NULL, _IONBF, 0); +#else + setlinebuf(stdin); +#endif + } +} + +/* Initialize signal handling */ + +/**/ +void +init_signals(void) +{ + if (interact) { + int i; + signal_setmask(signal_mask(0)); + for (i=0; i= 10) + fclose(bshin); + SHIN = movefd(open("/dev/null", O_RDONLY | O_NOCTTY)); + bshin = fdopen(SHIN, "r"); + execstring(cmd, 0, 1, "cmdarg"); + stopmsg = 1; + zexit(lastval, 0); + } + + if (interact && isset(RCS)) + readhistfile(NULL, 0, HFILE_USE_OPTIONS); +} + +/* + * source a file + * Returns one of the SOURCE_* enum values. + */ + +/**/ +mod_export enum source_return +source(char *s) +{ + Eprog prog; + int tempfd = -1, fd, cj; + zlong oldlineno; + int oldshst, osubsh, oloops; + FILE *obshin; + char *old_scriptname = scriptname, *us; + char *old_scriptfilename = scriptfilename; + unsigned char *ocs; + int ocsp; + int otrap_return = trap_return, otrap_state = trap_state; + struct funcstack fstack; + enum source_return ret = SOURCE_OK; + + if (!s || + (!(prog = try_source_file((us = unmeta(s)))) && + (tempfd = movefd(open(us, O_RDONLY | O_NOCTTY))) == -1)) { + return SOURCE_NOT_FOUND; + } + + /* save the current shell state */ + fd = SHIN; /* store the shell input fd */ + obshin = bshin; /* store file handle for buffered shell input */ + osubsh = subsh; /* store whether we are in a subshell */ + cj = thisjob; /* store our current job number */ + oldlineno = lineno; /* store our current lineno */ + oloops = loops; /* stored the # of nested loops we are in */ + oldshst = opts[SHINSTDIN]; /* store current value of this option */ + ocs = cmdstack; + ocsp = cmdsp; + cmdstack = (unsigned char *) zalloc(CMDSTACKSZ); + cmdsp = 0; + + if (!prog) { + SHIN = tempfd; + bshin = fdopen(SHIN, "r"); + } + subsh = 0; + lineno = 1; + loops = 0; + dosetopt(SHINSTDIN, 0, 1, opts); + scriptname = s; + scriptfilename = s; + + if (isset(SOURCETRACE)) { + printprompt4(); + fprintf(xtrerr ? xtrerr : stderr, "\n"); + } + + /* + * The special return behaviour of traps shouldn't + * trigger in files sourced from traps; the return + * is just a return from the file. + */ + trap_state = TRAP_STATE_INACTIVE; + + sourcelevel++; + + fstack.name = scriptfilename; + fstack.caller = funcstack ? funcstack->name : + dupstring(old_scriptfilename ? old_scriptfilename : "zsh"); + fstack.flineno = 0; + fstack.lineno = oldlineno; + fstack.filename = scriptfilename; + fstack.prev = funcstack; + fstack.tp = FS_SOURCE; + funcstack = &fstack; + + if (prog) { + pushheap(); + errflag &= ~ERRFLAG_ERROR; + execode(prog, 1, 0, "filecode"); + popheap(); + if (errflag) + ret = SOURCE_ERROR; + } else { + /* loop through the file to be sourced */ + switch (loop(0, 0)) + { + case LOOP_OK: + /* nothing to do but compilers like a complete enum */ + break; + + case LOOP_EMPTY: + /* Empty code resets status */ + lastval = 0; + break; + + case LOOP_ERROR: + ret = SOURCE_ERROR; + break; + } + } + funcstack = funcstack->prev; + sourcelevel--; + + trap_state = otrap_state; + trap_return = otrap_return; + + /* restore the current shell state */ + if (prog) + freeeprog(prog); + else { + fclose(bshin); + fdtable[SHIN] = FDT_UNUSED; + SHIN = fd; /* the shell input fd */ + bshin = obshin; /* file handle for buffered shell input */ + } + subsh = osubsh; /* whether we are in a subshell */ + thisjob = cj; /* current job number */ + lineno = oldlineno; /* our current lineno */ + loops = oloops; /* the # of nested loops we are in */ + dosetopt(SHINSTDIN, oldshst, 1, opts); /* SHINSTDIN option */ + errflag &= ~ERRFLAG_ERROR; + if (!exit_pending) + retflag = 0; + scriptname = old_scriptname; + scriptfilename = old_scriptfilename; + zfree(cmdstack, CMDSTACKSZ); + cmdstack = ocs; + cmdsp = ocsp; + + return ret; +} + +/* Try to source a file in the home directory */ + +/**/ +void +sourcehome(char *s) +{ + char *h; + + queue_signals(); + if (EMULATION(EMULATE_SH|EMULATE_KSH) || !(h = getsparam_u("ZDOTDIR"))) { + h = home; + if (!h) { + unqueue_signals(); + return; + } + } + + { + /* Let source() complain if path is too long */ + VARARR(char, buf, strlen(h) + strlen(s) + 2); + sprintf(buf, "%s/%s", h, s); + unqueue_signals(); + source(buf); + } +} + +/**/ +void +init_bltinmods(void) +{ + +#include "bltinmods.list" + + (void)load_module("zsh/main", NULL, 0); +} + +/**/ +mod_export void +noop_function(void) +{ + /* do nothing */ +} + +/**/ +mod_export void +noop_function_int(UNUSED(int nothing)) +{ + /* do nothing */ +} + +/* + * ZLE entry point pointer. + * No other source file needs to know which modules are linked in. + */ +/**/ +mod_export ZleEntryPoint zle_entry_ptr; + +/* + * State of loading of zle. + * 0 = Not loaded, not attempted. + * 1 = Loaded successfully + * 2 = Failed to load. + */ +/**/ +mod_export int zle_load_state; + +/**/ +mod_export char * +zleentry(VA_ALIST1(int cmd)) +VA_DCL +{ + char *ret = NULL; + va_list ap; + VA_DEF_ARG(int cmd); + + VA_START(ap, cmd); + VA_GET_ARG(ap, cmd, int); + +#if defined(LINKED_XMOD_zshQszle) || defined(UNLINKED_XMOD_zshQszle) + /* autoload */ + switch (zle_load_state) { + case 0: + /* + * Some commands don't require us to load ZLE. + * These also have no fallback. + */ + if (cmd != ZLE_CMD_TRASH && cmd != ZLE_CMD_RESET_PROMPT && + cmd != ZLE_CMD_REFRESH) + { + if (load_module("zsh/zle", NULL, 0) != 1) { + (void)load_module("zsh/compctl", NULL, 0); + ret = zle_entry_ptr(cmd, ap); + /* Don't execute fallback code */ + cmd = -1; + } else { + zle_load_state = 2; + /* Execute fallback code below */ + } + } + break; + + case 1: + ret = zle_entry_ptr(cmd, ap); + /* Don't execute fallback code */ + cmd = -1; + break; + + case 2: + /* Execute fallback code */ + break; + } +#endif + + switch (cmd) { + /* + * Only the read command really needs a fallback if zle + * is not available. ZLE_CMD_GET_LINE has traditionally + * had local code in bufferwords() to do this, but that' + * probably only because bufferwords() is part of completion + * and so everything to do with it is horribly complicated. + */ + case ZLE_CMD_READ: + { + char *pptbuf, **lp; + int pptlen; + + lp = va_arg(ap, char **); + + pptbuf = unmetafy(promptexpand(lp ? *lp : NULL, 0, NULL, NULL, + NULL), + &pptlen); + write_loop(2, pptbuf, pptlen); + free(pptbuf); + + ret = shingetline(); + break; + } + + case ZLE_CMD_GET_LINE: + { + int *ll, *cs; + + ll = va_arg(ap, int *); + cs = va_arg(ap, int *); + *ll = *cs = 0; + ret = ztrdup(""); + break; + } + } + + va_end(ap); + return ret; +} + +/* compctl entry point pointers. Similar to the ZLE ones. */ + +/**/ +mod_export CompctlReadFn compctlreadptr = fallback_compctlread; + +/**/ +mod_export int +fallback_compctlread(char *name, UNUSED(char **args), UNUSED(Options ops), UNUSED(char *reply)) +{ + zwarnnam(name, "no loaded module provides read for completion context"); + return 1; +} + +/* + * Used by zle to indicate it has already printed a "use 'exit' to exit" + * message. + */ +/**/ +mod_export int use_exit_printed; + +/* + * This is real main entry point. This has to be mod_export'ed + * so zsh.exe can found it on Cygwin + */ + +/**/ +mod_export int +zsh_main(UNUSED(int argc), char **argv) +{ + char **t, *runscript = NULL, *zsh_name; + char *cmd; /* argument to -c */ + int t0; +#ifdef USE_LOCALE + setlocale(LC_ALL, ""); +#endif + + init_jobs(argv, environ); + + /* + * Provisionally set up the type table to allow metafication. + * This will be done properly when we have decided if we are + * interactive + */ + typtab['\0'] |= IMETA; + typtab[STOUC(Meta) ] |= IMETA; + typtab[STOUC(Marker)] |= IMETA; + for (t0 = (int)STOUC(Pound); t0 <= (int)STOUC(Nularg); t0++) + typtab[t0] |= ITOK | IMETA; + + for (t = argv; *t; *t = metafy(*t, -1, META_ALLOC), t++); + + zsh_name = argv[0]; + do { + char *arg0 = zsh_name; + if (!(zsh_name = strrchr(arg0, '/'))) + zsh_name = arg0; + else + zsh_name++; + if (*zsh_name == '-') + zsh_name++; + if (strcmp(zsh_name, "su") == 0) { + char *sh = zgetenv("SHELL"); + if (sh && *sh && arg0 != sh) + zsh_name = sh; + else + break; + } else + break; + } while (zsh_name); + + fdtable_size = zopenmax(); + fdtable = zshcalloc(fdtable_size*sizeof(*fdtable)); + fdtable[0] = fdtable[1] = fdtable[2] = FDT_EXTERNAL; + + createoptiontable(); + /* sets emulation, LOGINSHELL, PRIVILEGED, ZLE, INTERACTIVE, + * SHINSTDIN and SINGLECOMMAND */ + parseargs(zsh_name, argv, &runscript, &cmd); + + SHTTY = -1; + init_io(cmd); + setupvals(cmd, runscript, zsh_name); + + init_signals(); + init_bltinmods(); + init_builtins(); + run_init_scripts(); + setupshin(runscript); + init_misc(cmd, zsh_name); + + for (;;) { + /* + * See if we can free up some of jobtab. + * We only do this at top level, because if we are + * executing stuff we may refer to them by job pointer. + */ + int errexit = 0; + maybeshrinkjobtab(); + + do { + /* Reset return from top level which gets us back here */ + retflag = 0; + loop(1,0); + if (errflag && !interact && !isset(CONTINUEONERROR)) { + errexit = 1; + break; + } + } while (tok != ENDINPUT && (tok != LEXERR || isset(SHINSTDIN))); + if (tok == LEXERR || errexit) { + /* Make sure a fatal error exits with non-zero status */ + if (!lastval) + lastval = 1; + stopmsg = 1; + zexit(lastval, 0); + } + if (!(isset(IGNOREEOF) && interact)) { +#if 0 + if (interact) + fputs(islogin ? "logout\n" : "exit\n", shout); +#endif + zexit(lastval, 0); + continue; + } + noexitct++; + if (noexitct >= 10) { + stopmsg = 1; + zexit(lastval, 0); + } + /* + * Don't print the message if it was already handled by + * zle, since that makes special arrangements to keep + * the display tidy. + */ + if (!use_exit_printed) + zerrnam("zsh", (!islogin) ? "use 'exit' to exit." + : "use 'logout' to logout."); + } +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/input.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/input.c new file mode 100644 index 00000000..9787dedf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/input.c @@ -0,0 +1,701 @@ +/* + * input.c - read and store lines of input + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + + +/* + * This file deals with input buffering, supplying characters to the + * history expansion code a character at a time. Input is stored on a + * stack, which allows insertion of strings into the input, possibly with + * flags marking the end of alias expansion, with minimal copying of + * strings. The same stack is used to record the fact that the input + * is a history or alias expansion and to store the alias while it is in use. + * + * Input is taken either from zle, if appropriate, or read directly from + * the input file, or may be supplied by some other part of the shell (such + * as `eval' or $(...) substitution). In the last case, it should be + * supplied by pushing a new level onto the stack, via inpush(input_string, + * flag, alias); if the current input really needs to be altered, use + * inputsetline(input_string, flag). `Flag' can include or's of INP_FREE + * (if the input string is to be freed when used), INP_CONT (if the input + * is to continue onto what's already in the input queue), INP_ALIAS + * (push supplied alias onto stack) or INP_HIST (ditto, but used to + * mark history expansion). `alias' is ignored unless INP_ALIAS or + * INP_HIST is supplied. INP_ALIAS is always set if INP_HIST is. + * + * Note that the input string is itself used as the input buffer: it is not + * copied, nor is it every written back to, so using a constant string + * should work. Consequently, when passing areas of memory from the heap + * it is necessary that that heap last as long as the operation of reading + * the string. After the string is read, the stack should be popped with + * inpop(), which effectively flushes any unread input as well as restoring + * the previous input state. + * + * The internal flags INP_ALCONT and INP_HISTCONT show that the stack + * element was pushed by an alias or history expansion; they should not + * be needed elsewhere. + * + * The global variable inalmore is set to indicate aliases should + * continue to be expanded because the last alias expansion ended + * in a space. It is only reset after a complete word was read + * without expanding a new alias, in exalias(). + * + * PWS 1996/12/10 + */ + +#ifdef HAVE_STDIO_H +#include +#endif + +#include "zsh.mdh" +#include "input.pro" + +/* the shell input fd */ + +/**/ +int SHIN; + +/* buffered shell input for non-interactive shells */ + +/**/ +FILE *bshin; + +/* != 0 means we are reading input from a string */ + +/**/ +int strin; + +/* total # of characters waiting to be read. */ + +/**/ +mod_export int inbufct; + +/* the flags controlling the input routines in input.c: see INP_* in zsh.h */ + +/**/ +int inbufflags; + +static char *inbuf; /* Current input buffer */ +static char *inbufptr; /* Pointer into input buffer */ +static char *inbufpush; /* Character at which to re-push alias */ +static int inbufleft; /* Characters left in current input + stack element */ + + + /* Input must be stacked since the input queue is used by + * various different parts of the shell. + */ + +struct instacks { + char *buf, *bufptr; + Alias alias; + int bufleft, bufct, flags; +}; +static struct instacks *instack, *instacktop; +/* + * Input stack size. We need to push the stack for aliases, history + * expansion, and reading from internal strings: only if these operations + * are nested do we need more than one extra level. Thus we shouldn't need + * too much space as a rule. Initially, INSTACK_INITIAL is allocated; if + * more is required, an extra INSTACK_EXPAND is added each time. + */ +#define INSTACK_INITIAL 4 +#define INSTACK_EXPAND 4 + +static int instacksz = INSTACK_INITIAL; + +/* Read a line from bshin. Convert tokens and * + * null characters to Meta c^32 character pairs. */ + +/**/ +mod_export char * +shingetline(void) +{ + char *line = NULL; + int ll = 0; + int c; + char buf[BUFSIZ]; + char *p; + int q = queue_signal_level(); + + p = buf; + winch_unblock(); + dont_queue_signals(); + for (;;) { + /* Can't fgets() here because we need to accept '\0' bytes */ + do { + errno = 0; + c = fgetc(bshin); + } while (c < 0 && errno == EINTR); + if (c < 0 || c == '\n') { + winch_block(); + restore_queue_signals(q); + if (c == '\n') + *p++ = '\n'; + if (p > buf) { + *p++ = '\0'; + line = zrealloc(line, ll + (p - buf)); + memcpy(line + ll, buf, p - buf); + } + return line; + } + if (imeta(c)) { + *p++ = Meta; + *p++ = c ^ 32; + } else + *p++ = c; + if (p >= buf + BUFSIZ - 1) { + winch_block(); + queue_signals(); + line = zrealloc(line, ll + (p - buf) + 1); + memcpy(line + ll, buf, p - buf); + ll += p - buf; + line[ll] = '\0'; + p = buf; + winch_unblock(); + dont_queue_signals(); + } + } +} + +/* Get the next character from the input. + * Will call inputline() to get a new line where necessary. + */ + +/**/ +int +ingetc(void) +{ + int lastc = ' '; + + if (lexstop) + return ' '; + for (;;) { + if (inbufleft) { + inbufleft--; + inbufct--; + if (itok(lastc = STOUC(*inbufptr++))) + continue; + if (((inbufflags & INP_LINENO) || !strin) && lastc == '\n') + lineno++; + break; + } + + /* + * See if we have reached the end of input + * (due to an error, or to reading from a single string). + * Check the remaining characters left, since if there aren't + * any we don't want to pop the stack---it'll mark any aliases + * as not in use before we've finished processing. + */ + if (!inbufct && (strin || errflag)) { + lexstop = 1; + break; + } + /* If the next element down the input stack is a continuation of + * this, use it. + */ + if (inbufflags & INP_CONT) { + inpoptop(); + continue; + } + /* As a last resort, get some more input */ + if (inputline()) + break; + } + if (!lexstop) + zshlex_raw_add(lastc); + return lastc; +} + +/* Read a line from the current command stream and store it as input */ + +/**/ +static int +inputline(void) +{ + char *ingetcline, **ingetcpmptl = NULL, **ingetcpmptr = NULL; + int context = ZLCON_LINE_START; + + /* If reading code interactively, work out the prompts. */ + if (interact && isset(SHINSTDIN)) { + if (!isfirstln) { + ingetcpmptl = &prompt2; + if (rprompt2) + ingetcpmptr = &rprompt2; + context = ZLCON_LINE_CONT; + } + else { + ingetcpmptl = &prompt; + if (rprompt) + ingetcpmptr = &rprompt; + } + } + if (!(interact && isset(SHINSTDIN) && SHTTY != -1 && isset(USEZLE))) { + /* + * If not using zle, read the line straight from the input file. + * Possibly we don't get the whole line at once: in that case, + * we get another chunk with the next call to inputline(). + */ + + if (interact && isset(SHINSTDIN)) { + /* + * We may still be interactive (e.g. running under emacs), + * so output a prompt if necessary. We don't know enough + * about the input device to be able to handle an rprompt, + * though. + */ + char *pptbuf; + int pptlen; + pptbuf = unmetafy(promptexpand(ingetcpmptl ? *ingetcpmptl : NULL, + 0, NULL, NULL, NULL), &pptlen); + write_loop(2, pptbuf, pptlen); + free(pptbuf); + } + ingetcline = shingetline(); + } else { + /* + * Since we may have to read multiple lines before getting + * a complete piece of input, we tell zle not to restore the + * original tty settings after reading each chunk. Instead, + * this is done when the history mechanism for the current input + * terminates, which is not until we have the whole input. + * This is supposed to minimise problems on systems that clobber + * typeahead when the terminal settings are altered. + * pws 1998/03/12 + */ + int flags = ZLRF_HISTORY|ZLRF_NOSETTY; + if (isset(IGNOREEOF)) + flags |= ZLRF_IGNOREEOF; + ingetcline = zleentry(ZLE_CMD_READ, ingetcpmptl, ingetcpmptr, + flags, context); + histdone |= HISTFLAG_SETTY; + } + if (!ingetcline) { + return lexstop = 1; + } + if (errflag) { + free(ingetcline); + errflag |= ERRFLAG_ERROR; + return lexstop = 1; + } + if (isset(VERBOSE)) { + /* Output the whole line read so far. */ + zputs(ingetcline, stderr); + fflush(stderr); + } + if (keyboardhackchar && *ingetcline && + ingetcline[strlen(ingetcline) - 1] == '\n' && + interact && isset(SHINSTDIN) && + SHTTY != -1 && ingetcline[1]) + { + char *stripptr = ingetcline + strlen(ingetcline) - 2; + if (*stripptr == keyboardhackchar) { + /* Junk an unwanted character at the end of the line. + (key too close to return key) */ + int ct = 1; /* force odd */ + char *ptr; + + if (keyboardhackchar == '\'' || keyboardhackchar == '"' || + keyboardhackchar == '`') { + /* + * for the chars above, also require an odd count before + * junking + */ + for (ct = 0, ptr = ingetcline; *ptr; ptr++) + if (*ptr == keyboardhackchar) + ct++; + } + if (ct & 1) { + stripptr[0] = '\n'; + stripptr[1] = '\0'; + } + } + } + isfirstch = 1; + if ((inbufflags & INP_APPEND) && inbuf) { + /* + * We need new input but need to be able to back up + * over the old input, so append this line. + * Pushing the line onto the stack doesn't have the right + * effect. + * + * This is quite a simple and inefficient fix, but currently + * we only need it when backing up over a multi-line $((... + * that turned out to be a command substitution rather than + * a math substitution, which is a very special case. + * So it's not worth rewriting. + */ + char *oinbuf = inbuf; + int newlen = strlen(ingetcline); + int oldlen = (int)(inbufptr - inbuf) + inbufleft; + if (inbufflags & INP_FREE) { + inbuf = realloc(inbuf, oldlen + newlen + 1); + } else { + inbuf = zalloc(oldlen + newlen + 1); + memcpy(inbuf, oinbuf, oldlen); + } + inbufptr += inbuf - oinbuf; + strcpy(inbuf + oldlen, ingetcline); + free(ingetcline); + inbufleft += newlen; + inbufct += newlen; + inbufflags |= INP_FREE; + } else { + /* Put this into the input channel. */ + inputsetline(ingetcline, INP_FREE); + } + + return 0; +} + +/* + * Put a string in the input queue: + * inbuf is only freeable if the flags include INP_FREE. + */ + +/**/ +static void +inputsetline(char *str, int flags) +{ + queue_signals(); + + if ((inbufflags & INP_FREE) && inbuf) { + free(inbuf); + } + inbuf = inbufptr = str; + inbufleft = strlen(inbuf); + + /* + * inbufct must reflect the total number of characters left, + * as it used by other parts of the shell, so we need to take account + * of whether the input stack continues, and whether there + * is an extra space to add on at the end. + */ + if (flags & INP_CONT) + inbufct += inbufleft; + else + inbufct = inbufleft; + inbufflags = flags; + + unqueue_signals(); +} + +/* + * Backup one character of the input. + * The last character can always be backed up, provided we didn't just + * expand an alias or a history reference. + * In fact, the character is ignored and the previous character is used. + * (If that's wrong, the bug is in the calling code. Use the #ifdef DEBUG + * code to check.) + */ + +/**/ +void +inungetc(int c) +{ + if (!lexstop) { + if (inbufptr != inbuf) { +#ifdef DEBUG + /* Just for debugging: enable only if foul play suspected. */ + if (inbufptr[-1] != (char) c) + fprintf(stderr, "Warning: backing up wrong character.\n"); +#endif + /* Just decrement the pointer: if it's not the same + * character being pushed back, we're in trouble anyway. + */ + inbufptr--; + inbufct++; + inbufleft++; + if (((inbufflags & INP_LINENO) || !strin) && c == '\n') + lineno--; + } + else if (!(inbufflags & INP_CONT)) { +#ifdef DEBUG + /* Just for debugging */ + fprintf(stderr, "Attempt to inungetc() at start of input.\n"); +#endif + zerr("Garbled input at %c (binary file as commands?)", c); + return; + } + else { + /* + * The character is being backed up from a previous input stack + * layer. However, there was an expansion in the middle, so we + * can't back up where we want to. Instead, we just push it + * onto the input stack as an extra character. + */ + char *cback = (char *)zshcalloc(2); + cback[0] = (char) c; + inpush(cback, INP_FREE|INP_CONT, NULL); + } + /* If we are back at the start of a segment, + * we may need to restore an alias popped from the stack. + * Note this may be a dummy (history expansion) entry. + */ + if (inbufptr == inbufpush && + (inbufflags & (INP_ALCONT|INP_HISTCONT))) { + /* + * Go back up the stack over all entries which were alias + * expansions and were pushed with nothing remaining to read. + */ + do { + if (instacktop->alias) + instacktop->alias->inuse = 1; + instacktop++; + } while ((instacktop->flags & (INP_ALCONT|INP_HISTCONT)) + && !instacktop->bufleft); + if (inbufflags & INP_HISTCONT) + inbufflags = INP_CONT|INP_ALIAS|INP_HIST; + else + inbufflags = INP_CONT|INP_ALIAS; + inbufleft = 0; + inbuf = inbufptr = ""; + } + zshlex_raw_back(); + } +} + +/* stuff a whole file into the input queue and print it */ + +/**/ +int +stuff(char *fn) +{ + FILE *in; + char *buf; + off_t len; + + if (!(in = fopen(unmeta(fn), "r"))) { + zerr("can't open %s", fn); + return 1; + } + fseek(in, 0, 2); + len = ftell(in); + fseek(in, 0, 0); + buf = (char *)zalloc(len + 1); + if (!(fread(buf, len, 1, in))) { + zerr("read error on %s", fn); + fclose(in); + zfree(buf, len + 1); + return 1; + } + fclose(in); + buf[len] = '\0'; + fwrite(buf, len, 1, stderr); + fflush(stderr); + inputsetline(metafy(buf, len, META_REALLOC), INP_FREE); + return 0; +} + +/* flush input queue */ + +/**/ +void +inerrflush(void) +{ + while (!lexstop && inbufct) + ingetc(); +} + +/* Set some new input onto a new element of the input stack */ + +/**/ +mod_export void +inpush(char *str, int flags, Alias inalias) +{ + if (!instack) { + /* Initial stack allocation */ + instack = (struct instacks *)zalloc(instacksz*sizeof(struct instacks)); + instacktop = instack; + } + + instacktop->buf = inbuf; + instacktop->bufptr = inbufptr; + instacktop->bufleft = inbufleft; + instacktop->bufct = inbufct; + inbufflags &= ~(INP_ALCONT|INP_HISTCONT); + if (flags & (INP_ALIAS|INP_HIST)) { + /* + * Text is expansion for history or alias, so continue + * back to old level when done. Also mark stack top + * as alias continuation so as to back up if necessary, + * and mark alias as in use. + */ + flags |= INP_CONT|INP_ALIAS; + if (flags & INP_HIST) + instacktop->flags = inbufflags | INP_HISTCONT; + else + instacktop->flags = inbufflags | INP_ALCONT; + if ((instacktop->alias = inalias)) + inalias->inuse = 1; + } else { + /* If we are continuing an alias expansion, record the alias + * expansion in new set of flags (do we need this?) + */ + if (((instacktop->flags = inbufflags) & INP_ALIAS) && + (flags & INP_CONT)) + flags |= INP_ALIAS; + } + + instacktop++; + if (instacktop == instack + instacksz) { + /* Expand the stack */ + instack = (struct instacks *) + realloc(instack, + (instacksz + INSTACK_EXPAND)*sizeof(struct instacks)); + instacktop = instack + instacksz; + instacksz += INSTACK_EXPAND; + } + /* + * We maintain the entry above the highest one with real + * text as a flag to inungetc() that it can stop re-pushing the stack. + */ + instacktop->flags = 0; + + inbufpush = inbuf = NULL; + + inputsetline(str, flags); +} + +/* Remove the top element of the stack */ + +/**/ +static void +inpoptop(void) +{ + if (!lexstop) { + inbufflags &= ~(INP_ALCONT|INP_HISTCONT); + while (inbufptr > inbuf) { + inbufptr--; + inbufct++; + inbufleft++; + /* + * As elsewhere in input and history mechanisms: + * unwinding aliases and unwinding history have different + * implications as aliases are after the lexer while + * history is before, but they're both pushed onto + * the input stack. + */ + if ((inbufflags & (INP_ALIAS|INP_HIST|INP_RAW_KEEP)) == INP_ALIAS) + zshlex_raw_back(); + } + } + + if (inbuf && (inbufflags & INP_FREE)) + free(inbuf); + + instacktop--; + + inbuf = instacktop->buf; + inbufptr = inbufpush = instacktop->bufptr; + inbufleft = instacktop->bufleft; + inbufct = instacktop->bufct; + inbufflags = instacktop->flags; + + if (!(inbufflags & (INP_ALCONT|INP_HISTCONT))) + return; + + if (instacktop->alias) { + char *t = instacktop->alias->text; + /* a real alias: mark it as unused. */ + instacktop->alias->inuse = 0; + if (*t && t[strlen(t) - 1] == ' ') { + inalmore = 1; + histbackword(); + } + } +} + +/* Remove the top element of the stack and all its continuations. */ + +/**/ +mod_export void +inpop(void) +{ + int remcont; + + do { + remcont = inbufflags & INP_CONT; + + inpoptop(); + } while (remcont); +} + +/* + * Expunge any aliases from the input stack; they shouldn't appear + * in the history and need to be flushed explicitly when we encounter + * an error. + */ + +/**/ +void +inpopalias(void) +{ + while (inbufflags & INP_ALIAS) + inpoptop(); +} + + +/* + * Get pointer to remaining string to read. + */ + +/**/ +char * +ingetptr(void) +{ + return inbufptr; +} + +/* + * Check if the current input line, including continuations, is + * expanding an alias. This does not detect alias expansions that + * have been fully processed and popped from the input stack. + * If there is an alias, the most recently expanded is returned, + * else NULL. + */ + +/**/ +char *input_hasalias(void) +{ + int flags = inbufflags; + struct instacks *instackptr = instacktop; + + for (;;) + { + if (!(flags & INP_CONT)) + break; + instackptr--; + if (instackptr->alias) + return instackptr->alias->node.nam; + flags = instackptr->flags; + } + + return NULL; +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/jobs.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/jobs.c new file mode 100644 index 00000000..38b3d896 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/jobs.c @@ -0,0 +1,2894 @@ +/* + * jobs.c - job control + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "jobs.pro" + +/* the process group of the shell at startup (equal to mypgprp, except + when we started without being process group leader */ + +/**/ +mod_export pid_t origpgrp; + +/* the process group of the shell */ + +/**/ +mod_export pid_t mypgrp; + +/* the job we are working on */ + +/**/ +mod_export int thisjob; + +/* the current job (+) */ + +/**/ +mod_export int curjob; + +/* the previous job (-) */ + +/**/ +mod_export int prevjob; + +/* the job table */ + +/**/ +mod_export struct job *jobtab; + +/* Size of the job table. */ + +/**/ +mod_export int jobtabsize; + +/* The highest numbered job in the jobtable */ + +/**/ +mod_export int maxjob; + +/* If we have entered a subshell, the original shell's job table. */ +static struct job *oldjobtab; + +/* The size of that. */ +static int oldmaxjob; + +/* shell timings */ + +/**/ +#ifdef HAVE_GETRUSAGE +/**/ +static struct rusage child_usage; +/**/ +#else +/**/ +static struct tms shtms; +/**/ +#endif + +/* 1 if ttyctl -f has been executed */ + +/**/ +mod_export int ttyfrozen; + +/* Previous values of errflag and breaks if the signal handler had to + * change them. And a flag saying if it did that. */ + +/**/ +int prev_errflag, prev_breaks, errbrk_saved; + +/**/ +int numpipestats, pipestats[MAX_PIPESTATS]; + +/* Diff two timevals for elapsed-time computations */ + +/**/ +static struct timeval * +dtime(struct timeval *dt, struct timeval *t1, struct timeval *t2) +{ + dt->tv_sec = t2->tv_sec - t1->tv_sec; + dt->tv_usec = t2->tv_usec - t1->tv_usec; + if (dt->tv_usec < 0) { + dt->tv_usec += 1000000.0; + dt->tv_sec -= 1.0; + } + return dt; +} + +/* change job table entry from stopped to running */ + +/**/ +void +makerunning(Job jn) +{ + Process pn; + + jn->stat &= ~STAT_STOPPED; + for (pn = jn->procs; pn; pn = pn->next) { +#if 0 + if (WIFSTOPPED(pn->status) && + (!(jn->stat & STAT_SUPERJOB) || pn->next)) + pn->status = SP_RUNNING; +#endif + if (WIFSTOPPED(pn->status)) + pn->status = SP_RUNNING; + } + + if (jn->stat & STAT_SUPERJOB) + makerunning(jobtab + jn->other); +} + +/* Find process and job associated with pid. * + * Return 1 if search was successful, else return 0. */ + +/**/ +int +findproc(pid_t pid, Job *jptr, Process *pptr, int aux) +{ + Process pn; + int i; + + *jptr = NULL; + *pptr = NULL; + for (i = 1; i <= maxjob; i++) + { + /* + * We are only interested in jobs with processes still + * marked as live. Careful in case there's an identical + * process number in a job we haven't quite got around + * to deleting. + */ + if (jobtab[i].stat & STAT_DONE) + continue; + + for (pn = aux ? jobtab[i].auxprocs : jobtab[i].procs; + pn; pn = pn->next) + { + /* + * Make sure we match a process that's still running. + * + * When a job contains two pids, one terminated pid and one + * running pid, then the condition (jobtab[i].stat & + * STAT_DONE) will not stop these pids from being candidates + * for the findproc result (which is supposed to be a + * RUNNING pid), and if the terminated pid is an identical + * process number for the pid identifying the running + * process we are trying to find (after pid number + * wrapping), then we need to avoid returning the terminated + * pid, otherwise the shell would block and wait forever for + * the termination of the process which pid we were supposed + * to return in a different job. + */ + if (pn->pid == pid) { + *pptr = pn; + *jptr = jobtab + i; + if (pn->status == SP_RUNNING) + return 1; + } + } + } + + return (*pptr && *jptr); +} + +/* Does the given job number have any processes? */ + +/**/ +int +hasprocs(int job) +{ + Job jn; + + if (job < 0) { + DPUTS(1, "job number invalid in hasprocs"); + return 0; + } + jn = jobtab + job; + + return jn->procs || jn->auxprocs; +} + +/* Find the super-job of a sub-job. */ + +/**/ +static int +super_job(int sub) +{ + int i; + + for (i = 1; i <= maxjob; i++) + if ((jobtab[i].stat & STAT_SUPERJOB) && + jobtab[i].other == sub && + jobtab[i].gleader) + return i; + return 0; +} + +/**/ +static int +handle_sub(int job, int fg) +{ + /* job: superjob; sj: subjob. */ + Job jn = jobtab + job, sj = jobtab + jn->other; + + if ((sj->stat & STAT_DONE) || (!sj->procs && !sj->auxprocs)) { + struct process *p; + + for (p = sj->procs; p; p = p->next) { + if (WIFSIGNALED(p->status)) { + if (jn->gleader != mypgrp && jn->procs->next) + killpg(jn->gleader, WTERMSIG(p->status)); + else + kill(jn->procs->pid, WTERMSIG(p->status)); + kill(sj->other, SIGCONT); + kill(sj->other, WTERMSIG(p->status)); + break; + } + } + if (!p) { + int cp; + + jn->stat &= ~STAT_SUPERJOB; + jn->stat |= STAT_WASSUPER; + + if ((cp = ((WIFEXITED(jn->procs->status) || + WIFSIGNALED(jn->procs->status)) && + killpg(jn->gleader, 0) == -1))) { + Process p; + for (p = jn->procs; p->next; p = p->next); + jn->gleader = p->pid; + } + /* This deleted the job too early if the parent + shell waited for a command in a list that will + be executed by the sub-shell (e.g.: if we have + `ls|if true;then sleep 20;cat;fi' and ^Z the + sleep, the rest will be executed by a sub-shell, + but the parent shell gets notified for the + sleep. + deletejob(sj, 0); */ + /* If this super-job contains only the sub-shell, + we have to attach the tty to its process group + now. */ + if ((fg || thisjob == job) && + (!jn->procs->next || cp || jn->procs->pid != jn->gleader)) + attachtty(jn->gleader); + kill(sj->other, SIGCONT); + if (jn->stat & STAT_DISOWN) + { + deletejob(jn, 1); + } + } + curjob = jn - jobtab; + } else if (sj->stat & STAT_STOPPED) { + struct process *p; + + jn->stat |= STAT_STOPPED; + for (p = jn->procs; p; p = p->next) + if (p->status == SP_RUNNING || + (!WIFEXITED(p->status) && !WIFSIGNALED(p->status))) + p->status = sj->procs->status; + curjob = jn - jobtab; + printjob(jn, !!isset(LONGLISTJOBS), 1); + return 1; + } + return 0; +} + + +/* Get the latest usage information */ + +/**/ +void +get_usage(void) +{ +#ifdef HAVE_GETRUSAGE + getrusage(RUSAGE_CHILDREN, &child_usage); +#else + times(&shtms); +#endif +} + + +#if !defined HAVE_WAIT3 || !defined HAVE_GETRUSAGE +/* Update status of process that we have just WAIT'ed for */ + +/**/ +void +update_process(Process pn, int status) +{ + struct timezone dummy_tz; +#ifdef HAVE_GETRUSAGE + struct timeval childs = child_usage.ru_stime; + struct timeval childu = child_usage.ru_utime; +#else + long childs = shtms.tms_cstime; + long childu = shtms.tms_cutime; +#endif + + /* get time-accounting info */ + get_usage(); + gettimeofday(&pn->endtime, &dummy_tz); /* record time process exited */ + + pn->status = status; /* save the status returned by WAIT */ +#ifdef HAVE_GETRUSAGE + dtime(&pn->ti.ru_stime, &childs, &child_usage.ru_stime); + dtime(&pn->ti.ru_utime, &childu, &child_usage.ru_utime); +#else + pn->ti.st = shtms.tms_cstime - childs; /* compute process system space time */ + pn->ti.ut = shtms.tms_cutime - childu; /* compute process user space time */ +#endif +} +#endif + +/* + * Called when the current shell is behaving as if it received + * a interactively generated signal (sig). + * + * As we got the signal or are pretending we did, we need to pretend + * anything attached to a CURSH process got it, too. + */ +/**/ +void +check_cursh_sig(int sig) +{ + int i, j; + + if (!errflag) + return; + for (i = 1; i <= maxjob; i++) { + if ((jobtab[i].stat & (STAT_CURSH|STAT_DONE)) == + STAT_CURSH) { + for (j = 0; j < 2; j++) { + Process pn = j ? jobtab[i].auxprocs : jobtab[i].procs; + for (; pn; pn = pn->next) { + if (pn->status == SP_RUNNING) { + kill(pn->pid, sig); + } + } + } + } + } +} + +/**/ +void +storepipestats(Job jn, int inforeground, int fixlastval) +{ + int i, pipefail = 0, jpipestats[MAX_PIPESTATS]; + Process p; + + for (p = jn->procs, i = 0; p && i < MAX_PIPESTATS; p = p->next, i++) { + jpipestats[i] = (WIFSIGNALED(p->status) ? + 0200 | WTERMSIG(p->status) : + (WIFSTOPPED(p->status) ? + 0200 | WEXITSTATUS(p->status) : + WEXITSTATUS(p->status))); + if (jpipestats[i]) + pipefail = jpipestats[i]; + } + if (inforeground) { + memcpy(pipestats, jpipestats, sizeof(int)*i); + if ((jn->stat & STAT_CURSH) && i < MAX_PIPESTATS) + pipestats[i++] = lastval; + numpipestats = i; + } + + if (fixlastval) { + if (jn->stat & STAT_CURSH) { + if (!lastval && isset(PIPEFAIL)) + lastval = pipefail; + } else if (isset(PIPEFAIL)) + lastval = pipefail; + } +} + +/* Update status of job, possibly printing it */ + +/**/ +void +update_job(Job jn) +{ + Process pn; + int job; + int val = 0, status = 0; + int somestopped = 0, inforeground = 0; + + for (pn = jn->auxprocs; pn; pn = pn->next) { +#ifdef WIFCONTINUED + if (WIFCONTINUED(pn->status)) + pn->status = SP_RUNNING; +#endif + if (pn->status == SP_RUNNING) + return; + } + + for (pn = jn->procs; pn; pn = pn->next) { +#ifdef WIFCONTINUED + if (WIFCONTINUED(pn->status)) { + jn->stat &= ~STAT_STOPPED; + pn->status = SP_RUNNING; + } +#endif + if (pn->status == SP_RUNNING) /* some processes in this job are running */ + return; /* so no need to update job table entry */ + if (WIFSTOPPED(pn->status)) /* some processes are stopped */ + somestopped = 1; /* so job is not done, but entry needs updating */ + if (!pn->next) /* last job in pipeline determines exit status */ + val = (WIFSIGNALED(pn->status) ? + 0200 | WTERMSIG(pn->status) : + (WIFSTOPPED(pn->status) ? + 0200 | WEXITSTATUS(pn->status) : + WEXITSTATUS(pn->status))); + if (pn->pid == jn->gleader) /* if this process is process group leader */ + status = pn->status; + } + + job = jn - jobtab; /* compute job number */ + + if (somestopped) { + if (jn->stty_in_env && !jn->ty) { + jn->ty = (struct ttyinfo *) zalloc(sizeof(struct ttyinfo)); + gettyinfo(jn->ty); + } + if (jn->stat & STAT_STOPPED) { + if (jn->stat & STAT_SUBJOB) { + /* If we have `cat foo|while read a; grep $a bar;done' + * and have hit ^Z, the sub-job is stopped, but the + * super-job may still be running, waiting to be stopped + * or to exit. So we have to send it a SIGTSTP. */ + int i; + + if ((i = super_job(job))) + killpg(jobtab[i].gleader, SIGTSTP); + } + return; + } + } + { /* job is done or stopped, remember return value */ + lastval2 = val; + /* If last process was run in the current shell, keep old status + * and let it handle its own traps, but always allow the test + * for the pgrp. + */ + if (jn->stat & STAT_CURSH) + inforeground = 1; + else if (job == thisjob) { + lastval = val; + inforeground = 2; + } + } + + if (shout && shout != stderr && !ttyfrozen && !jn->stty_in_env && + !zleactive && job == thisjob && !somestopped && + !(jn->stat & STAT_NOSTTY)) + gettyinfo(&shttyinfo); + + if (isset(MONITOR)) { + pid_t pgrp = gettygrp(); /* get process group of tty */ + + /* is this job in the foreground of an interactive shell? */ + if (mypgrp != pgrp && inforeground && + (jn->gleader == pgrp || (pgrp > 1 && kill(-pgrp, 0) == -1))) { + if (list_pipe) { + if (somestopped || (pgrp > 1 && kill(-pgrp, 0) == -1)) { + attachtty(mypgrp); + /* check window size and adjust if necessary */ + adjustwinsize(0); + } else { + /* + * Oh, dear, we're right in the middle of some confusion + * of shell jobs on the righthand side of a pipeline, so + * it's death to call attachtty() just yet. Mark the + * fact in the job, so that the attachtty() will be called + * when the job is finally deleted. + */ + jn->stat |= STAT_ATTACH; + } + /* If we have `foo|while true; (( x++ )); done', and hit + * ^C, we have to stop the loop, too. */ + if ((val & 0200) && inforeground == 1 && + ((val & ~0200) == SIGINT || (val & ~0200) == SIGQUIT)) { + if (!errbrk_saved) { + errbrk_saved = 1; + prev_breaks = breaks; + prev_errflag = errflag; + } + breaks = loops; + errflag |= ERRFLAG_INT; + inerrflush(); + } + } else { + attachtty(mypgrp); + /* check window size and adjust if necessary */ + adjustwinsize(0); + } + } + } else if (list_pipe && (val & 0200) && inforeground == 1 && + ((val & ~0200) == SIGINT || (val & ~0200) == SIGQUIT)) { + if (!errbrk_saved) { + errbrk_saved = 1; + prev_breaks = breaks; + prev_errflag = errflag; + } + breaks = loops; + errflag |= ERRFLAG_INT; + inerrflush(); + } + if (somestopped && jn->stat & STAT_SUPERJOB) + return; + jn->stat |= (somestopped) ? STAT_CHANGED | STAT_STOPPED : + STAT_CHANGED | STAT_DONE; + if (jn->stat & (STAT_DONE|STAT_STOPPED)) { + /* This may be redundant with printjob() but note that inforeground + * is true here for STAT_CURSH jobs even when job != thisjob, most + * likely because thisjob = -1 from exec.c:execsimple() trickery. + * However, if we reset lastval here we break it for printjob(). + */ + storepipestats(jn, inforeground, 0); + } + if (!inforeground && + (jn->stat & (STAT_SUBJOB | STAT_DONE)) == (STAT_SUBJOB | STAT_DONE)) { + int su; + + if ((su = super_job(jn - jobtab))) + handle_sub(su, 0); + } + if ((jn->stat & (STAT_DONE | STAT_STOPPED)) == STAT_STOPPED) { + prevjob = curjob; + curjob = job; + } + if ((isset(NOTIFY) || job == thisjob) && (jn->stat & STAT_LOCKED)) { + if (printjob(jn, !!isset(LONGLISTJOBS), 0) && + zleactive) + zleentry(ZLE_CMD_REFRESH); + } + if (sigtrapped[SIGCHLD] && job != thisjob) + dotrap(SIGCHLD); + + /* When MONITOR is set, the foreground process runs in a different * + * process group from the shell, so the shell will not receive * + * terminal signals, therefore we pretend that the shell got * + * the signal too. */ + if (inforeground == 2 && isset(MONITOR) && WIFSIGNALED(status)) { + int sig = WTERMSIG(status); + + if (sig == SIGINT || sig == SIGQUIT) { + if (sigtrapped[sig]) { + dotrap(sig); + /* We keep the errflag as set or not by dotrap. + * This is to fulfil the promise to carry on + * with the jobs if trap returns zero. + * Setting breaks = loops ensures a consistent return + * status if inside a loop. Maybe the code in loops + * should be changed. + */ + if (errflag) + breaks = loops; + } else { + breaks = loops; + errflag |= ERRFLAG_INT; + } + check_cursh_sig(sig); + } + } +} + +/* set the previous job to something reasonable */ + +/**/ +static void +setprevjob(void) +{ + int i; + + for (i = maxjob; i; i--) + if ((jobtab[i].stat & STAT_INUSE) && (jobtab[i].stat & STAT_STOPPED) && + !(jobtab[i].stat & STAT_SUBJOB) && i != curjob && i != thisjob) { + prevjob = i; + return; + } + + for (i = maxjob; i; i--) + if ((jobtab[i].stat & STAT_INUSE) && !(jobtab[i].stat & STAT_SUBJOB) && + i != curjob && i != thisjob) { + prevjob = i; + return; + } + + prevjob = -1; +} + +/**/ +long +get_clktck(void) +{ + static long clktck; + +#ifdef _SC_CLK_TCK + if (!clktck) + /* fetch clock ticks per second from * + * sysconf only the first time */ + clktck = sysconf(_SC_CLK_TCK); +#else +# ifdef __NeXT__ + /* NeXTStep 3.3 defines CLK_TCK wrongly */ + clktck = 60; +# else +# ifdef CLK_TCK + clktck = CLK_TCK; +# else +# ifdef HZ + clktck = HZ; +# else + clktck = 60; +# endif +# endif +# endif +#endif + + return clktck; +} + +/**/ +static void +printhhmmss(double secs) +{ + int mins = (int) secs / 60; + int hours = mins / 60; + + secs -= 60 * mins; + mins -= 60 * hours; + if (hours) + fprintf(stderr, "%d:%02d:%05.2f", hours, mins, secs); + else if (mins) + fprintf(stderr, "%d:%05.2f", mins, secs); + else + fprintf(stderr, "%.3f", secs); +} + +static void +printtime(struct timeval *real, child_times_t *ti, char *desc) +{ + char *s; + double elapsed_time, user_time, system_time; +#ifdef HAVE_GETRUSAGE + double total_time; +#endif + int percent, desclen; + + if (!desc) + { + desc = ""; + desclen = 0; + } + else + { + desc = dupstring(desc); + unmetafy(desc, &desclen); + } + + /* go ahead and compute these, since almost every TIMEFMT will have them */ + elapsed_time = real->tv_sec + real->tv_usec / 1000000.0; + +#ifdef HAVE_GETRUSAGE + user_time = ti->ru_utime.tv_sec + ti->ru_utime.tv_usec / 1000000.0; + system_time = ti->ru_stime.tv_sec + ti->ru_stime.tv_usec / 1000000.0; + total_time = user_time + system_time; + percent = 100.0 * total_time + / (real->tv_sec + real->tv_usec / 1000000.0); +#else + { + long clktck = get_clktck(); + user_time = ti->ut / (double) clktck; + system_time = ti->st / (double) clktck; + percent = 100.0 * (ti->ut + ti->st) + / (clktck * real->tv_sec + clktck * real->tv_usec / 1000000.0); + } +#endif + + queue_signals(); + if (!(s = getsparam("TIMEFMT"))) + s = DEFAULT_TIMEFMT; + else + s = unmetafy(s, NULL); + + for (; *s; s++) + if (*s == '%') + switch (*++s) { + case 'E': + fprintf(stderr, "%4.2fs", elapsed_time); + break; + case 'U': + fprintf(stderr, "%4.2fs", user_time); + break; + case 'S': + fprintf(stderr, "%4.2fs", system_time); + break; + case 'm': + switch (*++s) { + case 'E': + fprintf(stderr, "%0.fms", elapsed_time * 1000.0); + break; + case 'U': + fprintf(stderr, "%0.fms", user_time * 1000.0); + break; + case 'S': + fprintf(stderr, "%0.fms", system_time * 1000.0); + break; + default: + fprintf(stderr, "%%m"); + s--; + break; + } + break; + case 'u': + switch (*++s) { + case 'E': + fprintf(stderr, "%0.fus", elapsed_time * 1000000.0); + break; + case 'U': + fprintf(stderr, "%0.fus", user_time * 1000000.0); + break; + case 'S': + fprintf(stderr, "%0.fus", system_time * 1000000.0); + break; + default: + fprintf(stderr, "%%u"); + s--; + break; + } + break; + case '*': + switch (*++s) { + case 'E': + printhhmmss(elapsed_time); + break; + case 'U': + printhhmmss(user_time); + break; + case 'S': + printhhmmss(system_time); + break; + default: + fprintf(stderr, "%%*"); + s--; + break; + } + break; + case 'P': + fprintf(stderr, "%d%%", percent); + break; +#ifdef HAVE_STRUCT_RUSAGE_RU_NSWAP + case 'W': + fprintf(stderr, "%ld", ti->ru_nswap); + break; +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_IXRSS + case 'X': + fprintf(stderr, "%ld", + total_time ? + (long)(ti->ru_ixrss / total_time) : + (long)0); + break; +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_IDRSS + case 'D': + fprintf(stderr, "%ld", + total_time ? + (long) ((ti->ru_idrss +#ifdef HAVE_STRUCT_RUSAGE_RU_ISRSS + + ti->ru_isrss +#endif + ) / total_time) : + (long)0); + break; +#endif +#if defined(HAVE_STRUCT_RUSAGE_RU_IDRSS) || \ + defined(HAVE_STRUCT_RUSAGE_RU_ISRSS) || \ + defined(HAVE_STRUCT_RUSAGE_RU_IXRSS) + case 'K': + /* treat as D if X not available */ + fprintf(stderr, "%ld", + total_time ? + (long) (( +#ifdef HAVE_STRUCT_RUSAGE_RU_IXRSS + ti->ru_ixrss +#else + 0 +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_IDRSS + + ti->ru_idrss +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_ISRSS + + ti->ru_isrss +#endif + ) / total_time) : + (long)0); + break; +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_MAXRSS + case 'M': + fprintf(stderr, "%ld", ti->ru_maxrss / 1024); + break; +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_MAJFLT + case 'F': + fprintf(stderr, "%ld", ti->ru_majflt); + break; +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_MINFLT + case 'R': + fprintf(stderr, "%ld", ti->ru_minflt); + break; +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_INBLOCK + case 'I': + fprintf(stderr, "%ld", ti->ru_inblock); + break; +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_OUBLOCK + case 'O': + fprintf(stderr, "%ld", ti->ru_oublock); + break; +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_MSGRCV + case 'r': + fprintf(stderr, "%ld", ti->ru_msgrcv); + break; +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_MSGSND + case 's': + fprintf(stderr, "%ld", ti->ru_msgsnd); + break; +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_NSIGNALS + case 'k': + fprintf(stderr, "%ld", ti->ru_nsignals); + break; +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_NVCSW + case 'w': + fprintf(stderr, "%ld", ti->ru_nvcsw); + break; +#endif +#ifdef HAVE_STRUCT_RUSAGE_RU_NIVCSW + case 'c': + fprintf(stderr, "%ld", ti->ru_nivcsw); + break; +#endif + case 'J': + fwrite(desc, sizeof(char), desclen, stderr); + break; + case '%': + putc('%', stderr); + break; + case '\0': + s--; + break; + default: + fprintf(stderr, "%%%c", *s); + break; + } else + putc(*s, stderr); + unqueue_signals(); + putc('\n', stderr); + fflush(stderr); +} + +/**/ +static void +dumptime(Job jn) +{ + Process pn; + struct timeval dtimeval; + + if (!jn->procs) + return; + for (pn = jn->procs; pn; pn = pn->next) + printtime(dtime(&dtimeval, &pn->bgtime, &pn->endtime), &pn->ti, + pn->text); +} + +/* Check whether shell should report the amount of time consumed * + * by job. This will be the case if we have preceded the command * + * with the keyword time, or if REPORTTIME is non-negative and the * + * amount of time consumed by the job is greater than REPORTTIME */ + +/**/ +static int +should_report_time(Job j) +{ + struct value vbuf; + Value v; + char *s = "REPORTTIME"; + int save_errflag = errflag; + zlong reporttime = -1; +#ifdef HAVE_GETRUSAGE + char *sm = "REPORTMEMORY"; + zlong reportmemory = -1; +#endif + + /* if the time keyword was used */ + if (j->stat & STAT_TIMED) + return 1; + + queue_signals(); + errflag = 0; + if ((v = getvalue(&vbuf, &s, 0))) + reporttime = getintvalue(v); +#ifdef HAVE_GETRUSAGE + if ((v = getvalue(&vbuf, &sm, 0))) + reportmemory = getintvalue(v); +#endif + errflag = save_errflag; + unqueue_signals(); + if (reporttime < 0 +#ifdef HAVE_GETRUSAGE + && reportmemory < 0 +#endif + ) + return 0; + /* can this ever happen? */ + if (!j->procs) + return 0; + if (zleactive) + return 0; + + if (reporttime >= 0) + { +#ifdef HAVE_GETRUSAGE + reporttime -= j->procs->ti.ru_utime.tv_sec + + j->procs->ti.ru_stime.tv_sec; + if (j->procs->ti.ru_utime.tv_usec + + j->procs->ti.ru_stime.tv_usec >= 1000000) + reporttime--; + if (reporttime <= 0) + return 1; +#else + { + clktck = get_clktck(); + if ((j->procs->ti.ut + j->procs->ti.st) / clktck >= reporttime) + return 1; + } +#endif + } + +#ifdef HAVE_GETRUSAGE + if (reportmemory >= 0 && + j->procs->ti.ru_maxrss / 1024 > reportmemory) + return 1; +#endif + + return 0; +} + +/* !(lng & 3) means jobs * + * (lng & 1) means jobs -l * + * (lng & 2) means jobs -p + * (lng & 4) means jobs -d + * + * synch = 0 means asynchronous + * synch = 1 means synchronous + * synch = 2 means called synchronously from jobs + * synch = 3 means called synchronously from bg or fg + * + * Returns 1 if some output was done. + * + * The function also deletes the job if it was done, even it + * is not printed. + */ + +/**/ +int +printjob(Job jn, int lng, int synch) +{ + Process pn; + int job, len = 9, sig, sflag = 0, llen; + int conted = 0, lineleng = zterm_columns, skip = 0, doputnl = 0; + int doneprint = 0, skip_print = 0; + FILE *fout = (synch == 2 || !shout) ? stdout : shout; + + if (synch > 1 && oldjobtab != NULL) + job = jn - oldjobtab; + else + job = jn - jobtab; + DPUTS3(job < 0 || job > (oldjobtab && synch > 1 ? oldmaxjob : maxjob), + "bogus job number, jn = %L, jobtab = %L, oldjobtab = %L", + (long)jn, (long)jobtab, (long)oldjobtab); + + if (jn->stat & STAT_NOPRINT) { + skip_print = 1; + } + + if (lng < 0) { + conted = 1; + lng = !!isset(LONGLISTJOBS); + } + +/* find length of longest signame, check to see */ +/* if we really need to print this job */ + + for (pn = jn->procs; pn; pn = pn->next) { + if (jn->stat & STAT_SUPERJOB && + jn->procs->status == SP_RUNNING && !pn->next) + pn->status = SP_RUNNING; + if (pn->status != SP_RUNNING) { + if (WIFSIGNALED(pn->status)) { + sig = WTERMSIG(pn->status); + llen = strlen(sigmsg(sig)); + if (WCOREDUMP(pn->status)) + llen += 14; + if (llen > len) + len = llen; + if (sig != SIGINT && sig != SIGPIPE) + sflag = 1; + if (job == thisjob && sig == SIGINT) + doputnl = 1; + if (isset(PRINTEXITVALUE) && isset(SHINSTDIN)) { + sflag = 1; + skip_print = 0; + } + } else if (WIFSTOPPED(pn->status)) { + sig = WSTOPSIG(pn->status); + if ((int)strlen(sigmsg(sig)) > len) + len = strlen(sigmsg(sig)); + if (job == thisjob && sig == SIGTSTP) + doputnl = 1; + } else if (isset(PRINTEXITVALUE) && isset(SHINSTDIN) && + WEXITSTATUS(pn->status)) { + sflag = 1; + skip_print = 0; + } + } + } + + if (skip_print) { + if (jn->stat & STAT_DONE) { + /* This looks silly, but see update_job() */ + if (synch <= 1) + storepipestats(jn, job == thisjob, job == thisjob); + if (should_report_time(jn)) + dumptime(jn); + deletejob(jn, 0); + if (job == curjob) { + curjob = prevjob; + prevjob = job; + } + if (job == prevjob) + setprevjob(); + } + return 0; + } + + /* + * - Always print if called from jobs + * - Otherwise, require MONITOR option ("jobbing") and some + * change of state + * - also either the shell is interactive or this is synchronous. + */ + if (synch == 2 || + ((interact || synch) && jobbing && + ((jn->stat & STAT_STOPPED) || sflag || job != thisjob))) { + int len2, fline = 1; + /* POSIX requires just the job text for bg and fg */ + int plainfmt = (synch == 3) && isset(POSIXJOBS); + /* use special format for current job, except in `jobs' */ + int thisfmt = job == thisjob && synch != 2; + Process qn; + + if (!synch) + zleentry(ZLE_CMD_TRASH); + if (doputnl && !synch) { + doneprint = 1; + putc('\n', fout); + } + for (pn = jn->procs; pn;) { + len2 = (thisfmt ? 5 : 10) + len; /* 2 spaces */ + if (lng & 3) + qn = pn->next; + else + for (qn = pn->next; qn; qn = qn->next) { + if (qn->status != pn->status) + break; + if ((int)strlen(qn->text) + len2 + ((qn->next) ? 3 : 0) + > lineleng) + break; + len2 += strlen(qn->text) + 2; + } + doneprint = 1; + if (!plainfmt) { + if (!thisfmt || lng) { + if (fline) + fprintf(fout, "[%ld] %c ", + (long)job, + (job == curjob) ? '+' + : (job == prevjob) ? '-' : ' '); + else + fprintf(fout, (job > 9) ? " " : " "); + } else + fprintf(fout, "zsh: "); + if (lng & 1) + fprintf(fout, "%ld ", (long) pn->pid); + else if (lng & 2) { + pid_t x = jn->gleader; + + fprintf(fout, "%ld ", (long) x); + do + skip++; + while ((x /= 10)); + skip++; + lng &= ~3; + } else + fprintf(fout, "%*s", skip, ""); + if (pn->status == SP_RUNNING) { + if (!conted) + fprintf(fout, "running%*s", len - 7 + 2, ""); + else + fprintf(fout, "continued%*s", len - 9 + 2, ""); + } + else if (WIFEXITED(pn->status)) { + if (WEXITSTATUS(pn->status)) + fprintf(fout, "exit %-4d%*s", WEXITSTATUS(pn->status), + len - 9 + 2, ""); + else + fprintf(fout, "done%*s", len - 4 + 2, ""); + } else if (WIFSTOPPED(pn->status)) + fprintf(fout, "%-*s", len + 2, + sigmsg(WSTOPSIG(pn->status))); + else if (WCOREDUMP(pn->status)) + fprintf(fout, "%s (core dumped)%*s", + sigmsg(WTERMSIG(pn->status)), + (int)(len - 14 + 2 - + strlen(sigmsg(WTERMSIG(pn->status)))), ""); + else + fprintf(fout, "%-*s", len + 2, + sigmsg(WTERMSIG(pn->status))); + } + for (; pn != qn; pn = pn->next) { + char *txt = dupstring(pn->text); + int txtlen; + unmetafy(txt, &txtlen); + fwrite(txt, sizeof(char), txtlen, fout); + if (pn->next) + fputs(" | ", fout); + } + putc('\n', fout); + fline = 0; + } + fflush(fout); + } else if (doputnl && interact && !synch) { + doneprint = 1; + putc('\n', fout); + fflush(fout); + } + + /* print "(pwd now: foo)" messages: with (lng & 4) we are printing + * the directory where the job is running, otherwise the current directory + */ + + if ((lng & 4) || (interact && job == thisjob && + jn->pwd && strcmp(jn->pwd, pwd))) { + doneprint = 1; + fprintf(fout, "(pwd %s: ", (lng & 4) ? "" : "now"); + fprintdir(((lng & 4) && jn->pwd) ? jn->pwd : pwd, fout); + fprintf(fout, ")\n"); + fflush(fout); + } + + /* delete job if done */ + + if (jn->stat & STAT_DONE) { + /* This looks silly, but see update_job() */ + if (synch <= 1) + storepipestats(jn, job == thisjob, job == thisjob); + if (should_report_time(jn)) + dumptime(jn); + deletejob(jn, 0); + if (job == curjob) { + curjob = prevjob; + prevjob = job; + } + if (job == prevjob) + setprevjob(); + } else + jn->stat &= ~STAT_CHANGED; + + return doneprint; +} + +/* Add a file to be deleted or fd to be closed to the current job */ + +/**/ +void +addfilelist(const char *name, int fd) +{ + Jobfile jf = (Jobfile)zalloc(sizeof(struct jobfile)); + LinkList ll = jobtab[thisjob].filelist; + + if (!ll) + ll = jobtab[thisjob].filelist = znewlinklist(); + if (name) + { + jf->u.name = ztrdup(name); + jf->is_fd = 0; + } + else + { + jf->u.fd = fd; + jf->is_fd = 1; + } + zaddlinknode(ll, jf); +} + +/* Clean up pipes no longer needed associated with a job */ + +/**/ +void +pipecleanfilelist(LinkList filelist, int proc_subst_only) +{ + LinkNode node; + + if (!filelist) + return; + node = firstnode(filelist); + while (node) { + Jobfile jf = (Jobfile)getdata(node); + if (jf->is_fd && + (!proc_subst_only || fdtable[jf->u.fd] == FDT_PROC_SUBST)) { + LinkNode next = nextnode(node); + zclose(jf->u.fd); + (void)remnode(filelist, node); + zfree(jf, sizeof(*jf)); + node = next; + } else + incnode(node); + } +} + +/* Finished with list of files for a job */ + +/**/ +void +deletefilelist(LinkList file_list, int disowning) +{ + Jobfile jf; + if (file_list) { + while ((jf = (Jobfile)getlinknode(file_list))) { + if (jf->is_fd) { + if (!disowning) + zclose(jf->u.fd); + } else { + if (!disowning) + unlink(jf->u.name); + zsfree(jf->u.name); + } + zfree(jf, sizeof(*jf)); + } + zfree(file_list, sizeof(struct linklist)); + } +} + +/**/ +void +freejob(Job jn, int deleting) +{ + struct process *pn, *nx; + + pn = jn->procs; + jn->procs = NULL; + for (; pn; pn = nx) { + nx = pn->next; + zfree(pn, sizeof(struct process)); + } + + pn = jn->auxprocs; + jn->auxprocs = NULL; + for (; pn; pn = nx) { + nx = pn->next; + zfree(pn, sizeof(struct process)); + } + + if (jn->ty) + zfree(jn->ty, sizeof(struct ttyinfo)); + if (jn->pwd) + zsfree(jn->pwd); + jn->pwd = NULL; + if (jn->stat & STAT_WASSUPER) { + /* careful in case we shrink and move the job table */ + int job = jn - jobtab; + if (deleting) + deletejob(jobtab + jn->other, 0); + else + freejob(jobtab + jn->other, 0); + jn = jobtab + job; + } + jn->gleader = jn->other = 0; + jn->stat = jn->stty_in_env = 0; + jn->filelist = NULL; + jn->ty = NULL; + + /* Find the new highest job number. */ + if (maxjob == jn - jobtab) { + while (maxjob && !(jobtab[maxjob].stat & STAT_INUSE)) + maxjob--; + } +} + +/* + * We are actually finished with this job, rather + * than freeing it to make space. + * + * If "disowning" is set, files associated with the job are not + * actually deleted --- and won't be as there is nothing left + * to clear up. + */ + +/**/ +void +deletejob(Job jn, int disowning) +{ + deletefilelist(jn->filelist, disowning); + if (jn->stat & STAT_ATTACH) { + attachtty(mypgrp); + adjustwinsize(0); + } + if (jn->stat & STAT_SUPERJOB) { + Job jno = jobtab + jn->other; + if (jno->stat & STAT_SUBJOB) + jno->stat |= STAT_SUBJOB_ORPHANED; + } + + freejob(jn, 1); +} + +/* + * Add a process to the current job. + * The third argument is 1 if we are adding a process which is not + * part of the main pipeline but an auxiliary process used for + * handling MULTIOS or process substitution. We will wait for it + * but not display job information about it. + */ + +/**/ +void +addproc(pid_t pid, char *text, int aux, struct timeval *bgtime) +{ + Process pn, *pnlist; + + DPUTS(thisjob == -1, "No valid job in addproc."); + pn = (Process) zshcalloc(sizeof *pn); + pn->pid = pid; + if (text) + strcpy(pn->text, text); + else + *pn->text = '\0'; + pn->status = SP_RUNNING; + pn->next = NULL; + + if (!aux) + { + pn->bgtime = *bgtime; + /* if this is the first process we are adding to * + * the job, then it's the group leader. */ + if (!jobtab[thisjob].gleader) + jobtab[thisjob].gleader = pid; + /* attach this process to end of process list of current job */ + pnlist = &jobtab[thisjob].procs; + } + else + pnlist = &jobtab[thisjob].auxprocs; + + if (*pnlist) { + Process n; + + for (n = *pnlist; n->next; n = n->next); + n->next = pn; + } else { + /* first process for this job */ + *pnlist = pn; + } + /* If the first process in the job finished before any others were * + * added, maybe STAT_DONE got set incorrectly. This can happen if * + * a $(...) was waited for and the last existing job in the * + * pipeline was already finished. We need to be very careful that * + * there was no call to printjob() between then and now, else * + * the job will already have been deleted from the table. */ + jobtab[thisjob].stat &= ~STAT_DONE; +} + +/* Check if we have files to delete. We need to check this to see * + * if it's all right to exec a command without forking in the last * + * component of subshells or after the `-c' option. */ + +/**/ +int +havefiles(void) +{ + int i; + + for (i = 1; i <= maxjob; i++) + if (jobtab[i].stat && jobtab[i].filelist) + return 1; + return 0; + +} + +/* + * Wait for a particular process. + * wait_cmd indicates this is from the interactive wait command, + * in which case the behaviour is a little different: the command + * itself can be interrupted by a trapped signal. + */ + +/**/ +int +waitforpid(pid_t pid, int wait_cmd) +{ + int first = 1, q = queue_signal_level(); + + /* child_block() around this loop in case #ifndef WNOHANG */ + dont_queue_signals(); + child_block(); /* unblocked in signal_suspend() */ + queue_traps(wait_cmd); + + /* This function should never be called with a pid that is not a + * child of the current shell. Consequently, if kill(0, pid) + * fails here with ESRCH, the child has already been reaped. In + * the loop body, we expect this to happen in signal_suspend() + * via zhandler(), after which this test terminates the loop. + */ + while (!errflag && (kill(pid, 0) >= 0 || errno != ESRCH)) { + if (first) + first = 0; + else if (!wait_cmd) + kill(pid, SIGCONT); + + last_signal = -1; + signal_suspend(SIGCHLD, wait_cmd); + if (last_signal != SIGCHLD && wait_cmd && last_signal >= 0 && + (sigtrapped[last_signal] & ZSIG_TRAPPED)) { + /* wait command interrupted, but no error: return */ + restore_queue_signals(q); + return 128 + last_signal; + } + child_block(); + } + unqueue_traps(); + child_unblock(); + restore_queue_signals(q); + + return 0; +} + +/* + * Wait for a job to finish. + * wait_cmd indicates this is from the wait builtin; see + * wait_cmd in waitforpid(). + */ + +/**/ +static int +zwaitjob(int job, int wait_cmd) +{ + int q = queue_signal_level(); + Job jn = jobtab + job; + + child_block(); /* unblocked during signal_suspend() */ + queue_traps(wait_cmd); + dont_queue_signals(); + if (jn->procs || jn->auxprocs) { /* if any forks were done */ + jn->stat |= STAT_LOCKED; + if (jn->stat & STAT_CHANGED) + printjob(jn, !!isset(LONGLISTJOBS), 1); + if (jn->filelist) { + /* + * The main shell is finished with any file descriptors used + * for process substitution associated with this job: close + * them to indicate to listeners there's no more input. + * + * Note we can't safely delete temporary files yet as these + * are directly visible to other processes. However, + * we can't deadlock on the fact that those still exist, so + * that's not a problem. + */ + pipecleanfilelist(jn->filelist, 0); + } + while (!(errflag & ERRFLAG_ERROR) && jn->stat && + !(jn->stat & STAT_DONE) && + !(interact && (jn->stat & STAT_STOPPED))) { + signal_suspend(SIGCHLD, wait_cmd); + if (last_signal != SIGCHLD && wait_cmd && last_signal >= 0 && + (sigtrapped[last_signal] & ZSIG_TRAPPED)) + { + /* builtin wait interrupted by trapped signal */ + restore_queue_signals(q); + return 128 + last_signal; + } + /* Commenting this out makes ^C-ing a job started by a function + stop the whole function again. But I guess it will stop + something else from working properly, we have to find out + what this might be. --oberon + + When attempting to separate errors and interrupts, we + assumed because of the previous comment it would be OK + to remove ERRFLAG_ERROR and leave ERRFLAG_INT set, since + that's the one related to ^C. But that doesn't work. + There's something more here we don't understand. --pws + + The change above to ignore ERRFLAG_INT in the loop test + solves a problem wherein child processes that ignore the + INT signal were never waited-for. Clearing the flag here + still seems the wrong thing, but perhaps ERRFLAG_INT + should be saved and restored around signal_suspend() to + prevent it being lost within a signal trap? --Bart + + errflag = 0; */ + + if (subsh) { + killjb(jn, SIGCONT); + jn->stat &= ~STAT_STOPPED; + } + if (jn->stat & STAT_SUPERJOB) + if (handle_sub(jn - jobtab, 1)) + break; + child_block(); + } + } else { + deletejob(jn, 0); + pipestats[0] = lastval; + numpipestats = 1; + } + restore_queue_signals(q); + unqueue_traps(); + child_unblock(); + + return 0; +} + +/* wait for running job to finish */ + +/**/ +void +waitjobs(void) +{ + Job jn = jobtab + thisjob; + DPUTS(thisjob == -1, "No valid job in waitjobs."); + + if (jn->procs || jn->auxprocs) + zwaitjob(thisjob, 0); + else { + deletejob(jn, 0); + pipestats[0] = lastval; + numpipestats = 1; + } + thisjob = -1; +} + +/* clear job table when entering subshells */ + +/**/ +mod_export void +clearjobtab(int monitor) +{ + int i; + + if (isset(POSIXJOBS)) + oldmaxjob = 0; + for (i = 1; i <= maxjob; i++) { + /* + * See if there is a jobtable worth saving. + * We never free the saved version; it only happens + * once for each subshell of a shell with job control, + * so doesn't create a leak. + */ + if (monitor && !isset(POSIXJOBS) && jobtab[i].stat) + oldmaxjob = i+1; + else if (jobtab[i].stat & STAT_INUSE) + freejob(jobtab + i, 0); + } + + if (monitor && oldmaxjob) { + int sz = oldmaxjob * sizeof(struct job); + if (oldjobtab) + free(oldjobtab); + oldjobtab = (struct job *)zalloc(sz); + memcpy(oldjobtab, jobtab, sz); + + /* Don't report any job we're part of */ + if (thisjob != -1 && thisjob < oldmaxjob) + memset(oldjobtab+thisjob, 0, sizeof(struct job)); + } + + memset(jobtab, 0, jobtabsize * sizeof(struct job)); /* zero out table */ + maxjob = 0; + + /* + * Although we don't have job control in subshells, we + * sometimes needs control structures for other purposes such + * as multios. Grab a job for this purpose; any will do + * since we've freed them all up (so there's no question + * of problems with the job table size here). + */ + thisjob = initjob(); +} + +static int initnewjob(int i) +{ + jobtab[i].stat = STAT_INUSE; + if (jobtab[i].pwd) { + zsfree(jobtab[i].pwd); + jobtab[i].pwd = NULL; + } + jobtab[i].gleader = 0; + + if (i > maxjob) + maxjob = i; + + return i; +} + +/* Get a free entry in the job table and initialize it. */ + +/**/ +int +initjob(void) +{ + int i; + + for (i = 1; i <= maxjob; i++) + if (!jobtab[i].stat) + return initnewjob(i); + if (maxjob + 1 < jobtabsize) + return initnewjob(maxjob+1); + + if (expandjobtab()) + return initnewjob(i); + + zerr("job table full or recursion limit exceeded"); + return -1; +} + +/**/ +void +setjobpwd(void) +{ + int i; + + for (i = 1; i <= maxjob; i++) + if (jobtab[i].stat && !jobtab[i].pwd) + jobtab[i].pwd = ztrdup(pwd); +} + +/* print pids for & */ + +/**/ +void +spawnjob(void) +{ + Process pn; + + DPUTS(thisjob == -1, "No valid job in spawnjob."); + /* if we are not in a subshell */ + if (!subsh) { + if (curjob == -1 || !(jobtab[curjob].stat & STAT_STOPPED)) { + curjob = thisjob; + setprevjob(); + } else if (prevjob == -1 || !(jobtab[prevjob].stat & STAT_STOPPED)) + prevjob = thisjob; + if (jobbing && jobtab[thisjob].procs) { + FILE *fout = shout ? shout : stdout; + fprintf(fout, "[%d]", thisjob); + for (pn = jobtab[thisjob].procs; pn; pn = pn->next) + fprintf(fout, " %ld", (long) pn->pid); + fprintf(fout, "\n"); + fflush(fout); + } + } + if (!hasprocs(thisjob)) + deletejob(jobtab + thisjob, 0); + else { + jobtab[thisjob].stat |= STAT_LOCKED; + pipecleanfilelist(jobtab[thisjob].filelist, 0); + } + thisjob = -1; +} + +/**/ +void +shelltime(void) +{ + struct timezone dummy_tz; + struct timeval dtimeval, now; + child_times_t ti; +#ifndef HAVE_GETRUSAGE + struct tms buf; +#endif + + gettimeofday(&now, &dummy_tz); + +#ifdef HAVE_GETRUSAGE + getrusage(RUSAGE_SELF, &ti); +#else + times(&buf); + + ti.ut = buf.tms_utime; + ti.st = buf.tms_stime; +#endif + printtime(dtime(&dtimeval, &shtimer, &now), &ti, "shell"); + +#ifdef HAVE_GETRUSAGE + getrusage(RUSAGE_CHILDREN, &ti); +#else + ti.ut = buf.tms_cutime; + ti.st = buf.tms_cstime; +#endif + printtime(&dtimeval, &ti, "children"); + +} + +/* see if jobs need printing */ + +/**/ +void +scanjobs(void) +{ + int i; + + for (i = 1; i <= maxjob; i++) + if (jobtab[i].stat & STAT_CHANGED) + printjob(jobtab + i, !!isset(LONGLISTJOBS), 1); +} + +/**** job control builtins ****/ + +/* This simple function indicates whether or not s may represent * + * a number. It returns true iff s consists purely of digits and * + * minuses. Note that minus may appear more than once, and the empty * + * string will produce a `true' response. */ + +/**/ +static int +isanum(char *s) +{ + while (*s == '-' || idigit(*s)) + s++; + return *s == '\0'; +} + +/* Make sure we have a suitable current and previous job set. */ + +/**/ +static void +setcurjob(void) +{ + if (curjob == thisjob || + (curjob != -1 && !(jobtab[curjob].stat & STAT_INUSE))) { + curjob = prevjob; + setprevjob(); + if (curjob == thisjob || + (curjob != -1 && !((jobtab[curjob].stat & STAT_INUSE) && + curjob != thisjob))) { + curjob = prevjob; + setprevjob(); + } + } +} + +/* Convert a job specifier ("%%", "%1", "%foo", "%?bar?", etc.) * + * to a job number. */ + +/**/ +mod_export int +getjob(const char *s, const char *prog) +{ + int jobnum, returnval, mymaxjob; + Job myjobtab; + + if (oldjobtab) { + myjobtab = oldjobtab; + mymaxjob = oldmaxjob; + } else { + myjobtab= jobtab; + mymaxjob = maxjob; + } + + /* if there is no %, treat as a name */ + if (*s != '%') + goto jump; + s++; + /* "%%", "%+" and "%" all represent the current job */ + if (*s == '%' || *s == '+' || !*s) { + if (curjob == -1) { + if (prog) + zwarnnam(prog, "no current job"); + returnval = -1; + goto done; + } + returnval = curjob; + goto done; + } + /* "%-" represents the previous job */ + if (*s == '-') { + if (prevjob == -1) { + if (prog) + zwarnnam(prog, "no previous job"); + returnval = -1; + goto done; + } + returnval = prevjob; + goto done; + } + /* a digit here means we have a job number */ + if (idigit(*s)) { + jobnum = atoi(s); + if (jobnum && jobnum <= mymaxjob && myjobtab[jobnum].stat && + !(myjobtab[jobnum].stat & STAT_SUBJOB) && + /* + * If running jobs in a subshell, we are allowed to + * refer to the "current" job (it's not really the + * current job in the subshell). It's possible we + * should reset thisjob to -1 on entering the subshell. + */ + (myjobtab == oldjobtab || jobnum != thisjob)) { + returnval = jobnum; + goto done; + } + if (prog) + zwarnnam(prog, "%%%s: no such job", s); + returnval = -1; + goto done; + } + /* "%?" introduces a search string */ + if (*s == '?') { + struct process *pn; + + for (jobnum = mymaxjob; jobnum >= 0; jobnum--) + if (myjobtab[jobnum].stat && + !(myjobtab[jobnum].stat & STAT_SUBJOB) && + jobnum != thisjob) + for (pn = myjobtab[jobnum].procs; pn; pn = pn->next) + if (strstr(pn->text, s + 1)) { + returnval = jobnum; + goto done; + } + if (prog) + zwarnnam(prog, "job not found: %s", s); + returnval = -1; + goto done; + } + jump: + /* anything else is a job name, specified as a string that begins the + job's command */ + if ((jobnum = findjobnam(s)) != -1) { + returnval = jobnum; + goto done; + } + /* if we get here, it is because none of the above succeeded and went + to done */ + zwarnnam(prog, "job not found: %s", s); + returnval = -1; + done: + return returnval; +} + +#ifndef HAVE_SETPROCTITLE +/* For jobs -Z (which modifies the shell's name as seen in ps listings). * + * hackzero is the start of the safely writable space, and hackspace is * + * its length, excluding a final NUL terminator that will always be left. */ + +static char *hackzero; +static int hackspace; +#endif + + +/* Initialise job handling. */ + +/**/ +void +init_jobs(char **argv, char **envp) +{ +#ifndef HAVE_SETPROCTITLE + char *p, *q; +#endif + size_t init_bytes = MAXJOBS_ALLOC*sizeof(struct job); + + /* + * Initialise the job table. If this fails, we're in trouble. + */ + jobtab = (struct job *)zalloc(init_bytes); + if (!jobtab) { + zerr("failed to allocate job table, aborting."); + exit(1); + } + jobtabsize = MAXJOBS_ALLOC; + memset(jobtab, 0, init_bytes); + +#ifndef HAVE_SETPROCTITLE + /* + * Initialise the jobs -Z system. The technique is borrowed from + * perl: check through the argument and environment space, to see + * how many of the strings are in contiguous space. This determines + * the value of hackspace. + */ + hackzero = *argv; + p = strchr(hackzero, 0); + while(*++argv) { + q = *argv; + if(q != p+1) + goto done; + p = strchr(q, 0); + } +#if !defined(HAVE_PUTENV) && !defined(USE_SET_UNSET_ENV) + for(; *envp; envp++) { + q = *envp; + if(q != p+1) + goto done; + p = strchr(q, 0); + } +#endif + done: + hackspace = p - hackzero; +#endif +} + + +/* + * We have run out of space in the job table. + * Expand it by an additional MAXJOBS_ALLOC slots. + */ + +/* + * An arbitrary limit on the absolute maximum size of the job table. + * This prevents us taking over the entire universe. + * Ought to be a multiple of MAXJOBS_ALLOC, but doesn't need to be. + */ +#define MAX_MAXJOBS 1000 + +/**/ +int +expandjobtab(void) +{ + int newsize = jobtabsize + MAXJOBS_ALLOC; + struct job *newjobtab; + + if (newsize > MAX_MAXJOBS) + return 0; + + newjobtab = (struct job *)zrealloc(jobtab, newsize * sizeof(struct job)); + if (!newjobtab) + return 0; + + /* + * Clear the new section of the table; this is necessary for + * the jobs to appear unused. + */ + memset(newjobtab + jobtabsize, 0, MAXJOBS_ALLOC * sizeof(struct job)); + + jobtab = newjobtab; + jobtabsize = newsize; + + return 1; +} + + +/* + * See if we can reduce the job table. We can if we go over + * a MAXJOBS_ALLOC boundary. However, we leave a boundary, + * currently 20 jobs, so that we have a place for immediate + * expansion and don't play ping pong with the job table size. + */ + +/**/ +void +maybeshrinkjobtab(void) +{ + int jobbound; + + queue_signals(); + jobbound = maxjob + MAXJOBS_ALLOC - (maxjob % MAXJOBS_ALLOC); + if (jobbound < jobtabsize && jobbound > maxjob + 20) { + struct job *newjobtab; + + /* Hope this can't fail, but anyway... */ + newjobtab = (struct job *)zrealloc(jobtab, + jobbound*sizeof(struct job)); + + if (newjobtab) { + jobtab = newjobtab; + jobtabsize = jobbound; + } + } + unqueue_signals(); +} + +/* + * Definitions for the background process stuff recorded below. + * This would be more efficient as a hash, but + * - that's quite heavyweight for something not needed very often + * - we need some kind of ordering as POSIX allows us to limit + * the size of the list to the value of _SC_CHILD_MAX and clearly + * we want to clear the oldest first + * - cases with a long list of background jobs where the user doesn't + * wait for a large number, and then does wait for one (the only + * inefficient case) are rare + * - in the context of waiting for an external process, looping + * over a list isn't so very inefficient. + * Enough excuses already. + */ + +/* Data in the link list, a key (process ID) / value (exit status) pair. */ +struct bgstatus { + pid_t pid; + int status; +}; +typedef struct bgstatus *Bgstatus; +/* The list of those entries */ +static LinkList bgstatus_list; +/* Count of entries. Reaches value of _SC_CHILD_MAX and stops. */ +static long bgstatus_count; + +/* + * Remove and free a bgstatus entry. + */ +static void rembgstatus(LinkNode node) +{ + zfree(remnode(bgstatus_list, node), sizeof(struct bgstatus)); + bgstatus_count--; +} + +/* + * Record the status of a background process that exited so we + * can execute the builtin wait for it. + * + * We can't execute the wait builtin for something that exited in the + * foreground as it's not visible to the user, so don't bother recording. + */ + +/**/ +void +addbgstatus(pid_t pid, int status) +{ + static long child_max; + Bgstatus bgstatus_entry; + + if (!child_max) { +#ifdef _SC_CHILD_MAX + child_max = sysconf(_SC_CHILD_MAX); + if (!child_max) /* paranoia */ +#endif + { + /* Be inventive */ + child_max = 1024L; + } + } + + if (!bgstatus_list) { + bgstatus_list = znewlinklist(); + /* + * We're not always robust about memory failures, but + * this is pretty deep in the shell basics to be failing owing + * to memory, and a failure to wait is reported loudly, so test + * and fail silently here. + */ + if (!bgstatus_list) + return; + } + if (bgstatus_count == child_max) { + /* Overflow. List is in order, remove first */ + rembgstatus(firstnode(bgstatus_list)); + } + bgstatus_entry = (Bgstatus)zalloc(sizeof(*bgstatus_entry)); + if (!bgstatus_entry) { + /* See note above */ + return; + } + bgstatus_entry->pid = pid; + bgstatus_entry->status = status; + if (!zaddlinknode(bgstatus_list, bgstatus_entry)) { + zfree(bgstatus_entry, sizeof(*bgstatus_entry)); + return; + } + bgstatus_count++; +} + +/* + * See if pid has a recorded exit status. + * Note we make no guarantee that the PIDs haven't wrapped, so this + * may not be the right process. + * + * This is only used by wait, which must only work on each + * pid once, so we need to remove the entry if we find it. + */ + +static int getbgstatus(pid_t pid) +{ + LinkNode node; + Bgstatus bgstatus_entry; + + if (!bgstatus_list) + return -1; + for (node = firstnode(bgstatus_list); node; incnode(node)) { + bgstatus_entry = (Bgstatus)getdata(node); + if (bgstatus_entry->pid == pid) { + int status = bgstatus_entry->status; + rembgstatus(node); + return status; + } + } + return -1; +} + +/* bg, disown, fg, jobs, wait: most of the job control commands are * + * here. They all take the same type of argument. Exception: wait can * + * take a pid or a job specifier, whereas the others only work on jobs. */ + +/**/ +int +bin_fg(char *name, char **argv, Options ops, int func) +{ + int job, lng, firstjob = -1, retval = 0, ofunc = func; + + if (OPT_ISSET(ops,'Z')) { + int len; + + if(isset(RESTRICTED)) { + zwarnnam(name, "-Z is restricted"); + return 1; + } + if(!argv[0] || argv[1]) { + zwarnnam(name, "-Z requires one argument"); + return 1; + } + queue_signals(); + unmetafy(*argv, &len); +#ifdef HAVE_SETPROCTITLE + setproctitle("%s", *argv); +#else + if(len > hackspace) + len = hackspace; + memcpy(hackzero, *argv, len); + memset(hackzero + len, 0, hackspace - len); +#endif + unqueue_signals(); + return 0; + } + + if (func == BIN_JOBS) { + lng = (OPT_ISSET(ops,'l')) ? 1 : (OPT_ISSET(ops,'p')) ? 2 : 0; + if (OPT_ISSET(ops,'d')) + lng |= 4; + } else { + lng = !!isset(LONGLISTJOBS); + } + + if ((func == BIN_FG || func == BIN_BG) && !jobbing) { + /* oops... maybe bg and fg should have been disabled? */ + zwarnnam(name, "no job control in this shell."); + return 1; + } + + queue_signals(); + /* + * In case any processes changed state recently, wait for them. + * This updates stopped processes (but we should have been + * signalled about those, up to inevitable races), and also + * continued processes if that feature is available. + */ + wait_for_processes(); + + /* If necessary, update job table. */ + if (unset(NOTIFY)) + scanjobs(); + + if (func != BIN_JOBS || isset(MONITOR) || !oldmaxjob) + setcurjob(); + + if (func == BIN_JOBS) + /* If you immediately type "exit" after "jobs", this * + * will prevent zexit from complaining about stopped jobs */ + stopmsg = 2; + if (!*argv) { + /* This block handles all of the default cases (no arguments). bg, + fg and disown act on the current job, and jobs and wait act on all the + jobs. */ + if (func == BIN_FG || func == BIN_BG || func == BIN_DISOWN) { + /* W.r.t. the above comment, we'd better have a current job at this + point or else. */ + if (curjob == -1 || (jobtab[curjob].stat & STAT_NOPRINT)) { + zwarnnam(name, "no current job"); + unqueue_signals(); + return 1; + } + firstjob = curjob; + } else if (func == BIN_JOBS) { + /* List jobs. */ + struct job *jobptr; + int curmaxjob, ignorejob; + if (unset(MONITOR) && oldmaxjob) { + jobptr = oldjobtab; + curmaxjob = oldmaxjob ? oldmaxjob - 1 : 0; + ignorejob = 0; + } else { + jobptr = jobtab; + curmaxjob = maxjob; + ignorejob = thisjob; + } + for (job = 0; job <= curmaxjob; job++, jobptr++) + if (job != ignorejob && jobptr->stat) { + if ((!OPT_ISSET(ops,'r') && !OPT_ISSET(ops,'s')) || + (OPT_ISSET(ops,'r') && OPT_ISSET(ops,'s')) || + (OPT_ISSET(ops,'r') && + !(jobptr->stat & STAT_STOPPED)) || + (OPT_ISSET(ops,'s') && jobptr->stat & STAT_STOPPED)) + printjob(jobptr, lng, 2); + } + unqueue_signals(); + return 0; + } else { /* Must be BIN_WAIT, so wait for all jobs */ + for (job = 0; job <= maxjob; job++) + if (job != thisjob && jobtab[job].stat && + !(jobtab[job].stat & STAT_NOPRINT)) + retval = zwaitjob(job, 1); + unqueue_signals(); + return retval; + } + } + + /* Defaults have been handled. We now have an argument or two, or three... + In the default case for bg, fg and disown, the argument will be provided by + the above routine. We now loop over the arguments. */ + for (; (firstjob != -1) || *argv; (void)(*argv && argv++)) { + int stopped, ocj = thisjob, jstat; + + func = ofunc; + + if (func == BIN_WAIT && isanum(*argv)) { + /* wait can take a pid; the others can't. */ + pid_t pid = (long)atoi(*argv); + Job j; + Process p; + + if (findproc(pid, &j, &p, 0)) { + if (j->stat & STAT_STOPPED) { + retval = (killjb(j, SIGCONT) != 0); + if (retval == 0) + makerunning(j); + } + if (retval == 0) { + /* + * returns 0 for normal exit, else signal+128 + * in which case we should return that status. + */ + retval = waitforpid(pid, 1); + } + if (retval == 0) { + if ((retval = getbgstatus(pid)) < 0) { + retval = lastval2; + } + } + } else if ((retval = getbgstatus(pid)) < 0) { + zwarnnam(name, "pid %d is not a child of this shell", pid); + /* presumably lastval2 doesn't tell us a heck of a lot? */ + retval = 1; + } + thisjob = ocj; + continue; + } + if (func != BIN_JOBS && oldjobtab != NULL) { + zwarnnam(name, "can't manipulate jobs in subshell"); + unqueue_signals(); + return 1; + } + /* The only type of argument allowed now is a job spec. Check it. */ + job = (*argv) ? getjob(*argv, name) : firstjob; + firstjob = -1; + if (job == -1) { + retval = 1; + break; + } + jstat = oldjobtab ? oldjobtab[job].stat : jobtab[job].stat; + if (!(jstat & STAT_INUSE) || + (jstat & STAT_NOPRINT)) { + zwarnnam(name, "%s: no such job", *argv); + unqueue_signals(); + return 1; + } + /* If AUTO_CONTINUE is set (automatically make stopped jobs running + * on disown), we actually do a bg and then delete the job table entry. */ + + if (isset(AUTOCONTINUE) && func == BIN_DISOWN && + jstat & STAT_STOPPED) + func = BIN_BG; + + /* We have a job number. Now decide what to do with it. */ + switch (func) { + case BIN_FG: + case BIN_BG: + case BIN_WAIT: + if (func == BIN_BG) { + jobtab[job].stat |= STAT_NOSTTY; + jobtab[job].stat &= ~STAT_CURSH; + } + if ((stopped = (jobtab[job].stat & STAT_STOPPED))) { + makerunning(jobtab + job); + if (func == BIN_BG) { + /* Set $! to indicate this was backgrounded */ + Process pn = jobtab[job].procs; + for (;;) { + Process next = pn->next; + if (!next) { + lastpid = (zlong) pn->pid; + break; + } + pn = next; + } + } + } else if (func == BIN_BG) { + /* Silly to bg a job already running. */ + zwarnnam(name, "job already in background"); + thisjob = ocj; + unqueue_signals(); + return 1; + } + /* It's time to shuffle the jobs around! Reset the current job, + and pick a sensible secondary job. */ + if (curjob == job) { + curjob = prevjob; + prevjob = (func == BIN_BG) ? -1 : job; + } + if (prevjob == job || prevjob == -1) + setprevjob(); + if (curjob == -1) { + curjob = prevjob; + setprevjob(); + } + if (func != BIN_WAIT) + /* for bg and fg -- show the job we are operating on */ + printjob(jobtab + job, (stopped) ? -1 : lng, 3); + if (func != BIN_BG) { /* fg or wait */ + if (jobtab[job].pwd && strcmp(jobtab[job].pwd, pwd)) { + FILE *fout = (func == BIN_JOBS || !shout) ? stdout : shout; + fprintf(fout, "(pwd : "); + fprintdir(jobtab[job].pwd, fout); + fprintf(fout, ")\n"); + fflush(fout); + } + if (func != BIN_WAIT) { /* fg */ + thisjob = job; + if ((jobtab[job].stat & STAT_SUPERJOB) && + ((!jobtab[job].procs->next || + (jobtab[job].stat & STAT_SUBLEADER) || + killpg(jobtab[job].gleader, 0) == -1)) && + jobtab[jobtab[job].other].gleader) + attachtty(jobtab[jobtab[job].other].gleader); + else + attachtty(jobtab[job].gleader); + } + } + if (stopped) { + if (func != BIN_BG && jobtab[job].ty) + settyinfo(jobtab[job].ty); + killjb(jobtab + job, SIGCONT); + } + if (func == BIN_WAIT) + { + retval = zwaitjob(job, 1); + if (!retval) + retval = lastval2; + } + else if (func != BIN_BG) { + /* + * HERE: there used not to be an "else" above. How + * could it be right to wait for the foreground job + * when we've just been told to wait for another + * job (and done it)? + */ + waitjobs(); + retval = lastval2; + } else if (ofunc == BIN_DISOWN) + deletejob(jobtab + job, 1); + break; + case BIN_JOBS: + printjob(job + (oldjobtab ? oldjobtab : jobtab), lng, 2); + break; + case BIN_DISOWN: + if (jobtab[job].stat & STAT_SUPERJOB) { + jobtab[job].stat |= STAT_DISOWN; + continue; + } + if (jobtab[job].stat & STAT_STOPPED) { + char buf[20], *pids = ""; + + if (jobtab[job].stat & STAT_SUPERJOB) { + Process pn; + + for (pn = jobtab[jobtab[job].other].procs; pn; pn = pn->next) { + sprintf(buf, " -%d", pn->pid); + pids = dyncat(pids, buf); + } + for (pn = jobtab[job].procs; pn->next; pn = pn->next) { + sprintf(buf, " %d", pn->pid); + pids = dyncat(pids, buf); + } + if (!jobtab[jobtab[job].other].procs && pn) { + sprintf(buf, " %d", pn->pid); + pids = dyncat(pids, buf); + } + } else { + sprintf(buf, " -%d", jobtab[job].gleader); + pids = buf; + } + zwarnnam(name, +#ifdef USE_SUSPENDED + "warning: job is suspended, use `kill -CONT%s' to resume", +#else + "warning: job is stopped, use `kill -CONT%s' to resume", +#endif + pids); + } + deletejob(jobtab + job, 1); + break; + } + thisjob = ocj; + } + unqueue_signals(); + return retval; +} + +static const struct { + const char *name; + int num; +} alt_sigs[] = { +#if defined(SIGCHLD) && defined(SIGCLD) +#if SIGCHLD == SIGCLD + { "CLD", SIGCLD }, +#endif +#endif +#if defined(SIGPOLL) && defined(SIGIO) +#if SIGPOLL == SIGIO + { "IO", SIGIO }, +#endif +#endif +#if !defined(SIGERR) + /* + * If SIGERR is not defined by the operating system, use it + * as an alias for SIGZERR. + */ + { "ERR", SIGZERR }, +#endif + { NULL, 0 } +}; + +/* kill: send a signal to a process. The process(es) may be specified * + * by job specifier (see above) or pid. A signal, defaulting to * + * SIGTERM, may be specified by name or number, preceded by a dash. */ + +/**/ +int +bin_kill(char *nam, char **argv, UNUSED(Options ops), UNUSED(int func)) +{ + int sig = SIGTERM; + int returnval = 0; + + /* check for, and interpret, a signal specifier */ + if (*argv && **argv == '-') { + if (idigit((*argv)[1])) { + char *endp; + /* signal specified by number */ + sig = zstrtol(*argv + 1, &endp, 10); + if (*endp) { + zwarnnam(nam, "invalid signal number: %s", *argv); + return 1; + } + } else if ((*argv)[1] != '-' || (*argv)[2]) { + char *signame; + + /* with argument "-l" display the list of signal names */ + if ((*argv)[1] == 'l' && (*argv)[2] == '\0') { + if (argv[1]) { + while (*++argv) { + sig = zstrtol(*argv, &signame, 10); + if (signame == *argv) { + if (!strncmp(signame, "SIG", 3)) + signame += 3; + for (sig = 1; sig <= SIGCOUNT; sig++) + if (!strcasecmp(sigs[sig], signame)) + break; + if (sig > SIGCOUNT) { + int i; + + for (i = 0; alt_sigs[i].name; i++) + if (!strcasecmp(alt_sigs[i].name, signame)) + { + sig = alt_sigs[i].num; + break; + } + } + if (sig > SIGCOUNT) { + zwarnnam(nam, "unknown signal: SIG%s", + signame); + returnval++; + } else + printf("%d\n", sig); + } else { + if (*signame) { + zwarnnam(nam, "unknown signal: SIG%s", + signame); + returnval++; + } else { + if (WIFSIGNALED(sig)) + sig = WTERMSIG(sig); + else if (WIFSTOPPED(sig)) + sig = WSTOPSIG(sig); + if (1 <= sig && sig <= SIGCOUNT) + printf("%s\n", sigs[sig]); + else + printf("%d\n", sig); + } + } + } + return returnval; + } + printf("%s", sigs[1]); + for (sig = 2; sig <= SIGCOUNT; sig++) + printf(" %s", sigs[sig]); + putchar('\n'); + return 0; + } + + if ((*argv)[1] == 'n' && (*argv)[2] == '\0') { + char *endp; + + if (!*++argv) { + zwarnnam(nam, "-n: argument expected"); + return 1; + } + sig = zstrtol(*argv, &endp, 10); + if (*endp) { + zwarnnam(nam, "invalid signal number: %s", *argv); + return 1; + } + } else { + if (!((*argv)[1] == 's' && (*argv)[2] == '\0')) + signame = *argv + 1; + else if (!(*++argv)) { + zwarnnam(nam, "-s: argument expected"); + return 1; + } else + signame = *argv; + if (!*signame) { + zwarnnam(nam, "-: signal name expected"); + return 1; + } + signame = casemodify(signame, CASMOD_UPPER); + if (!strncmp(signame, "SIG", 3)) + signame+=3; + + /* check for signal matching specified name */ + for (sig = 1; sig <= SIGCOUNT; sig++) + if (!strcmp(*(sigs + sig), signame)) + break; + if (*signame == '0' && !signame[1]) + sig = 0; + if (sig > SIGCOUNT) { + int i; + + for (i = 0; alt_sigs[i].name; i++) + if (!strcmp(alt_sigs[i].name, signame)) + { + sig = alt_sigs[i].num; + break; + } + } + if (sig > SIGCOUNT) { + zwarnnam(nam, "unknown signal: SIG%s", signame); + zwarnnam(nam, "type kill -l for a list of signals"); + return 1; + } + } + } + argv++; + } + + /* Discard the standard "-" and "--" option breaks */ + if (*argv && (*argv)[0] == '-' && (!(*argv)[1] || (*argv)[1] == '-')) + argv++; + + if (!*argv) { + zwarnnam(nam, "not enough arguments"); + return 1; + } + + queue_signals(); + setcurjob(); + + /* Remaining arguments specify processes. Loop over them, and send the + signal (number sig) to each process. */ + for (; *argv; argv++) { + if (**argv == '%') { + /* job specifier introduced by '%' */ + int p; + + if ((p = getjob(*argv, nam)) == -1) { + returnval++; + continue; + } + if (killjb(jobtab + p, sig) == -1) { + zwarnnam("kill", "kill %s failed: %e", *argv, errno); + returnval++; + continue; + } + /* automatically update the job table if sending a SIGCONT to a + job, and send the job a SIGCONT if sending it a non-stopping + signal. */ + if (jobtab[p].stat & STAT_STOPPED) { +#ifndef WIFCONTINUED + /* With WIFCONTINUED we find this out properly */ + if (sig == SIGCONT) + makerunning(jobtab + p); +#endif + if (sig != SIGKILL && sig != SIGCONT && sig != SIGTSTP + && sig != SIGTTOU && sig != SIGTTIN && sig != SIGSTOP) + killjb(jobtab + p, SIGCONT); + } + } else if (!isanum(*argv)) { + zwarnnam("kill", "illegal pid: %s", *argv); + returnval++; + } else { + int pid = atoi(*argv); + if (kill(pid, sig) == -1) { + zwarnnam("kill", "kill %s failed: %e", *argv, errno); + returnval++; + } +#ifndef WIFCONTINUED + else if (sig == SIGCONT) { + Job jn; + Process pn; + /* With WIFCONTINUED we find this out properly */ + if (findproc(pid, &jn, &pn, 0)) { + if (WIFSTOPPED(pn->status)) + pn->status = SP_RUNNING; + } + } +#endif + } + } + unqueue_signals(); + + return returnval < 126 ? returnval : 1; +} +/* Get a signal number from a string */ + +/**/ +mod_export int +getsignum(const char *s) +{ + int x, i; + + /* check for a signal specified by number */ + x = atoi(s); + if (idigit(*s) && x >= 0 && x < VSIGCOUNT) + return x; + + /* search for signal by name */ + if (!strncmp(s, "SIG", 3)) + s += 3; + + for (i = 0; i < VSIGCOUNT; i++) + if (!strcmp(s, sigs[i])) + return i; + + for (i = 0; alt_sigs[i].name; i++) + { + if (!strcmp(s, alt_sigs[i].name)) + return alt_sigs[i].num; + } + + /* no matching signal */ + return -1; +} + +/* Get the name for a signal. */ + +/**/ +mod_export const char * +getsigname(int sig) +{ + if (sigtrapped[sig] & ZSIG_ALIAS) + { + int i; + for (i = 0; alt_sigs[i].name; i++) + if (sig == alt_sigs[i].num) + return alt_sigs[i].name; + } + else + return sigs[sig]; + + /* shouldn't reach here */ +#ifdef DEBUG + dputs("Bad alias flag for signal"); +#endif + return ""; +} + + +/* Get the function node for a trap, taking care about alternative names */ +/**/ +HashNode +gettrapnode(int sig, int ignoredisable) +{ + char fname[20]; + HashNode hn; + HashNode (*getptr)(HashTable ht, const char *name); + int i; + if (ignoredisable) + getptr = shfunctab->getnode2; + else + getptr = shfunctab->getnode; + + sprintf(fname, "TRAP%s", sigs[sig]); + if ((hn = getptr(shfunctab, fname))) + return hn; + + for (i = 0; alt_sigs[i].name; i++) { + if (alt_sigs[i].num == sig) { + sprintf(fname, "TRAP%s", alt_sigs[i].name); + if ((hn = getptr(shfunctab, fname))) + return hn; + } + } + + return NULL; +} + +/* Remove a TRAP function under any name for the signal */ + +/**/ +void +removetrapnode(int sig) +{ + HashNode hn = gettrapnode(sig, 1); + if (hn) { + shfunctab->removenode(shfunctab, hn->nam); + shfunctab->freenode(hn); + } +} + +/* Suspend this shell */ + +/**/ +int +bin_suspend(char *name, UNUSED(char **argv), Options ops, UNUSED(int func)) +{ + /* won't suspend a login shell, unless forced */ + if (islogin && !OPT_ISSET(ops,'f')) { + zwarnnam(name, "can't suspend login shell"); + return 1; + } + if (jobbing) { + /* stop ignoring signals */ + signal_default(SIGTTIN); + signal_default(SIGTSTP); + signal_default(SIGTTOU); + + /* Move ourselves back to the process group we came from */ + release_pgrp(); + } + + /* suspend ourselves with a SIGTSTP */ + killpg(origpgrp, SIGTSTP); + + if (jobbing) { + acquire_pgrp(); + /* restore signal handling */ + signal_ignore(SIGTTOU); + signal_ignore(SIGTSTP); + signal_ignore(SIGTTIN); + } + return 0; +} + +/* find a job named s */ + +/**/ +int +findjobnam(const char *s) +{ + int jobnum; + + for (jobnum = maxjob; jobnum >= 0; jobnum--) + if (!(jobtab[jobnum].stat & (STAT_SUBJOB | STAT_NOPRINT)) && + jobtab[jobnum].stat && jobtab[jobnum].procs && jobnum != thisjob && + jobtab[jobnum].procs->text[0] && strpfx(s, jobtab[jobnum].procs->text)) + return jobnum; + return -1; +} + + +/* make sure we are a process group leader by creating a new process + group if necessary */ + +/**/ +void +acquire_pgrp(void) +{ + long ttpgrp; + sigset_t blockset, oldset; + + if ((mypgrp = GETPGRP()) >= 0) { + long lastpgrp = mypgrp; + sigemptyset(&blockset); + sigaddset(&blockset, SIGTTIN); + sigaddset(&blockset, SIGTTOU); + sigaddset(&blockset, SIGTSTP); + oldset = signal_block(blockset); + while ((ttpgrp = gettygrp()) != -1 && ttpgrp != mypgrp) { + mypgrp = GETPGRP(); + if (mypgrp == mypid) { + if (!interact) + break; /* attachtty() will be a no-op, give up */ + signal_setmask(oldset); + attachtty(mypgrp); /* Might generate SIGT* */ + signal_block(blockset); + } + if (mypgrp == gettygrp()) + break; + signal_setmask(oldset); + if (read(0, NULL, 0) != 0) {} /* Might generate SIGT* */ + signal_block(blockset); + mypgrp = GETPGRP(); + if (mypgrp == lastpgrp && !interact) + break; /* Unlikely that pgrp will ever change */ + lastpgrp = mypgrp; + } + if (mypgrp != mypid) { + if (setpgrp(0, 0) == 0) { + mypgrp = mypid; + attachtty(mypgrp); + } else + opts[MONITOR] = 0; + } + signal_setmask(oldset); + } else + opts[MONITOR] = 0; +} + +/* revert back to the process group we came from (before acquire_pgrp) */ + +/**/ +void +release_pgrp(void) +{ + if (origpgrp != mypgrp) { + /* in linux pid namespaces, origpgrp may never have been set */ + if (origpgrp) { + attachtty(origpgrp); + setpgrp(0, origpgrp); + } + mypgrp = origpgrp; + } +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/lex.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/lex.c new file mode 100644 index 00000000..44ad8804 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/lex.c @@ -0,0 +1,2203 @@ +/* + * lex.c - lexical analysis + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "lex.pro" + +#define LEX_HEAP_SIZE (32) + +/* tokens */ + +/**/ +mod_export char ztokens[] = "#$^*(())$=|{}[]`<>>?~`,-!'\"\\\\"; + +/* parts of the current token */ + +/**/ +char *zshlextext; +/**/ +mod_export char *tokstr; +/**/ +mod_export enum lextok tok; +/**/ +mod_export int tokfd; + +/* + * Line number at which the first character of a token was found. + * We always set this in gettok(), which is always called from + * zshlex() unless we have reached an error. So it is always + * valid when parsing. It is not useful during execution + * of the parsed structure. + */ + +/**/ +zlong toklineno; + +/* lexical analyzer error flag */ + +/**/ +mod_export int lexstop; + +/* if != 0, this is the first line of the command */ + +/**/ +mod_export int isfirstln; + +/* if != 0, this is the first char of the command (not including white space) */ + +/**/ +int isfirstch; + +/* flag that an alias should be expanded after expansion ending in space */ + +/**/ +int inalmore; + +/* + * Don't do spelling correction. + * Bit 1 is only valid for the current word. It's + * set when we detect a lookahead that stops the word from + * needing correction. + */ + +/**/ +int nocorrect; + +/* + * TBD: the following exported variables are part of the non-interface + * with ZLE for completion. They are poorly named and the whole + * scheme is incredibly brittle. One piece of robustness is applied: + * the variables are only set if LEXFLAGS_ZLE is set. Improvements + * should therefore concentrate on areas with this flag set. + * + * Cursor position and line length in zle when the line is + * metafied for access from the main shell. + */ + +/**/ +mod_export int zlemetacs, zlemetall; + +/* inwhat says what exactly we are in * + * (its value is one of the IN_* things). */ + +/**/ +mod_export int inwhat; + +/* 1 if x added to complete in a blank between words */ + +/**/ +mod_export int addedx; + +/* wb and we hold the beginning/end position of the word we are completing. */ + +/**/ +mod_export int wb, we; + +/**/ +mod_export int wordbeg; + +/**/ +mod_export int parbegin; + +/**/ +mod_export int parend; + + +/* 1 if aliases should not be expanded */ + +/**/ +mod_export int noaliases; + +/* + * If non-zero, we are parsing a line sent to use by the editor, or some + * other string that's not part of standard command input (e.g. eval is + * part of normal command input). + * + * Set of bits from LEXFLAGS_*. + * + * Note that although it is passed into the lexer as an input, the + * lexer can set it to zero after finding the word it's searching for. + * This only happens if the line being parsed actually does come from + * ZLE, and hence the bit LEXFLAGS_ZLE is set. + */ + +/**/ +mod_export int lexflags; + +/* don't recognize comments */ + +/**/ +mod_export int nocomments; + +/* add raw input characters while parsing command substitution */ + +/**/ +int lex_add_raw; + +/* variables associated with the above */ + +static char *tokstr_raw; +static struct lexbufstate lexbuf_raw; + +/* text of punctuation tokens */ + +/**/ +mod_export char *tokstrings[WHILE + 1] = { + NULL, /* NULLTOK 0 */ + ";", /* SEPER */ + "\\n", /* NEWLIN */ + ";", /* SEMI */ + ";;", /* DSEMI */ + "&", /* AMPER 5 */ + "(", /* INPAR */ + ")", /* OUTPAR */ + "||", /* DBAR */ + "&&", /* DAMPER */ + ">", /* OUTANG 10 */ + ">|", /* OUTANGBANG */ + ">>", /* DOUTANG */ + ">>|", /* DOUTANGBANG */ + "<", /* INANG */ + "<>", /* INOUTANG 15 */ + "<<", /* DINANG */ + "<<-", /* DINANGDASH */ + "<&", /* INANGAMP */ + ">&", /* OUTANGAMP */ + "&>", /* AMPOUTANG 20 */ + "&>|", /* OUTANGAMPBANG */ + ">>&", /* DOUTANGAMP */ + ">>&|", /* DOUTANGAMPBANG */ + "<<<", /* TRINANG */ + "|", /* BAR 25 */ + "|&", /* BARAMP */ + "()", /* INOUTPAR */ + "((", /* DINPAR */ + "))", /* DOUTPAR */ + "&|", /* AMPERBANG 30 */ + ";&", /* SEMIAMP */ + ";|", /* SEMIBAR */ +}; + +/* lexical state */ + +static int dbparens; +static struct lexbufstate lexbuf = { NULL, 256, 0 }; + +/* save lexical context */ + +/**/ +void +lex_context_save(struct lex_stack *ls, int toplevel) +{ + (void)toplevel; + + ls->dbparens = dbparens; + ls->isfirstln = isfirstln; + ls->isfirstch = isfirstch; + ls->lexflags = lexflags; + + ls->tok = tok; + ls->tokstr = tokstr; + ls->zshlextext = zshlextext; + ls->lexbuf = lexbuf; + ls->lex_add_raw = lex_add_raw; + ls->tokstr_raw = tokstr_raw; + ls->lexbuf_raw = lexbuf_raw; + ls->lexstop = lexstop; + ls->toklineno = toklineno; + + tokstr = zshlextext = lexbuf.ptr = NULL; + lexbuf.siz = 256; + tokstr_raw = lexbuf_raw.ptr = NULL; + lexbuf_raw.siz = lexbuf_raw.len = lex_add_raw = 0; +} + +/* restore lexical context */ + +/**/ +mod_export void +lex_context_restore(const struct lex_stack *ls, int toplevel) +{ + (void)toplevel; + + dbparens = ls->dbparens; + isfirstln = ls->isfirstln; + isfirstch = ls->isfirstch; + lexflags = ls->lexflags; + tok = ls->tok; + tokstr = ls->tokstr; + zshlextext = ls->zshlextext; + lexbuf = ls->lexbuf; + lex_add_raw = ls->lex_add_raw; + tokstr_raw = ls->tokstr_raw; + lexbuf_raw = ls->lexbuf_raw; + lexstop = ls->lexstop; + toklineno = ls->toklineno; +} + +/**/ +void +zshlex(void) +{ + if (tok == LEXERR) + return; + do { + if (inrepeat_) + ++inrepeat_; + if (inrepeat_ == 3 && isset(SHORTLOOPS)) + incmdpos = 1; + tok = gettok(); + } while (tok != ENDINPUT && exalias()); + nocorrect &= 1; + if (tok == NEWLIN || tok == ENDINPUT) { + while (hdocs) { + struct heredocs *next = hdocs->next; + char *doc, *munged_term; + + hwbegin(0); + cmdpush(hdocs->type == REDIR_HEREDOC ? CS_HEREDOC : CS_HEREDOCD); + munged_term = dupstring(hdocs->str); + STOPHIST + doc = gethere(&munged_term, hdocs->type); + ALLOWHIST + cmdpop(); + hwend(); + if (!doc) { + zerr("here document too large"); + while (hdocs) { + next = hdocs->next; + zfree(hdocs, sizeof(struct heredocs)); + hdocs = next; + } + tok = LEXERR; + break; + } + setheredoc(hdocs->pc, REDIR_HERESTR, doc, hdocs->str, + munged_term); + zfree(hdocs, sizeof(struct heredocs)); + hdocs = next; + } + } + if (tok != NEWLIN) + isnewlin = 0; + else + isnewlin = (inbufct) ? -1 : 1; + if (tok == SEMI || (tok == NEWLIN && !(lexflags & LEXFLAGS_NEWLINE))) + tok = SEPER; +} + +/**/ +mod_export void +ctxtlex(void) +{ + static int oldpos; + + zshlex(); + switch (tok) { + case SEPER: + case NEWLIN: + case SEMI: + case DSEMI: + case SEMIAMP: + case SEMIBAR: + case AMPER: + case AMPERBANG: + case INPAR: + case INBRACE: + case DBAR: + case DAMPER: + case BAR: + case BARAMP: + case INOUTPAR: + case DOLOOP: + case THEN: + case ELIF: + case ELSE: + case DOUTBRACK: + incmdpos = 1; + break; + case STRING: + case TYPESET: + /* case ENVSTRING: */ + case ENVARRAY: + case OUTPAR: + case CASE: + case DINBRACK: + incmdpos = 0; + break; + + default: + /* nothing to do, keep compiler happy */ + break; + } + if (tok != DINPAR) + infor = tok == FOR ? 2 : 0; + if (IS_REDIROP(tok) || tok == FOR || tok == FOREACH || tok == SELECT) { + inredir = 1; + oldpos = incmdpos; + incmdpos = 0; + } else if (inredir) { + incmdpos = oldpos; + inredir = 0; + } +} + +#define LX1_BKSLASH 0 +#define LX1_COMMENT 1 +#define LX1_NEWLIN 2 +#define LX1_SEMI 3 +#define LX1_AMPER 5 +#define LX1_BAR 6 +#define LX1_INPAR 7 +#define LX1_OUTPAR 8 +#define LX1_INANG 13 +#define LX1_OUTANG 14 +#define LX1_OTHER 15 + +#define LX2_BREAK 0 +#define LX2_OUTPAR 1 +#define LX2_BAR 2 +#define LX2_STRING 3 +#define LX2_INBRACK 4 +#define LX2_OUTBRACK 5 +#define LX2_TILDE 6 +#define LX2_INPAR 7 +#define LX2_INBRACE 8 +#define LX2_OUTBRACE 9 +#define LX2_OUTANG 10 +#define LX2_INANG 11 +#define LX2_EQUALS 12 +#define LX2_BKSLASH 13 +#define LX2_QUOTE 14 +#define LX2_DQUOTE 15 +#define LX2_BQUOTE 16 +#define LX2_COMMA 17 +#define LX2_DASH 18 +#define LX2_BANG 19 +#define LX2_OTHER 20 +#define LX2_META 21 + +static unsigned char lexact1[256], lexact2[256], lextok2[256]; + +/**/ +void +initlextabs(void) +{ + int t0; + static char *lx1 = "\\q\n;!&|(){}[]<>"; + static char *lx2 = ";)|$[]~({}><=\\\'\"`,-!"; + + for (t0 = 0; t0 != 256; t0++) { + lexact1[t0] = LX1_OTHER; + lexact2[t0] = LX2_OTHER; + lextok2[t0] = t0; + } + for (t0 = 0; lx1[t0]; t0++) + lexact1[(int)lx1[t0]] = t0; + for (t0 = 0; lx2[t0]; t0++) + lexact2[(int)lx2[t0]] = t0; + lexact2['&'] = LX2_BREAK; + lexact2[STOUC(Meta)] = LX2_META; + lextok2['*'] = Star; + lextok2['?'] = Quest; + lextok2['{'] = Inbrace; + lextok2['['] = Inbrack; + lextok2['$'] = String; + lextok2['~'] = Tilde; + lextok2['#'] = Pound; + lextok2['^'] = Hat; +} + +/* initialize lexical state */ + +/**/ +void +lexinit(void) +{ + nocorrect = dbparens = lexstop = 0; + tok = ENDINPUT; +} + +/* add a char to the string buffer */ + +/**/ +void +add(int c) +{ + *lexbuf.ptr++ = c; + if (lexbuf.siz == ++lexbuf.len) { + int newbsiz = lexbuf.siz * 2; + + if (newbsiz > inbufct && inbufct > lexbuf.siz) + newbsiz = inbufct; + + tokstr = (char *)hrealloc(tokstr, lexbuf.siz, newbsiz); + lexbuf.ptr = tokstr + lexbuf.len; + /* len == bsiz, so bptr is at the start of newly allocated memory */ + memset(lexbuf.ptr, 0, newbsiz - lexbuf.siz); + lexbuf.siz = newbsiz; + } +} + +#define SETPARBEGIN { \ + if ((lexflags & LEXFLAGS_ZLE) && !(inbufflags & INP_ALIAS) && \ + zlemetacs >= zlemetall+1-inbufct) \ + parbegin = inbufct; \ + } +#define SETPAREND { \ + if ((lexflags & LEXFLAGS_ZLE) && !(inbufflags & INP_ALIAS) && \ + parbegin != -1 && parend == -1) { \ + if (zlemetacs >= zlemetall + 1 - inbufct) \ + parbegin = -1; \ + else \ + parend = inbufct; \ + } \ + } + +enum { + CMD_OR_MATH_CMD, + CMD_OR_MATH_MATH, + CMD_OR_MATH_ERR +}; + +/* + * Return one of the above. If it couldn't be + * parsed as math, but there was no gross error, it's a command. + */ + +static int +cmd_or_math(int cs_type) +{ + int oldlen = lexbuf.len; + int c; + int oinflags = inbufflags; + + cmdpush(cs_type); + inbufflags |= INP_APPEND; + c = dquote_parse(')', 0); + if (!(oinflags & INP_APPEND)) + inbufflags &= ~INP_APPEND; + cmdpop(); + *lexbuf.ptr = '\0'; + if (!c) { + /* Successfully parsed, see if it was math */ + c = hgetc(); + if (c == ')') + return CMD_OR_MATH_MATH; /* yes */ + hungetc(c); + lexstop = 0; + c = ')'; + } else if (lexstop) { + /* we haven't got anything to unget */ + return CMD_OR_MATH_ERR; + } + /* else unsuccessful: unget the whole thing */ + hungetc(c); + lexstop = 0; + while (lexbuf.len > oldlen && !(errflag & ERRFLAG_ERROR)) { + lexbuf.len--; + hungetc(itok(*--lexbuf.ptr) ? + ztokens[*lexbuf.ptr - Pound] : *lexbuf.ptr); + } + if (errflag) + return CMD_OR_MATH_ERR; + hungetc('('); + return errflag ? CMD_OR_MATH_ERR : CMD_OR_MATH_CMD; +} + + +/* + * Parse either a $(( ... )) or a $(...) + * Return the same as cmd_or_math(). + */ +static int +cmd_or_math_sub(void) +{ + int c = hgetc(), ret; + + if (c == '(') { + int lexpos = (int)(lexbuf.ptr - tokstr); + add(Inpar); + add('('); + if ((ret = cmd_or_math(CS_MATHSUBST)) == CMD_OR_MATH_MATH) { + tokstr[lexpos] = Inparmath; + add(')'); + return CMD_OR_MATH_MATH; + } + if (ret == CMD_OR_MATH_ERR) + return CMD_OR_MATH_ERR; + lexbuf.ptr -= 2; + lexbuf.len -= 2; + } else { + hungetc(c); + lexstop = 0; + } + return skipcomm() ? CMD_OR_MATH_ERR : CMD_OR_MATH_CMD; +} + +/* Check whether we're looking at valid numeric globbing syntax * + * (/\<[0-9]*-[0-9]*\>/). Call pointing just after the opening "<". * + * Leaves the input in the same place, returning 0 or 1. */ + +/**/ +static int +isnumglob(void) +{ + int c, ec = '-', ret = 0; + int tbs = 256, n = 0; + char *tbuf = (char *)zalloc(tbs); + + while(1) { + c = hgetc(); + if(lexstop) { + lexstop = 0; + break; + } + tbuf[n++] = c; + if(!idigit(c)) { + if(c != ec) + break; + if(ec == '>') { + ret = 1; + break; + } + ec = '>'; + } + if(n == tbs) + tbuf = (char *)realloc(tbuf, tbs *= 2); + } + while(n--) + hungetc(tbuf[n]); + zfree(tbuf, tbs); + return ret; +} + +/**/ +static enum lextok +gettok(void) +{ + int c, d; + int peekfd = -1; + enum lextok peek; + + beginning: + tokstr = NULL; + while (iblank(c = hgetc()) && !lexstop); + toklineno = lineno; + if (lexstop) + return (errflag) ? LEXERR : ENDINPUT; + isfirstln = 0; + if ((lexflags & LEXFLAGS_ZLE) && !(inbufflags & INP_ALIAS)) + wordbeg = inbufct - (qbang && c == bangchar); + hwbegin(-1-(qbang && c == bangchar)); + /* word includes the last character read and possibly \ before ! */ + if (dbparens) { + lexbuf.len = 0; + lexbuf.ptr = tokstr = (char *) hcalloc(lexbuf.siz = LEX_HEAP_SIZE); + hungetc(c); + cmdpush(CS_MATH); + c = dquote_parse(infor ? ';' : ')', 0); + cmdpop(); + *lexbuf.ptr = '\0'; + if (!c && infor) { + infor--; + return DINPAR; + } + if (c || (c = hgetc()) != ')') { + hungetc(c); + return LEXERR; + } + dbparens = 0; + return DOUTPAR; + } else if (idigit(c)) { /* handle 1< foo */ + d = hgetc(); + if(d == '&') { + d = hgetc(); + if(d == '>') { + peekfd = c - '0'; + hungetc('>'); + c = '&'; + } else { + hungetc(d); + lexstop = 0; + hungetc('&'); + } + } else if (d == '>' || d == '<') { + peekfd = c - '0'; + c = d; + } else { + hungetc(d); + lexstop = 0; + } + } + + /* chars in initial position in word */ + + /* + * Handle comments. There are some special cases when this + * is not normal command input: lexflags implies we are examining + * a line lexically without it being used for normal command input. + */ + if (c == hashchar && !nocomments && + (isset(INTERACTIVECOMMENTS) || + ((!lexflags || (lexflags & LEXFLAGS_COMMENTS)) && !expanding && + (!interact || unset(SHINSTDIN) || strin)))) { + /* History is handled here to prevent extra * + * newlines being inserted into the history. */ + + if (lexflags & LEXFLAGS_COMMENTS_KEEP) { + lexbuf.len = 0; + lexbuf.ptr = tokstr = + (char *)hcalloc(lexbuf.siz = LEX_HEAP_SIZE); + add(c); + } + hwabort(); + while ((c = ingetc()) != '\n' && !lexstop) { + hwaddc(c); + addtoline(c); + if (lexflags & LEXFLAGS_COMMENTS_KEEP) + add(c); + } + + if (errflag) + peek = LEXERR; + else { + if (lexflags & LEXFLAGS_COMMENTS_KEEP) { + *lexbuf.ptr = '\0'; + if (!lexstop) + hungetc(c); + peek = STRING; + } else { + hwend(); + hwbegin(0); + hwaddc('\n'); + addtoline('\n'); + /* + * If splitting a line and removing comments, + * we don't want a newline token since it's + * treated specially. + */ + if ((lexflags & LEXFLAGS_COMMENTS_STRIP) && lexstop) + peek = ENDINPUT; + else + peek = NEWLIN; + } + } + return peek; + } + switch (lexact1[STOUC(c)]) { + case LX1_BKSLASH: + d = hgetc(); + if (d == '\n') + goto beginning; + hungetc(d); + lexstop = 0; + break; + case LX1_NEWLIN: + return NEWLIN; + case LX1_SEMI: + d = hgetc(); + if(d == ';') + return DSEMI; + else if(d == '&') + return SEMIAMP; + else if (d == '|') + return SEMIBAR; + hungetc(d); + lexstop = 0; + return SEMI; + case LX1_AMPER: + d = hgetc(); + if (d == '&') + return DAMPER; + else if (d == '!' || d == '|') + return AMPERBANG; + else if (d == '>') { + tokfd = peekfd; + d = hgetc(); + if (d == '!' || d == '|') + return OUTANGAMPBANG; + else if (d == '>') { + d = hgetc(); + if (d == '!' || d == '|') + return DOUTANGAMPBANG; + hungetc(d); + lexstop = 0; + return DOUTANGAMP; + } + hungetc(d); + lexstop = 0; + return AMPOUTANG; + } + hungetc(d); + lexstop = 0; + return AMPER; + case LX1_BAR: + d = hgetc(); + if (d == '|' && !incasepat) + return DBAR; + else if (d == '&') + return BARAMP; + hungetc(d); + lexstop = 0; + return BAR; + case LX1_INPAR: + d = hgetc(); + if (d == '(') { + if (infor) { + dbparens = 1; + return DINPAR; + } + if (incmdpos || (isset(SHGLOB) && !isset(KSHGLOB))) { + lexbuf.len = 0; + lexbuf.ptr = tokstr = (char *) + hcalloc(lexbuf.siz = LEX_HEAP_SIZE); + switch (cmd_or_math(CS_MATH)) { + case CMD_OR_MATH_MATH: + return DINPAR; + + case CMD_OR_MATH_CMD: + /* + * Not math, so we don't return the contents + * as a string in this case. + */ + tokstr = NULL; + return INPAR; + + case CMD_OR_MATH_ERR: + /* + * LEXFLAGS_ACTIVE means we came from bufferwords(), + * so we treat as an incomplete math expression + */ + if (lexflags & LEXFLAGS_ACTIVE) + tokstr = dyncat("((", tokstr ? tokstr : ""); + /* fall through */ + + default: + return LEXERR; + } + } + } else if (d == ')') + return INOUTPAR; + hungetc(d); + lexstop = 0; + if (!(isset(SHGLOB) || incond == 1 || incmdpos)) + break; + return INPAR; + case LX1_OUTPAR: + return OUTPAR; + case LX1_INANG: + d = hgetc(); + if (d == '(') { + hungetc(d); + lexstop = 0; + unpeekfd: + if(peekfd != -1) { + hungetc(c); + c = '0' + peekfd; + } + break; + } + if (d == '>') { + peek = INOUTANG; + } else if (d == '<') { + int e = hgetc(); + + if (e == '(') { + hungetc(e); + hungetc(d); + peek = INANG; + } else if (e == '<') + peek = TRINANG; + else if (e == '-') + peek = DINANGDASH; + else { + hungetc(e); + lexstop = 0; + peek = DINANG; + } + } else if (d == '&') { + peek = INANGAMP; + } else { + hungetc(d); + if(isnumglob()) + goto unpeekfd; + peek = INANG; + } + tokfd = peekfd; + return peek; + case LX1_OUTANG: + d = hgetc(); + if (d == '(') { + hungetc(d); + goto unpeekfd; + } else if (d == '&') { + d = hgetc(); + if (d == '!' || d == '|') + peek = OUTANGAMPBANG; + else { + hungetc(d); + lexstop = 0; + peek = OUTANGAMP; + } + } else if (d == '!' || d == '|') + peek = OUTANGBANG; + else if (d == '>') { + d = hgetc(); + if (d == '&') { + d = hgetc(); + if (d == '!' || d == '|') + peek = DOUTANGAMPBANG; + else { + hungetc(d); + lexstop = 0; + peek = DOUTANGAMP; + } + } else if (d == '!' || d == '|') + peek = DOUTANGBANG; + else if (d == '(') { + hungetc(d); + hungetc('>'); + peek = OUTANG; + } else { + hungetc(d); + lexstop = 0; + peek = DOUTANG; + if (isset(HISTALLOWCLOBBER)) + hwaddc('|'); + } + } else { + hungetc(d); + lexstop = 0; + peek = OUTANG; + if (!incond && isset(HISTALLOWCLOBBER)) + hwaddc('|'); + } + tokfd = peekfd; + return peek; + } + + /* we've started a string, now get the * + * rest of it, performing tokenization */ + return gettokstr(c, 0); +} + +/* + * Get the remains of a token string. This has two uses. + * When called from gettok(), with sub = 0, we have already identified + * any interesting initial character and want to get the rest of + * what we now know is a string. However, the string may still include + * metacharacters and potentially substitutions. + * + * When called from parse_subst_string() with sub = 1, we are not + * fully parsing a command line, merely tokenizing a string. + * In this case we always add characters to the parsed string + * unless there is a parse error. + */ + +/**/ +static enum lextok +gettokstr(int c, int sub) +{ + int bct = 0, pct = 0, brct = 0, seen_brct = 0, fdpar = 0; + int intpos = 1, in_brace_param = 0; + int inquote, unmatched = 0; + enum lextok peek; +#ifdef DEBUG + int ocmdsp = cmdsp; +#endif + + peek = STRING; + if (!sub) { + lexbuf.len = 0; + lexbuf.ptr = tokstr = (char *) hcalloc(lexbuf.siz = LEX_HEAP_SIZE); + } + for (;;) { + int act; + int e; + int inbl = inblank(c); + + if (fdpar && !inbl && c != ')') + fdpar = 0; + + if (inbl && !in_brace_param && !pct) + act = LX2_BREAK; + else { + act = lexact2[STOUC(c)]; + c = lextok2[STOUC(c)]; + } + switch (act) { + case LX2_BREAK: + if (!in_brace_param && !sub) + goto brk; + break; + case LX2_META: + c = hgetc(); +#ifdef DEBUG + if (lexstop) { + fputs("BUG: input terminated by Meta\n", stderr); + fflush(stderr); + goto brk; + } +#endif + add(Meta); + break; + case LX2_OUTPAR: + if (fdpar) { + /* this is a single word `( )', treat as INOUTPAR */ + add(c); + *lexbuf.ptr = '\0'; + return INOUTPAR; + } + if ((sub || in_brace_param) && isset(SHGLOB)) + break; + if (!in_brace_param && !pct--) { + if (sub) { + pct = 0; + break; + } else + goto brk; + } + c = Outpar; + break; + case LX2_BAR: + if (!pct && !in_brace_param) { + if (sub) + break; + else + goto brk; + } + if (unset(SHGLOB) || (!sub && !in_brace_param)) + c = Bar; + break; + case LX2_STRING: + e = hgetc(); + if (e == '[') { + cmdpush(CS_MATHSUBST); + add(String); + add(Inbrack); + c = dquote_parse(']', sub); + cmdpop(); + if (c) { + peek = LEXERR; + goto brk; + } + c = Outbrack; + } else if (e == '(') { + add(String); + switch (cmd_or_math_sub()) { + case CMD_OR_MATH_CMD: + c = Outpar; + break; + + case CMD_OR_MATH_MATH: + c = Outparmath; + break; + + default: + peek = LEXERR; + goto brk; + } + } else { + if (e == '{') { + add(c); + c = Inbrace; + ++bct; + cmdpush(CS_BRACEPAR); + if (!in_brace_param) { + if ((in_brace_param = bct)) + seen_brct = 0; + } + } else { + hungetc(e); + lexstop = 0; + } + } + break; + case LX2_INBRACK: + if (!in_brace_param) { + brct++; + seen_brct = 1; + } + c = Inbrack; + break; + case LX2_OUTBRACK: + if (!in_brace_param) + brct--; + if (brct < 0) + brct = 0; + c = Outbrack; + break; + case LX2_INPAR: + if (isset(SHGLOB)) { + if (sub || in_brace_param) + break; + if (incasepat > 0 && !lexbuf.len) + return INPAR; + if (!isset(KSHGLOB) && lexbuf.len) + goto brk; + } + if (!in_brace_param) { + if (!sub) { + e = hgetc(); + hungetc(e); + lexstop = 0; + /* For command words, parentheses are only + * special at the start. But now we're tokenising + * the remaining string. So I don't see what + * the old incmdpos test here is for. + * pws 1999/6/8 + * + * Oh, no. + * func1( ) + * is a valid function definition in [k]sh. The best + * thing we can do, without really nasty lookahead tricks, + * is break if we find a blank after a parenthesis. At + * least this can't happen inside braces or brackets. We + * only allow this with SHGLOB (set for both sh and ksh). + * + * Things like `print @( |foo)' should still + * work, because [k]sh don't allow multiple words + * in a function definition, so we only do this + * in command position. + * pws 1999/6/14 + */ + if (e == ')' || (isset(SHGLOB) && inblank(e) && !bct && + !brct && !intpos && incmdpos)) { + /* + * Either a () token, or a command word with + * something suspiciously like a ksh function + * definition. + * The current word isn't spellcheckable. + */ + nocorrect |= 2; + goto brk; + } + } + /* + * This also handles the [k]sh `foo( )' function definition. + * Maintain a variable fdpar, set as long as a single set of + * parentheses contains only space. Then if we get to the + * closing parenthesis and it is still set, we can assume we + * have a function definition. Only do this at the start of + * the word, since the (...) must be a separate token. + */ + if (!pct++ && isset(SHGLOB) && intpos && !bct && !brct) + fdpar = 1; + } + c = Inpar; + break; + case LX2_INBRACE: + if (isset(IGNOREBRACES) || sub) + c = '{'; + else { + if (!lexbuf.len && incmdpos) { + add('{'); + *lexbuf.ptr = '\0'; + return STRING; + } + if (in_brace_param) { + cmdpush(CS_BRACE); + } + bct++; + } + break; + case LX2_OUTBRACE: + if ((isset(IGNOREBRACES) || sub) && !in_brace_param) + break; + if (!bct) + break; + if (in_brace_param) { + cmdpop(); + } + if (bct-- == in_brace_param) + in_brace_param = 0; + c = Outbrace; + break; + case LX2_COMMA: + if (unset(IGNOREBRACES) && !sub && bct > in_brace_param) + c = Comma; + break; + case LX2_OUTANG: + if (in_brace_param || sub) + break; + e = hgetc(); + if (e != '(') { + hungetc(e); + lexstop = 0; + goto brk; + } + add(OutangProc); + if (skipcomm()) { + peek = LEXERR; + goto brk; + } + c = Outpar; + break; + case LX2_INANG: + if (isset(SHGLOB) && sub) + break; + e = hgetc(); + if (!(in_brace_param || sub) && e == '(') { + add(Inang); + if (skipcomm()) { + peek = LEXERR; + goto brk; + } + c = Outpar; + break; + } + hungetc(e); + if(isnumglob()) { + add(Inang); + while ((c = hgetc()) != '>') + add(c); + c = Outang; + break; + } + lexstop = 0; + if (in_brace_param || sub) + break; + goto brk; + case LX2_EQUALS: + if (!sub) { + if (intpos) { + e = hgetc(); + if (e != '(') { + hungetc(e); + lexstop = 0; + c = Equals; + } else { + add(Equals); + if (skipcomm()) { + peek = LEXERR; + goto brk; + } + c = Outpar; + } + } else if (peek != ENVSTRING && + (incmdpos || intypeset) && !bct && !brct) { + char *t = tokstr; + if (idigit(*t)) + while (++t < lexbuf.ptr && idigit(*t)); + else { + int sav = *lexbuf.ptr; + *lexbuf.ptr = '\0'; + t = itype_end(t, IIDENT, 0); + if (t < lexbuf.ptr) { + skipparens(Inbrack, Outbrack, &t); + } else { + *lexbuf.ptr = sav; + } + } + if (*t == '+') + t++; + if (t == lexbuf.ptr) { + e = hgetc(); + if (e == '(') { + *lexbuf.ptr = '\0'; + return ENVARRAY; + } + hungetc(e); + lexstop = 0; + peek = ENVSTRING; + intpos = 2; + } else + c = Equals; + } else + c = Equals; + } + break; + case LX2_BKSLASH: + c = hgetc(); + if (c == '\n') { + c = hgetc(); + if (!lexstop) + continue; + } else { + add(Bnull); + if (c == STOUC(Meta)) { + c = hgetc(); +#ifdef DEBUG + if (lexstop) { + fputs("BUG: input terminated by Meta\n", stderr); + fflush(stderr); + goto brk; + } +#endif + add(Meta); + } + } + if (lexstop) + goto brk; + break; + case LX2_QUOTE: { + int strquote = (lexbuf.len && lexbuf.ptr[-1] == String); + + add(Snull); + cmdpush(CS_QUOTE); + for (;;) { + STOPHIST + while ((c = hgetc()) != '\'' && !lexstop) { + if (strquote && c == '\\') { + c = hgetc(); + if (lexstop) + break; + /* + * Mostly we don't need to do anything special + * with escape backslashes or closing quotes + * inside $'...'; however in completion we + * need to be able to strip multiple backslashes + * neatly. + */ + if (c == '\\' || c == '\'') + add(Bnull); + else + add('\\'); + } else if (!sub && isset(CSHJUNKIEQUOTES) && c == '\n') { + if (lexbuf.ptr[-1] == '\\') + lexbuf.ptr--, lexbuf.len--; + else + break; + } + add(c); + } + ALLOWHIST + if (c != '\'') { + unmatched = '\''; + /* Not an error when called from bufferwords() */ + if (!(lexflags & LEXFLAGS_ACTIVE)) + peek = LEXERR; + cmdpop(); + goto brk; + } + e = hgetc(); + if (e != '\'' || unset(RCQUOTES) || strquote) + break; + add(c); + } + cmdpop(); + hungetc(e); + lexstop = 0; + c = Snull; + break; + } + case LX2_DQUOTE: + add(Dnull); + cmdpush(CS_DQUOTE); + c = dquote_parse('"', sub); + cmdpop(); + if (c) { + unmatched = '"'; + /* Not an error when called from bufferwords() */ + if (!(lexflags & LEXFLAGS_ACTIVE)) + peek = LEXERR; + goto brk; + } + c = Dnull; + break; + case LX2_BQUOTE: + add(Tick); + cmdpush(CS_BQUOTE); + SETPARBEGIN + inquote = 0; + while ((c = hgetc()) != '`' && !lexstop) { + if (c == '\\') { + c = hgetc(); + if (c != '\n') { + add(c == '`' || c == '\\' || c == '$' ? Bnull : '\\'); + add(c); + } + else if (!sub && isset(CSHJUNKIEQUOTES)) + add(c); + } else { + if (!sub && isset(CSHJUNKIEQUOTES) && c == '\n') { + break; + } + add(c); + if (c == '\'') { + if ((inquote = !inquote)) + STOPHIST + else + ALLOWHIST + } + } + } + if (inquote) + ALLOWHIST + cmdpop(); + if (c != '`') { + unmatched = '`'; + /* Not an error when called from bufferwords() */ + if (!(lexflags & LEXFLAGS_ACTIVE)) + peek = LEXERR; + goto brk; + } + c = Tick; + SETPAREND + break; + case LX2_DASH: + /* + * - shouldn't be treated as a special character unless + * we're in a pattern. Unfortunately, working out for + * sure in complicated expressions whether we're in a + * pattern is tricky. So we'll make it special and + * turn it back any time we don't need it special. + * This is not ideal as it's a lot of work. + */ + c = Dash; + break; + case LX2_BANG: + /* + * Same logic as Dash, for ! to perform negation in range. + */ + if (seen_brct) + c = Bang; + else + c = '!'; + } + add(c); + c = hgetc(); + if (intpos) + intpos--; + if (lexstop) + break; + } + brk: + if (errflag) { + if (in_brace_param) { + while(bct-- >= in_brace_param) + cmdpop(); + } + return LEXERR; + } + hungetc(c); + if (unmatched && !(lexflags & LEXFLAGS_ACTIVE)) + zerr("unmatched %c", unmatched); + if (in_brace_param) { + while(bct-- >= in_brace_param) + cmdpop(); + zerr("closing brace expected"); + } else if (unset(IGNOREBRACES) && !sub && lexbuf.len > 1 && + peek == STRING && lexbuf.ptr[-1] == '}' && + lexbuf.ptr[-2] != Bnull) { + /* hack to get {foo} command syntax work */ + lexbuf.ptr--; + lexbuf.len--; + lexstop = 0; + hungetc('}'); + } + *lexbuf.ptr = '\0'; + DPUTS(cmdsp != ocmdsp, "BUG: gettok: cmdstack changed."); + return peek; +} + + +/* + * Parse input as if in double quotes. + * endchar is the end character to expect. + * sub has got something to do with whether we are doing quoted substitution. + * Return non-zero for error (character to unget), else zero + */ + +/**/ +static int +dquote_parse(char endchar, int sub) +{ + int pct = 0, brct = 0, bct = 0, intick = 0, err = 0; + int c; + int math = endchar == ')' || endchar == ']' || infor; + int zlemath = math && zlemetacs > zlemetall + addedx - inbufct; + + while (((c = hgetc()) != endchar || bct || + (math && ((pct > 0) || (brct > 0))) || + intick) && !lexstop) { + cont: + switch (c) { + case '\\': + c = hgetc(); + if (c != '\n') { + if (c == '$' || c == '\\' || (c == '}' && !intick && bct) || + c == endchar || c == '`' || + (endchar == ']' && (c == '[' || c == ']' || + c == '(' || c == ')' || + c == '{' || c == '}' || + (c == '"' && sub)))) + add(Bnull); + else { + /* lexstop is implicitly handled here */ + add('\\'); + goto cont; + } + } else if (sub || unset(CSHJUNKIEQUOTES) || endchar != '"') + continue; + break; + case '\n': + err = !sub && isset(CSHJUNKIEQUOTES) && endchar == '"'; + break; + case '$': + if (intick) + break; + c = hgetc(); + if (c == '(') { + add(Qstring); + switch (cmd_or_math_sub()) { + case CMD_OR_MATH_CMD: + c = Outpar; + break; + + case CMD_OR_MATH_MATH: + c = Outparmath; + break; + + default: + err = 1; + break; + } + } else if (c == '[') { + add(String); + add(Inbrack); + cmdpush(CS_MATHSUBST); + err = dquote_parse(']', sub); + cmdpop(); + c = Outbrack; + } else if (c == '{') { + add(Qstring); + c = Inbrace; + cmdpush(CS_BRACEPAR); + bct++; + } else if (c == '$') + add(Qstring); + else { + hungetc(c); + lexstop = 0; + c = Qstring; + } + break; + case '}': + if (intick || !bct) + break; + c = Outbrace; + bct--; + cmdpop(); + break; + case '`': + c = Qtick; + if (intick == 2) + ALLOWHIST + if ((intick = !intick)) { + SETPARBEGIN + cmdpush(CS_BQUOTE); + } else { + SETPAREND + cmdpop(); + } + break; + case '\'': + if (!intick) + break; + if (intick == 1) + intick = 2, STOPHIST + else + intick = 1, ALLOWHIST + break; + case '(': + if (!math || !bct) + pct++; + break; + case ')': + if (!math || !bct) + err = (!pct-- && math); + break; + case '[': + if (!math || !bct) + brct++; + break; + case ']': + if (!math || !bct) + err = (!brct-- && math); + break; + case '"': + if (intick || (endchar != '"' && !bct)) + break; + if (bct) { + add(Dnull); + cmdpush(CS_DQUOTE); + err = dquote_parse('"', sub); + cmdpop(); + c = Dnull; + } else + err = 1; + break; + } + if (err || lexstop) + break; + add(c); + } + if (intick == 2) + ALLOWHIST + if (intick) { + cmdpop(); + } + while (bct--) + cmdpop(); + if (lexstop) + err = intick || endchar || err; + else if (err == 1) { + /* + * TODO: as far as I can see, this hack is used in gettokstr() + * to hungetc() a character on an error. However, I don't + * understand what that actually gets us, and we can't guarantee + * it's a character anyway, because of the previous test. + * + * We use the same feature in cmd_or_math where we actually do + * need to unget if we decide it's really a command substitution. + * We try to handle the other case by testing for lexstop. + */ + err = c; + } + if (zlemath && zlemetacs <= zlemetall + 1 - inbufct) + inwhat = IN_MATH; + return err; +} + +/* + * Tokenize a string given in s. Parsing is done as in double + * quotes. This is usually called before singsub(). + * + * parsestr() is noisier, reporting an error if the parse failed. + * + * On entry, *s must point to a string allocated from the stack of + * exactly the right length, i.e. strlen(*s) + 1, as the string + * is used as the lexical token string whose memory management + * demands this. Usually the input string will therefore be + * the result of an immediately preceding dupstring(). + */ + +/**/ +mod_export int +parsestr(char **s) +{ + int err; + + if ((err = parsestrnoerr(s))) { + untokenize(*s); + if (!(errflag & ERRFLAG_INT)) { + if (err > 32 && err < 127) + zerr("parse error near `%c'", err); + else + zerr("parse error"); + } + } + return err; +} + +/**/ +mod_export int +parsestrnoerr(char **s) +{ + int l = strlen(*s), err; + + zcontext_save(); + untokenize(*s); + inpush(dupstring(*s), 0, NULL); + strinbeg(0); + lexbuf.len = 0; + lexbuf.ptr = tokstr = *s; + lexbuf.siz = l + 1; + err = dquote_parse('\0', 1); + if (tokstr) + *s = tokstr; + *lexbuf.ptr = '\0'; + strinend(); + inpop(); + DPUTS(cmdsp, "BUG: parsestr: cmdstack not empty."); + zcontext_restore(); + return err; +} + +/* + * Parse a subscript in string s. + * sub is passed down to dquote_parse(). + * endchar is the final character. + * Return the next character, or NULL. + */ +/**/ +mod_export char * +parse_subscript(char *s, int sub, int endchar) +{ + int l = strlen(s), err, toklen; + char *t; + + if (!*s || *s == endchar) + return 0; + zcontext_save(); + untokenize(t = dupstring(s)); + inpush(t, 0, NULL); + strinbeg(0); + /* + * Warning to Future Generations: + * + * This way of passing the subscript through the lexer is brittle. + * Code above this for several layers assumes that when we tokenise + * the input it goes into the same place as the original string. + * However, the lexer may overwrite later bits of the string or + * reallocate it, in particular when expanding aliaes. To get + * around this, we copy the string and then copy it back. This is a + * bit more robust but still relies on the underlying assumption of + * length preservation. + */ + lexbuf.len = 0; + lexbuf.ptr = tokstr = dupstring(s); + lexbuf.siz = l + 1; + err = dquote_parse(endchar, sub); + toklen = (int)(lexbuf.ptr - tokstr); + DPUTS(toklen > l, "Bad length for parsed subscript"); + memcpy(s, tokstr, toklen); + if (err) { + char *strend = s + toklen; + err = *strend; + *strend = '\0'; + untokenize(s); + *strend = err; + s = NULL; + } else { + s += toklen; + } + strinend(); + inpop(); + DPUTS(cmdsp, "BUG: parse_subscript: cmdstack not empty."); + zcontext_restore(); + return s; +} + +/* Tokenize a string given in s. Parsing is done as if s were a normal * + * command-line argument but it may contain separators. This is used * + * to parse the right-hand side of ${...%...} substitutions. */ + +/**/ +mod_export int +parse_subst_string(char *s) +{ + int c, l = strlen(s), err; + char *ptr; + enum lextok ctok; + + if (!*s || !strcmp(s, nulstring)) + return 0; + zcontext_save(); + untokenize(s); + inpush(dupstring(s), 0, NULL); + strinbeg(0); + lexbuf.len = 0; + lexbuf.ptr = tokstr = s; + lexbuf.siz = l + 1; + c = hgetc(); + ctok = gettokstr(c, 1); + err = errflag; + strinend(); + inpop(); + DPUTS(cmdsp, "BUG: parse_subst_string: cmdstack not empty."); + zcontext_restore(); + /* Keep any interrupt error status */ + errflag = err | (errflag & ERRFLAG_INT); + if (ctok == LEXERR) { + untokenize(s); + return 1; + } +#ifdef DEBUG + /* + * Historical note: we used to check here for olen (the value of lexbuf.len + * before zcontext_restore()) == l, but that's not necessarily the case if + * we stripped an RCQUOTE. + */ + if (ctok != STRING || (errflag && !noerrs)) { + fprintf(stderr, "Oops. Bug in parse_subst_string: %s\n", + errflag ? "errflag" : "ctok != STRING"); + fflush(stderr); + untokenize(s); + return 1; + } +#endif + /* Check for $'...' quoting. This needs special handling. */ + for (ptr = s; *ptr; ) + { + if (*ptr == String && ptr[1] == Snull) + { + char *t; + int len, tlen, diff; + t = getkeystring(ptr + 2, &len, GETKEYS_DOLLARS_QUOTE, NULL); + len += 2; + tlen = strlen(t); + diff = len - tlen; + /* + * Yuk. + * parse_subst_string() currently handles strings in-place. + * That's not so easy to fix without knowing whether + * additional memory should come off the heap or + * otherwise. So we cheat by copying the unquoted string + * into place, unless it's too long. That's not the + * normal case, but I'm worried there are pathological + * cases with converting metafied multibyte strings. + * If someone can prove there aren't I will be very happy. + */ + if (diff < 0) { + DPUTS(1, "$'...' subst too long: fix get_parse_string()"); + return 1; + } + memcpy(ptr, t, tlen); + ptr += tlen; + if (diff > 0) { + char *dptr = ptr; + char *sptr = ptr + diff; + while ((*dptr++ = *sptr++)) + ; + } + } else + ptr++; + } + return 0; +} + +/* Called below to report word positions. */ + +/**/ +static void +gotword(void) +{ + int nwe = zlemetall + 1 - inbufct + (addedx == 2 ? 1 : 0); + if (zlemetacs <= nwe) { + int nwb = zlemetall - wordbeg + addedx; + if (zlemetacs >= nwb) { + wb = nwb; + we = nwe; + } else { + wb = zlemetacs + addedx; + if (we < wb) + we = wb; + } + lexflags = 0; + } +} + +/* Check if current lex text matches an alias: 1 if so, else 0 */ + +static int +checkalias(void) +{ + Alias an; + + if (!zshlextext) + return 0; + + if (!noaliases && isset(ALIASESOPT) && + (!isset(POSIXALIASES) || + (tok == STRING && !reswdtab->getnode(reswdtab, zshlextext)))) { + char *suf; + + an = (Alias) aliastab->getnode(aliastab, zshlextext); + if (an && !an->inuse && + ((an->node.flags & ALIAS_GLOBAL) || + (incmdpos && tok == STRING) || inalmore)) { + if (!lexstop) { + /* + * Tokens that don't require a space after, get one, + * because they are treated as if preceded by one. + */ + int c = hgetc(); + hungetc(c); + if (!iblank(c)) + inpush(" ", INP_ALIAS, 0); + } + inpush(an->text, INP_ALIAS, an); + if (an->text[0] == ' ' && !(an->node.flags & ALIAS_GLOBAL)) + aliasspaceflag = 1; + lexstop = 0; + return 1; + } + if ((suf = strrchr(zshlextext, '.')) && suf[1] && + suf > zshlextext && suf[-1] != Meta && + (an = (Alias)sufaliastab->getnode(sufaliastab, suf+1)) && + !an->inuse && incmdpos) { + inpush(dupstring(zshlextext), INP_ALIAS, an); + inpush(" ", INP_ALIAS, NULL); + inpush(an->text, INP_ALIAS, NULL); + lexstop = 0; + return 1; + } + } + + return 0; +} + +/* expand aliases and reserved words */ + +/**/ +int +exalias(void) +{ + Reswd rw; + + hwend(); + if (interact && isset(SHINSTDIN) && !strin && incasepat <= 0 && + tok == STRING && !nocorrect && !(inbufflags & INP_ALIAS) && + (isset(CORRECTALL) || (isset(CORRECT) && incmdpos))) + spckword(&tokstr, 1, incmdpos, 1); + + if (!tokstr) { + zshlextext = tokstrings[tok]; + + if (tok == NEWLIN) + return 0; + return checkalias(); + } else { + VARARR(char, copy, (strlen(tokstr) + 1)); + + if (has_token(tokstr)) { + char *p, *t; + + zshlextext = p = copy; + for (t = tokstr; + (*p++ = itok(*t) ? ztokens[*t++ - Pound] : *t++);); + } else + zshlextext = tokstr; + + if ((lexflags & LEXFLAGS_ZLE) && !(inbufflags & INP_ALIAS)) { + int zp = lexflags; + + gotword(); + if ((zp & LEXFLAGS_ZLE) && !lexflags) { + if (zshlextext == copy) + zshlextext = tokstr; + return 0; + } + } + + if (tok == STRING) { + /* Check for an alias */ + if ((zshlextext != copy || !isset(POSIXALIASES)) && checkalias()) { + if (zshlextext == copy) + zshlextext = tokstr; + return 1; + } + + /* Then check for a reserved word */ + if ((incmdpos || + (unset(IGNOREBRACES) && unset(IGNORECLOSEBRACES) && + zshlextext[0] == '}' && !zshlextext[1])) && + (rw = (Reswd) reswdtab->getnode(reswdtab, zshlextext))) { + tok = rw->token; + inrepeat_ = (tok == REPEAT); + if (tok == DINBRACK) + incond = 1; + } else if (incond && !strcmp(zshlextext, "]]")) { + tok = DOUTBRACK; + incond = 0; + } else if (incond == 1 && zshlextext[0] == '!' && !zshlextext[1]) + tok = BANG; + } + inalmore = 0; + if (zshlextext == copy) + zshlextext = tokstr; + } + return 0; +} + +/**/ +void +zshlex_raw_add(int c) +{ + if (!lex_add_raw) + return; + + *lexbuf_raw.ptr++ = c; + if (lexbuf_raw.siz == ++lexbuf_raw.len) { + int newbsiz = lexbuf_raw.siz * 2; + + tokstr_raw = (char *)hrealloc(tokstr_raw, lexbuf_raw.siz, newbsiz); + lexbuf_raw.ptr = tokstr_raw + lexbuf_raw.len; + memset(lexbuf_raw.ptr, 0, newbsiz - lexbuf_raw.siz); + lexbuf_raw.siz = newbsiz; + } +} + +/**/ +void +zshlex_raw_back(void) +{ + if (!lex_add_raw) + return; + lexbuf_raw.ptr--; + lexbuf_raw.len--; +} + +/**/ +int +zshlex_raw_mark(int offset) +{ + if (!lex_add_raw) + return 0; + return lexbuf_raw.len + offset; +} + +/**/ +void +zshlex_raw_back_to_mark(int mark) +{ + if (!lex_add_raw) + return; + lexbuf_raw.ptr = tokstr_raw + mark; + lexbuf_raw.len = mark; +} + +/* + * Skip (...) for command-style substitutions: $(...), <(...), >(...) + * + * In order to ensure we don't stop at closing parentheses with + * some other syntactic significance, we'll parse the input until + * we find an unmatched closing parenthesis. However, we'll throw + * away the result of the parsing and just keep the string we've built + * up on the way. + */ + +/**/ +static int +skipcomm(void) +{ +#ifdef ZSH_OLD_SKIPCOMM + int pct = 1, c, start = 1; + + cmdpush(CS_CMDSUBST); + SETPARBEGIN + c = Inpar; + do { + int iswhite; + add(c); + c = hgetc(); + if (itok(c) || lexstop) + break; + iswhite = inblank(c); + switch (c) { + case '(': + pct++; + break; + case ')': + pct--; + break; + case '\\': + add(c); + c = hgetc(); + break; + case '\'': { + int strquote = lexbuf.ptr[-1] == '$'; + add(c); + STOPHIST + while ((c = hgetc()) != '\'' && !lexstop) { + if (c == '\\' && strquote) { + add(c); + c = hgetc(); + } + add(c); + } + ALLOWHIST + break; + } + case '\"': + add(c); + while ((c = hgetc()) != '\"' && !lexstop) + if (c == '\\') { + add(c); + add(hgetc()); + } else + add(c); + break; + case '`': + add(c); + while ((c = hgetc()) != '`' && !lexstop) + if (c == '\\') + add(c), add(hgetc()); + else + add(c); + break; + case '#': + if (start) { + add(c); + while ((c = hgetc()) != '\n' && !lexstop) + add(c); + iswhite = 1; + } + break; + } + start = iswhite; + } + while (pct); + if (!lexstop) + SETPAREND + cmdpop(); + return lexstop; +#else + char *new_tokstr; + int new_lexstop, new_lex_add_raw; + int save_infor = infor; + struct lexbufstate new_lexbuf; + + infor = 0; + cmdpush(CS_CMDSUBST); + SETPARBEGIN + add(Inpar); + + new_lex_add_raw = lex_add_raw + 1; + if (!lex_add_raw) { + /* + * We'll combine the string so far with the input + * read in for the command substitution. To do this + * we'll just propagate the current tokstr etc. as the + * variables used for adding raw input, and + * ensure we swap those for the real tokstr etc. at the end. + * + * However, we need to save and restore the rest of the + * lexical and parse state as we're effectively parsing + * an internal string. Because we're still parsing it from + * the original input source (we have to --- we don't know + * when to stop inputting it otherwise and can't rely on + * the input being recoverable until we've read it) we need + * to keep the same history context. + */ + new_tokstr = tokstr; + new_lexbuf = lexbuf; + + /* + * If we're expanding an alias at this point, we need the whole + * remaining text as part of the string for the command in + * parentheses, so don't backtrack. This is different from the + * usual case where the alias is fully within the command, where + * we want the unexpanded text so that it will be expanded + * again when the command in the parentheses is executed. + * + * I never wanted to be a software engineer, you know. + */ + if (inbufflags & INP_ALIAS) + inbufflags |= INP_RAW_KEEP; + zcontext_save_partial(ZCONTEXT_LEX|ZCONTEXT_PARSE); + hist_in_word(1); + } else { + /* + * Set up for nested command subsitution, however + * we don't actually need the string until we get + * back to the top level and recover the lot. + * The $() body just appears empty. + * + * We do need to propagate the raw variables which would + * otherwise by cleared, though. + */ + new_tokstr = tokstr_raw; + new_lexbuf = lexbuf_raw; + + zcontext_save_partial(ZCONTEXT_LEX|ZCONTEXT_PARSE); + } + tokstr_raw = new_tokstr; + lexbuf_raw = new_lexbuf; + lex_add_raw = new_lex_add_raw; + /* + * Don't do any ZLE specials down here: they're only needed + * when we return the string from the recursive parse. + * (TBD: this probably means we should be initialising lexflags + * more consistently.) + * + * Note that in that case we're still using the ZLE line reading + * function at the history layer --- this is consistent with the + * intention of maintaining the history and input layers across + * the recursive parsing. + * + * Also turn off LEXFLAGS_NEWLINE because this is already skipping + * across the entire construct, and parse_event() needs embedded + * newlines to be "real" when looking for the OUTPAR token. + */ + lexflags &= ~(LEXFLAGS_ZLE|LEXFLAGS_NEWLINE); + dbparens = 0; /* restored by zcontext_restore_partial() */ + + if (!parse_event(OUTPAR) || tok != OUTPAR) { + if (strin) { + /* + * Get the rest of the string raw since we don't + * know where this token ends. + */ + while (!lexstop) + (void)ingetc(); + } else + lexstop = 1; + } + /* Outpar lexical token gets added in caller if present */ + + /* + * We're going to keep the full raw input string + * as the current token string after popping the stack. + */ + new_tokstr = tokstr_raw; + new_lexbuf = lexbuf_raw; + /* + * We're also going to propagate the lexical state: + * if we couldn't parse the command substitution we + * can't continue. + */ + new_lexstop = lexstop; + + zcontext_restore_partial(ZCONTEXT_LEX|ZCONTEXT_PARSE); + + if (lex_add_raw) { + /* + * Keep going, so retain the raw variables. + */ + tokstr_raw = new_tokstr; + lexbuf_raw = new_lexbuf; + } else { + if (!new_lexstop) { + /* Ignore the ')' added on input */ + new_lexbuf.len--; + *--new_lexbuf.ptr = '\0'; + } + + /* + * Convince the rest of lex.c we were examining a string + * all along. + */ + tokstr = new_tokstr; + lexbuf = new_lexbuf; + lexstop = new_lexstop; + hist_in_word(0); + } + + if (!lexstop) + SETPAREND + cmdpop(); + infor = save_infor; + + return lexstop; +#endif +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/loop.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/loop.c new file mode 100644 index 00000000..1013aeb5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/loop.c @@ -0,0 +1,795 @@ +/* + * loop.c - loop execution + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "loop.pro" + +/* # of nested loops we are in */ + +/**/ +int loops; + +/* # of continue levels */ + +/**/ +mod_export int contflag; + +/* # of break levels */ + +/**/ +mod_export int breaks; + +/**/ +int +execfor(Estate state, int do_exec) +{ + Wordcode end, loop; + wordcode code = state->pc[-1]; + int iscond = (WC_FOR_TYPE(code) == WC_FOR_COND), ctok = 0, atok = 0; + int last = 0; + char *name, *str, *cond = NULL, *advance = NULL; + zlong val = 0; + LinkList vars = NULL, args = NULL; + int old_simple_pline = simple_pline; + + /* See comments in execwhile() */ + simple_pline = 1; + + end = state->pc + WC_FOR_SKIP(code); + + if (iscond) { + str = dupstring(ecgetstr(state, EC_NODUP, NULL)); + singsub(&str); + if (isset(XTRACE)) { + char *str2 = dupstring(str); + untokenize(str2); + printprompt4(); + fprintf(xtrerr, "%s\n", str2); + fflush(xtrerr); + } + if (!errflag) { + matheval(str); + } + if (errflag) { + state->pc = end; + simple_pline = old_simple_pline; + return 1; + } + cond = ecgetstr(state, EC_NODUP, &ctok); + advance = ecgetstr(state, EC_NODUP, &atok); + } else { + vars = ecgetlist(state, *state->pc++, EC_NODUP, NULL); + + if (WC_FOR_TYPE(code) == WC_FOR_LIST) { + int htok = 0; + + if (!(args = ecgetlist(state, *state->pc++, EC_DUPTOK, &htok))) { + state->pc = end; + simple_pline = old_simple_pline; + return 0; + } + if (htok) { + execsubst(args); + if (errflag) { + state->pc = end; + simple_pline = old_simple_pline; + return 1; + } + } + } else { + char **x; + + args = newlinklist(); + for (x = pparams; *x; x++) + addlinknode(args, dupstring(*x)); + } + } + + if (!args || empty(args)) + lastval = 0; + + loops++; + pushheap(); + cmdpush(CS_FOR); + loop = state->pc; + while (!last) { + if (iscond) { + if (ctok) { + str = dupstring(cond); + singsub(&str); + } else + str = cond; + if (!errflag) { + while (iblank(*str)) + str++; + if (*str) { + if (isset(XTRACE)) { + printprompt4(); + fprintf(xtrerr, "%s\n", str); + fflush(xtrerr); + } + val = mathevali(str); + } else + val = 1; + } + if (errflag) { + if (breaks) + breaks--; + lastval = 1; + break; + } + if (!val) + break; + } else { + LinkNode node; + int count = 0; + for (node = firstnode(vars); node; incnode(node)) + { + name = (char *)getdata(node); + if (!args || !(str = (char *) ugetnode(args))) + { + if (count) { + str = ""; + last = 1; + } else + break; + } + if (isset(XTRACE)) { + printprompt4(); + fprintf(xtrerr, "%s=%s\n", name, str); + fflush(xtrerr); + } + setsparam(name, ztrdup(str)); + count++; + } + if (!count) + break; + } + state->pc = loop; + execlist(state, 1, do_exec && args && empty(args)); + if (breaks) { + breaks--; + if (breaks || !contflag) + break; + contflag = 0; + } + if (retflag) + break; + if (iscond && !errflag) { + if (atok) { + str = dupstring(advance); + singsub(&str); + } else + str = advance; + if (isset(XTRACE)) { + printprompt4(); + fprintf(xtrerr, "%s\n", str); + fflush(xtrerr); + } + if (!errflag) + matheval(str); + } + if (errflag) { + if (breaks) + breaks--; + lastval = 1; + break; + } + freeheap(); + } + popheap(); + cmdpop(); + loops--; + simple_pline = old_simple_pline; + state->pc = end; + this_noerrexit = 1; + return lastval; +} + +/**/ +int +execselect(Estate state, UNUSED(int do_exec)) +{ + Wordcode end, loop; + wordcode code = state->pc[-1]; + char *str, *s, *name; + LinkNode n; + int i, usezle; + FILE *inp; + size_t more; + LinkList args; + int old_simple_pline = simple_pline; + + /* See comments in execwhile() */ + simple_pline = 1; + + end = state->pc + WC_FOR_SKIP(code); + name = ecgetstr(state, EC_NODUP, NULL); + + if (WC_SELECT_TYPE(code) == WC_SELECT_PPARAM) { + char **x; + + args = newlinklist(); + for (x = pparams; *x; x++) + addlinknode(args, dupstring(*x)); + } else { + int htok = 0; + + if (!(args = ecgetlist(state, *state->pc++, EC_DUPTOK, &htok))) { + state->pc = end; + simple_pline = old_simple_pline; + return 0; + } + if (htok) { + execsubst(args); + if (errflag) { + state->pc = end; + simple_pline = old_simple_pline; + return 1; + } + } + } + if (!args || empty(args)) { + state->pc = end; + simple_pline = old_simple_pline; + return 0; + } + loops++; + + pushheap(); + cmdpush(CS_SELECT); + usezle = interact && SHTTY != -1 && isset(USEZLE); + inp = fdopen(dup(usezle ? SHTTY : 0), "r"); + more = selectlist(args, 0); + loop = state->pc; + for (;;) { + for (;;) { + if (empty(bufstack)) { + if (usezle) { + int oef = errflag; + + isfirstln = 1; + str = zleentry(ZLE_CMD_READ, &prompt3, NULL, + 0, ZLCON_SELECT); + if (errflag) + str = NULL; + /* Keep any user interrupt error status */ + errflag = oef | (errflag & ERRFLAG_INT); + } else { + str = promptexpand(prompt3, 0, NULL, NULL, NULL); + zputs(str, stderr); + free(str); + fflush(stderr); + str = fgets(zhalloc(256), 256, inp); + } + } else + str = (char *)getlinknode(bufstack); + if (!str && !errflag) + setsparam("REPLY", ztrdup("")); /* EOF (user pressed Ctrl+D) */ + if (!str || errflag) { + if (breaks) + breaks--; + fprintf(stderr, "\n"); + fflush(stderr); + goto done; + } + if ((s = strchr(str, '\n'))) + *s = '\0'; + if (*str) + break; + more = selectlist(args, more); + } + setsparam("REPLY", ztrdup(str)); + i = atoi(str); + if (!i) + str = ""; + else { + for (i--, n = firstnode(args); n && i; incnode(n), i--); + if (n) + str = (char *) getdata(n); + else + str = ""; + } + setsparam(name, ztrdup(str)); + state->pc = loop; + execlist(state, 1, 0); + freeheap(); + if (breaks) { + breaks--; + if (breaks || !contflag) + break; + contflag = 0; + } + if (retflag || errflag) + break; + } + done: + cmdpop(); + popheap(); + fclose(inp); + loops--; + simple_pline = old_simple_pline; + state->pc = end; + this_noerrexit = 1; + return lastval; +} + +/* And this is used to print select lists. */ + +/**/ +size_t +selectlist(LinkList l, size_t start) +{ + size_t longest = 1, fct, fw = 0, colsz, t0, t1, ct; + char **arr, **ap; + + zleentry(ZLE_CMD_TRASH); + arr = hlinklist2array(l, 0); + for (ap = arr; *ap; ap++) + if (strlen(*ap) > longest) + longest = strlen(*ap); + t0 = ct = ap - arr; + longest++; + while (t0) + t0 /= 10, longest++; + /* to compensate for added ')' */ + fct = (zterm_columns - 1) / (longest + 3); + if (fct == 0) + fct = 1; + else + fw = (zterm_columns - 1) / fct; + colsz = (ct + fct - 1) / fct; + for (t1 = start; t1 != colsz && t1 - start < zterm_lines - 2; t1++) { + ap = arr + t1; + do { + size_t t2 = strlen(*ap) + 2; + int t3; + + fprintf(stderr, "%d) %s", t3 = ap - arr + 1, *ap); + while (t3) + t2++, t3 /= 10; + for (; t2 < fw; t2++) + fputc(' ', stderr); + for (t0 = colsz; t0 && *ap; t0--, ap++); + } + while (*ap); + fputc('\n', stderr); + } + + /* Below is a simple attempt at doing it the Korn Way.. + ap = arr; + t0 = 0; + do { + t0++; + fprintf(stderr,"%d) %s\n",t0,*ap); + ap++; + } + while (*ap);*/ + fflush(stderr); + + return t1 < colsz ? t1 : 0; +} + +/**/ +int +execwhile(Estate state, UNUSED(int do_exec)) +{ + Wordcode end, loop; + wordcode code = state->pc[-1]; + int olderrexit, oldval, isuntil = (WC_WHILE_TYPE(code) == WC_WHILE_UNTIL); + int old_simple_pline = simple_pline; + + end = state->pc + WC_WHILE_SKIP(code); + olderrexit = noerrexit; + oldval = 0; + pushheap(); + cmdpush(isuntil ? CS_UNTIL : CS_WHILE); + loops++; + loop = state->pc; + + if (loop[0] == WC_END && loop[1] == WC_END) { + + /* This is an empty loop. Make sure the signal handler sets the + * flags and then just wait for someone hitting ^C. */ + + simple_pline = 1; + + while (!breaks) + ; + breaks--; + + simple_pline = old_simple_pline; + } else + for (;;) { + state->pc = loop; + noerrexit = NOERREXIT_EXIT | NOERREXIT_RETURN; + + /* In case the test condition is a functional no-op, + * make sure signal handlers recognize ^C to end the loop. */ + simple_pline = 1; + + execlist(state, 1, 0); + + simple_pline = old_simple_pline; + noerrexit = olderrexit; + if (!((lastval == 0) ^ isuntil)) { + if (breaks) + breaks--; + if (!retflag) + lastval = oldval; + break; + } + if (retflag) + break; + + /* In case the loop body is also a functional no-op, + * make sure signal handlers recognize ^C as above. */ + simple_pline = 1; + + execlist(state, 1, 0); + + simple_pline = old_simple_pline; + if (breaks) { + breaks--; + if (breaks || !contflag) + break; + contflag = 0; + } + if (errflag) { + lastval = 1; + break; + } + if (retflag) + break; + freeheap(); + oldval = lastval; + } + cmdpop(); + popheap(); + loops--; + state->pc = end; + this_noerrexit = 1; + return lastval; +} + +/**/ +int +execrepeat(Estate state, UNUSED(int do_exec)) +{ + Wordcode end, loop; + wordcode code = state->pc[-1]; + int count, htok = 0; + char *tmp; + int old_simple_pline = simple_pline; + + /* See comments in execwhile() */ + simple_pline = 1; + + end = state->pc + WC_REPEAT_SKIP(code); + + lastval = 0; + tmp = ecgetstr(state, EC_DUPTOK, &htok); + if (htok) + singsub(&tmp); + count = mathevali(tmp); + if (errflag) + return 1; + pushheap(); + cmdpush(CS_REPEAT); + loops++; + loop = state->pc; + while (count-- > 0) { + state->pc = loop; + execlist(state, 1, 0); + freeheap(); + if (breaks) { + breaks--; + if (breaks || !contflag) + break; + contflag = 0; + } + if (errflag) { + lastval = 1; + break; + } + if (retflag) + break; + } + cmdpop(); + popheap(); + loops--; + simple_pline = old_simple_pline; + state->pc = end; + this_noerrexit = 1; + return lastval; +} + +/**/ +int +execif(Estate state, int do_exec) +{ + Wordcode end, next; + wordcode code = state->pc[-1]; + int olderrexit, s = 0, run = 0; + + olderrexit = noerrexit; + end = state->pc + WC_IF_SKIP(code); + + noerrexit |= NOERREXIT_EXIT | NOERREXIT_RETURN; + while (state->pc < end) { + code = *state->pc++; + if (wc_code(code) != WC_IF || + (run = (WC_IF_TYPE(code) == WC_IF_ELSE))) { + if (run) + run = 2; + break; + } + next = state->pc + WC_IF_SKIP(code); + cmdpush(s ? CS_ELIF : CS_IF); + execlist(state, 1, 0); + cmdpop(); + if (!lastval) { + run = 1; + break; + } + if (retflag) + break; + s = 1; + state->pc = next; + } + + if (run) { + /* we need to ignore lastval until we reach execcmd() */ + if (olderrexit) + noerrexit = olderrexit; + else if (lastval) + noerrexit |= NOERREXIT_EXIT | NOERREXIT_RETURN | NOERREXIT_UNTIL_EXEC; + else + noerrexit &= ~ (NOERREXIT_EXIT | NOERREXIT_RETURN); + cmdpush(run == 2 ? CS_ELSE : (s ? CS_ELIFTHEN : CS_IFTHEN)); + execlist(state, 1, do_exec); + cmdpop(); + } else { + noerrexit = olderrexit; + if (!retflag) + lastval = 0; + } + state->pc = end; + this_noerrexit = 1; + + return lastval; +} + +/**/ +int +execcase(Estate state, int do_exec) +{ + Wordcode end, next; + wordcode code = state->pc[-1]; + char *word, *pat; + int npat, save, nalts, ialt, patok, anypatok; + Patprog *spprog, pprog; + + end = state->pc + WC_CASE_SKIP(code); + + word = ecgetstr(state, EC_DUP, NULL); + singsub(&word); + untokenize(word); + anypatok = 0; + + cmdpush(CS_CASE); + while (state->pc < end) { + code = *state->pc++; + if (wc_code(code) != WC_CASE) + break; + + save = 0; + next = state->pc + WC_CASE_SKIP(code); + nalts = *state->pc++; + ialt = patok = 0; + + if (isset(XTRACE)) { + printprompt4(); + fprintf(xtrerr, "case %s (", word); + } + + while (!patok && nalts) { + npat = state->pc[1]; + spprog = state->prog->pats + npat; + pprog = NULL; + pat = NULL; + + queue_signals(); + + if (isset(XTRACE)) { + int htok = 0; + pat = dupstring(ecrawstr(state->prog, state->pc, &htok)); + if (htok) + singsub(&pat); + + if (ialt++) + fprintf(stderr, " | "); + quote_tokenized_output(pat, xtrerr); + } + + if (*spprog != dummy_patprog1 && *spprog != dummy_patprog2) + pprog = *spprog; + + if (!pprog) { + if (!pat) { + char *opat; + int htok = 0; + + pat = dupstring(opat = ecrawstr(state->prog, + state->pc, &htok)); + if (htok) + singsub(&pat); + save = (!(state->prog->flags & EF_HEAP) && + !strcmp(pat, opat) && *spprog != dummy_patprog2); + } + if (!(pprog = patcompile(pat, (save ? PAT_ZDUP : PAT_STATIC), + NULL))) + zerr("bad pattern: %s", pat); + else if (save) + *spprog = pprog; + } + if (pprog && pattry(pprog, word)) + patok = anypatok = 1; + state->pc += 2; + nalts--; + + unqueue_signals(); + } + state->pc += 2 * nalts; + if (isset(XTRACE)) { + fprintf(xtrerr, ")\n"); + fflush(xtrerr); + } + if (patok) { + execlist(state, 1, ((WC_CASE_TYPE(code) == WC_CASE_OR) && + do_exec)); + while (!retflag && wc_code(code) == WC_CASE && + WC_CASE_TYPE(code) == WC_CASE_AND && state->pc < end) { + state->pc = next; + code = *state->pc++; + next = state->pc + WC_CASE_SKIP(code); + nalts = *state->pc++; + state->pc += 2 * nalts; + execlist(state, 1, ((WC_CASE_TYPE(code) == WC_CASE_OR) && + do_exec)); + } + if (WC_CASE_TYPE(code) != WC_CASE_TESTAND) + break; + } + state->pc = next; + } + cmdpop(); + + state->pc = end; + + if (!anypatok) + lastval = 0; + this_noerrexit = 1; + + return lastval; +} + +/* + * Errflag from `try' block, may be reset in `always' block. + * Accessible from an integer parameter, so needs to be a zlong. + */ + +/**/ +zlong +try_errflag = -1; + +/** + * Corresponding interrupt error status form `try' block. + */ + +/**/ +zlong +try_interrupt = -1; + +/**/ +zlong +try_tryflag = 0; + +/**/ +int +exectry(Estate state, int do_exec) +{ + Wordcode end, always; + int endval; + int save_retflag, save_breaks, save_contflag; + zlong save_try_errflag, save_try_tryflag, save_try_interrupt; + + end = state->pc + WC_TRY_SKIP(state->pc[-1]); + always = state->pc + 1 + WC_TRY_SKIP(*state->pc); + state->pc++; + pushheap(); + cmdpush(CS_CURSH); + + /* The :try clause */ + save_try_tryflag = try_tryflag; + try_tryflag = 1; + + execlist(state, 1, do_exec); + + try_tryflag = save_try_tryflag; + + /* Don't record errflag here, may be reset. However, */ + /* endval should show failure when there is an error. */ + endval = lastval ? lastval : errflag; + + freeheap(); + + cmdpop(); + cmdpush(CS_ALWAYS); + + /* The always clause. */ + save_try_errflag = try_errflag; + save_try_interrupt = try_interrupt; + try_errflag = (zlong)(errflag & ERRFLAG_ERROR); + try_interrupt = (zlong)((errflag & ERRFLAG_INT) ? 1 : 0); + /* We need to reset all errors to allow the block to execute */ + errflag = 0; + save_retflag = retflag; + retflag = 0; + save_breaks = breaks; + breaks = 0; + save_contflag = contflag; + contflag = 0; + + state->pc = always; + execlist(state, 1, do_exec); + + if (try_errflag) + errflag |= ERRFLAG_ERROR; + else + errflag &= ~ERRFLAG_ERROR; + if (try_interrupt) + errflag |= ERRFLAG_INT; + else + errflag &= ~ERRFLAG_INT; + try_errflag = save_try_errflag; + try_interrupt = save_try_interrupt; + if (!retflag) + retflag = save_retflag; + if (!breaks) + breaks = save_breaks; + if (!contflag) + contflag = save_contflag; + + cmdpop(); + popheap(); + state->pc = end; + + return endval; +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/makepro.awk b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/makepro.awk new file mode 100644 index 00000000..0498c154 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/makepro.awk @@ -0,0 +1,166 @@ +# +# makepro.awk - generate prototype lists +# + +BEGIN { + aborting = 0 + + # arg 1 is the name of the file to process + # arg 2 is the name of the subdirectory it is in + if(ARGC != 3) { + aborting = 1 + exit 1 + } + name = ARGV[1] + gsub(/^.*\//, "", name) + gsub(/\.c$/, "", name) + name = ARGV[2] "_" name + gsub(/\//, "_", name) + ARGC-- + + printf "E#ifndef have_%s_globals\n", name + printf "E#define have_%s_globals\n", name + printf "E\n" +} + +# all relevant declarations are preceded by "/**/" on a line by itself + +/^\/\*\*\/$/ { + # The declaration is on following lines. The interesting part might + # be terminated by a `{' (`int foo(void) { }' or `int bar[] = {') + # or `;' (`int x;'). + line = "" + isfunc = 0 + while(1) { + if(getline <= 0) { + aborting = 1 + exit 1 + } + if (line == "" && $0 ~ /^[ \t]*#/) { + # Directly after the /**/ was a preprocessor line. + # Spit it out and re-start the outer loop. + printf "E%s\n", $0 + printf "L%s\n", $0 + next + } + gsub(/\t/, " ") + line = line " " $0 + gsub(/\/\*([^*]|\*+[^*\/])*\*+\//, " ", line) + if(line ~ /\/\*/) + continue + # If it is a function definition, note so. + if(line ~ /\) *(VA_DCL )*[{].*$/) #} + isfunc = 1 + if(sub(/ *[{;].*$/, "", line)) #} + break + } + if (!match(line, /VA_ALIST/)) { + # Put spaces around each identifier. + while(match(line, /[^_0-9A-Za-z ][_0-9A-Za-z]/) || + match(line, /[_0-9A-Za-z][^_0-9A-Za-z ]/)) + line = substr(line, 1, RSTART) " " substr(line, RSTART+1) + } + # Separate declarations into a type and a list of declarators. + # In each declarator, "@{" and "@}" are used in place of parens to + # mark function parameter lists, and "@!" is used in place of commas + # in parameter lists. "@<" and "@>" are used in place of + # non-parameter list parens. + gsub(/ _ +/, " _ ", line) + while(1) { + if(isfunc && match(line, /\([^()]*\)$/)) + line = substr(line, 1, RSTART-1) " _ (" substr(line, RSTART) ")" + else if(match(line, / _ \(\([^,()]*,/)) + line = substr(line, 1, RSTART+RLENGTH-2) "@!" substr(line, RSTART+RLENGTH) + else if(match(line, / _ \(\([^,()]*\)\)/)) + line = substr(line, 1, RSTART-1) "@{" substr(line, RSTART+5, RLENGTH-7) "@}" substr(line, RSTART+RLENGTH) + else if(match(line, /\([^,()]*\)/)) + line = substr(line, 1, RSTART-1) "@<" substr(line, RSTART+1, RLENGTH-2) "@>" substr(line, RSTART+RLENGTH) + else + break + } + sub(/^ */, "", line) + match(line, /^((const|enum|mod_export|static|struct|union) +)*([_0-9A-Za-z]+ +|((char|double|float|int|long|short|unsigned|void) +)+)((const|static) +)*/) + dtype = substr(line, 1, RLENGTH) + sub(/ *$/, "", dtype) + if(" " dtype " " ~ / static /) + locality = "L" + else + locality = "E" + exported = " " dtype " " ~ / mod_export / + line = substr(line, RLENGTH+1) "," + # Handle each declarator. + if (match(line, /VA_ALIST/)) { + # Already has VARARGS handling. + + # Put parens etc. back + gsub(/@[{]/, "((", line) + gsub(/@}/, "))", line) + gsub(/@/, ")", line) + gsub(/@!/, ",", line) + sub(/,$/, ";", line) + gsub(/mod_export/, "mod_import_function", dtype) + gsub(/VA_ALIST/, "VA_ALIST_PROTO", line) + sub(/ VA_DCL/, "", line) + + if(locality ~ /E/) + dtype = "extern " dtype + + if (match(line, /[_0-9A-Za-z]+\(VA_ALIST/)) + dnam = substr(line, RSTART, RLENGTH-9) + + # If this is exported, add it to the exported symbol list. + if (exported) + printf "X%s\n", dnam + + printf "%s%s %s\n", locality, dtype, line + } else { + while(match(line, /^[^,]*,/)) { + # Separate out the name from the declarator. Use "@+" and "@-" + # to bracket the name within the declarator. Strip off any + # initialiser. + dcltor = substr(line, 1, RLENGTH-1) + line = substr(line, RLENGTH+1) + sub(/\=.*$/, "", dcltor) + match(dcltor, /^([^_0-9A-Za-z]| const )*/) + dcltor = substr(dcltor, 1, RLENGTH) "@+" substr(dcltor, RLENGTH+1) + match(dcltor, /^.*@\+[_0-9A-Za-z]+/) + dcltor = substr(dcltor, 1, RLENGTH) "@-" substr(dcltor, RLENGTH+1) + dnam = dcltor + sub(/^.*@\+/, "", dnam) + sub(/@-.*$/, "", dnam) + + # Put parens etc. back + gsub(/@[{]/, " _((", dcltor) + gsub(/@}/, "))", dcltor) + gsub(/@/, ")", dcltor) + gsub(/@!/, ",", dcltor) + + # If this is exported, add it to the exported symbol list. + if(exported) + printf "X%s\n", dnam + + # Format the declaration for output + dcl = dtype " " dcltor ";" + if(locality ~ /E/) + dcl = "extern " dcl + if(isfunc) + gsub(/ mod_export /, " mod_import_function ", dcl) + else + gsub(/ mod_export /, " mod_import_variable ", dcl) + gsub(/@[+-]/, "", dcl) + gsub(/ +/, " ", dcl) + while(match(dcl, /[^_0-9A-Za-z] ./) || match(dcl, /. [^_0-9A-Za-z]/)) + dcl = substr(dcl, 1, RSTART) substr(dcl, RSTART+2) + printf "%s%s\n", locality, dcl + } + } +} + +END { + if(aborting) + exit 1 + printf "E\n" + printf "E#endif /* !have_%s_globals */\n", name +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/mem.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/mem.c new file mode 100644 index 00000000..77e4375f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/mem.c @@ -0,0 +1,1899 @@ +/* + * mem.c - memory management + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "mem.pro" + +/* + There are two ways to allocate memory in zsh. The first way is + to call zalloc/zshcalloc, which call malloc/calloc directly. It + is legal to call realloc() or free() on memory allocated this way. + The second way is to call zhalloc/hcalloc, which allocates memory + from one of the memory pools on the heap stack. Such memory pools + will automatically created when the heap allocation routines are + called. To be sure that they are freed at appropriate times + one should call pushheap() before one starts using heaps and + popheap() after that (when the memory allocated on the heaps since + the last pushheap() isn't needed anymore). + pushheap() saves the states of all currently allocated heaps and + popheap() resets them to the last state saved and destroys the + information about that state. If you called pushheap() and + allocated some memory on the heaps and then come to a place where + you don't need the allocated memory anymore but you still want + to allocate memory on the heap, you should call freeheap(). This + works like popheap(), only that it doesn't free the information + about the heap states (i.e. the heaps are like after the call to + pushheap() and you have to call popheap some time later). + + Memory allocated in this way does not have to be freed explicitly; + it will all be freed when the pool is destroyed. In fact, + attempting to free this memory may result in a core dump. + + If possible, the heaps are allocated using mmap() so that the + (*real*) heap isn't filled up with empty zsh heaps. If mmap() + is not available and zsh's own allocator is used, we use a simple trick + to avoid that: we allocate a large block of memory before allocating + a heap pool, this memory is freed again immediately after the pool + is allocated. If there are only small blocks on the free list this + guarantees that the memory for the pool is at the end of the memory + which means that we can give it back to the system when the pool is + freed. + + hrealloc(char *p, size_t old, size_t new) is an optimisation + with a similar interface to realloc(). Typically the new size + will be larger than the old one, since there is no gain in + shrinking the allocation (indeed, that will confused hrealloc() + since it will forget that the unused space once belonged to this + pointer). However, new == 0 is a special case; then if we + had to allocate a special heap for this memory it is freed at + that point. +*/ + +#if defined(HAVE_SYS_MMAN_H) && defined(HAVE_MMAP) && defined(HAVE_MUNMAP) + +#include + +/* + * This definition is designed to enable use of memory mapping on MacOS. + * However, performance tests indicate that MacOS mapped regions are + * somewhat slower to allocate than memory from malloc(), so whether + * using this improves performance depends on details of zhalloc(). + */ +#if defined(MAP_ANON) && !defined(MAP_ANONYMOUS) +#define MAP_ANONYMOUS MAP_ANON +#endif + +#if defined(MAP_ANONYMOUS) && defined(MAP_PRIVATE) + +#define USE_MMAP 1 +#define MMAP_FLAGS (MAP_ANONYMOUS | MAP_PRIVATE) + +#endif +#endif + +#ifdef ZSH_MEM_WARNING +# ifndef DEBUG +# define DEBUG 1 +# endif +#endif + +#if defined(ZSH_MEM) && defined(ZSH_MEM_DEBUG) + +static int h_m[1025], h_push, h_pop, h_free; + +#endif + +/* Make sure we align to the longest fundamental type. */ +union mem_align { + zlong l; + double d; +}; + +#define H_ISIZE sizeof(union mem_align) +#define HEAPSIZE (16384 - H_ISIZE) +/* Memory available for user data in default arena size */ +#define HEAP_ARENA_SIZE (HEAPSIZE - sizeof(struct heap)) +#define HEAPFREE (16384 - H_ISIZE) + +/* Memory available for user data in heap h */ +#define ARENA_SIZEOF(h) ((h)->size - sizeof(struct heap)) + +/* list of zsh heaps */ + +static Heap heaps; + +/* a heap with free space, not always correct (it will be the last heap + * if that was newly allocated but it may also be another one) */ + +static Heap fheap; + +/**/ +#ifdef ZSH_HEAP_DEBUG +/* + * The heap ID we'll allocate next. + * + * We'll avoid using 0 as that means zero-initialised memory + * containing a heap ID is (correctly) marked as invalid. + */ +static Heapid next_heap_id = (Heapid)1; + +/* + * The ID of the heap from which we last allocated heap memory. + * In theory, since we carefully avoid allocating heap memory during + * interrupts, after any call to zhalloc() or wrappers this should + * be the ID of the heap containing the memory just returned. + */ +/**/ +mod_export Heapid last_heap_id; + +/* + * Stack of heaps saved by new_heaps(). + * Assumes old_heaps() will come along and restore it later + * (outputs an error if old_heaps() is called out of sequence). + */ +static LinkList heaps_saved; + +/* + * Debugging verbosity. This must be set from a debugger. + * An 'or' of bits from the enum heap_debug_verbosity. + */ +static volatile int heap_debug_verbosity; + +/* + * Generate a heap identifier that's unique up to unsigned integer wrap. + * + * For the purposes of debugging we won't bother trying to make a + * heap_id globally unique, which would require checking all existing + * heaps every time we create an ID and still wouldn't do what we + * ideally want, which is to make sure the IDs of valid heaps are + * different from the IDs of no-longer-valid heaps. Given that, + * we'll just assume that if we haven't tracked the problem when the + * ID wraps we're out of luck. We could change the type to a long long + * if we wanted more room + */ + +static Heapid +new_heap_id(void) +{ + return next_heap_id++; +} + +/**/ +#endif + +/* Use new heaps from now on. This returns the old heap-list. */ + +/**/ +mod_export Heap +new_heaps(void) +{ + Heap h; + + queue_signals(); + h = heaps; + + fheap = heaps = NULL; + unqueue_signals(); + +#ifdef ZSH_HEAP_DEBUG + if (heap_debug_verbosity & HDV_NEW) { + fprintf(stderr, "HEAP DEBUG: heap " HEAPID_FMT + " saved, new heaps created.\n", h->heap_id); + } + if (!heaps_saved) + heaps_saved = znewlinklist(); + zpushnode(heaps_saved, h); +#endif + return h; +} + +/* Re-install the old heaps again, freeing the new ones. */ + +/**/ +mod_export void +old_heaps(Heap old) +{ + Heap h, n; + + queue_signals(); + for (h = heaps; h; h = n) { + n = h->next; + DPUTS(h->sp, "BUG: old_heaps() with pushed heaps"); +#ifdef ZSH_HEAP_DEBUG + if (heap_debug_verbosity & HDV_FREE) { + fprintf(stderr, "HEAP DEBUG: heap " HEAPID_FMT + "freed in old_heaps().\n", h->heap_id); + } +#endif +#ifdef USE_MMAP + munmap((void *) h, h->size); +#else + zfree(h, HEAPSIZE); +#endif +#ifdef ZSH_VALGRIND + VALGRIND_DESTROY_MEMPOOL((char *)h); +#endif + } + heaps = old; +#ifdef ZSH_HEAP_DEBUG + if (heap_debug_verbosity & HDV_OLD) { + fprintf(stderr, "HEAP DEBUG: heap " HEAPID_FMT + "restored.\n", heaps->heap_id); + } + { + Heap myold = heaps_saved ? getlinknode(heaps_saved) : NULL; + if (old != myold) + { + fprintf(stderr, "HEAP DEBUG: invalid old heap " HEAPID_FMT + ", expecting " HEAPID_FMT ".\n", old->heap_id, + myold->heap_id); + } + } +#endif + fheap = NULL; + unqueue_signals(); +} + +/* Temporarily switch to other heaps (or back again). */ + +/**/ +mod_export Heap +switch_heaps(Heap new) +{ + Heap h; + + queue_signals(); + h = heaps; + +#ifdef ZSH_HEAP_DEBUG + if (heap_debug_verbosity & HDV_SWITCH) { + fprintf(stderr, "HEAP DEBUG: heap temporarily switched from " + HEAPID_FMT " to " HEAPID_FMT ".\n", h->heap_id, new->heap_id); + } +#endif + heaps = new; + fheap = NULL; + unqueue_signals(); + + return h; +} + +/* save states of zsh heaps */ + +/**/ +mod_export void +pushheap(void) +{ + Heap h; + Heapstack hs; + + queue_signals(); + +#if defined(ZSH_MEM) && defined(ZSH_MEM_DEBUG) + h_push++; +#endif + + for (h = heaps; h; h = h->next) { + DPUTS(!h->used && h->next, "BUG: empty heap"); + hs = (Heapstack) zalloc(sizeof(*hs)); + hs->next = h->sp; + h->sp = hs; + hs->used = h->used; +#ifdef ZSH_HEAP_DEBUG + hs->heap_id = h->heap_id; + h->heap_id = new_heap_id(); + if (heap_debug_verbosity & HDV_PUSH) { + fprintf(stderr, "HEAP DEBUG: heap " HEAPID_FMT " pushed, new id is " + HEAPID_FMT ".\n", + hs->heap_id, h->heap_id); + } +#endif + } + unqueue_signals(); +} + +/* reset heaps to previous state */ + +/**/ +mod_export void +freeheap(void) +{ + Heap h, hn, hl = NULL; + + queue_signals(); + +#if defined(ZSH_MEM) && defined(ZSH_MEM_DEBUG) + h_free++; +#endif + + /* + * When pushheap() is called, it sweeps over the entire heaps list of + * arenas and marks every one of them with the amount of free space in + * that arena at that moment. zhalloc() is then allowed to grab bits + * out of any of those arenas that have free space. + * + * Whenever fheap is NULL here, the loop below sweeps back over the + * entire heap list again, resetting the free space in every arena to + * the amount stashed by pushheap() and finding the arena with the most + * free space to optimize zhalloc()'s next search. When there's a lot + * of stuff already on the heap, this is an enormous amount of work, + * and performance goes to hell. + * + * Therefore, we defer freeing the most recently allocated arena until + * we reach popheap(). + * + * However, if the arena to which fheap points is unused, we want to + * reclaim space in earlier arenas, so we have no choice but to do the + * sweep for a new fheap. + */ + if (fheap && !fheap->sp) + fheap = NULL; /* We used to do this unconditionally */ + /* + * In other cases, either fheap is already correct, or it has never + * been set and this loop will do it, or it'll be reset from scratch + * on the next popheap(). So all that's needed here is to pick up + * the scan wherever the last pass [or the last popheap()] left off. + */ + for (h = (fheap ? fheap : heaps); h; h = hn) { + hn = h->next; + if (h->sp) { +#ifdef ZSH_MEM_DEBUG +#ifdef ZSH_VALGRIND + VALGRIND_MAKE_MEM_UNDEFINED((char *)arena(h) + h->sp->used, + h->used - h->sp->used); +#endif + memset(arena(h) + h->sp->used, 0xff, h->used - h->sp->used); +#endif + h->used = h->sp->used; + if (!fheap) { + if (h->used < ARENA_SIZEOF(h)) + fheap = h; + } else if (ARENA_SIZEOF(h) - h->used > + ARENA_SIZEOF(fheap) - fheap->used) + fheap = h; + hl = h; +#ifdef ZSH_HEAP_DEBUG + /* + * As the free makes the heap invalid, give it a new + * identifier. We're not popping it, so don't use + * the one in the heap stack. + */ + { + Heapid new_id = new_heap_id(); + if (heap_debug_verbosity & HDV_FREE) { + fprintf(stderr, "HEAP DEBUG: heap " HEAPID_FMT + " freed, new id is " HEAPID_FMT ".\n", + h->heap_id, new_id); + } + h->heap_id = new_id; + } +#endif +#ifdef ZSH_VALGRIND + VALGRIND_MEMPOOL_TRIM((char *)h, (char *)arena(h), h->used); +#endif + } else { + if (fheap == h) + fheap = NULL; + if (h->next) { + /* We want to cut this out of the arena list if we can */ + if (h == heaps) + hl = heaps = h->next; + else if (hl && hl->next == h) + hl->next = h->next; + else { + DPUTS(hl, "hl->next != h when freeing"); + hl = h; + continue; + } + h->next = NULL; + } else { + /* Leave an empty arena at the end until popped */ + h->used = 0; + fheap = hl = h; + break; + } +#ifdef USE_MMAP + munmap((void *) h, h->size); +#else + zfree(h, HEAPSIZE); +#endif +#ifdef ZSH_VALGRIND + VALGRIND_DESTROY_MEMPOOL((char *)h); +#endif + } + } + if (hl) + hl->next = NULL; + else + heaps = fheap = NULL; + + unqueue_signals(); +} + +/* reset heap to previous state and destroy state information */ + +/**/ +mod_export void +popheap(void) +{ + Heap h, hn, hl = NULL; + Heapstack hs; + + queue_signals(); + +#if defined(ZSH_MEM) && defined(ZSH_MEM_DEBUG) + h_pop++; +#endif + + fheap = NULL; + for (h = heaps; h; h = hn) { + hn = h->next; + if ((hs = h->sp)) { + h->sp = hs->next; +#ifdef ZSH_MEM_DEBUG +#ifdef ZSH_VALGRIND + VALGRIND_MAKE_MEM_UNDEFINED((char *)arena(h) + hs->used, + h->used - hs->used); +#endif + memset(arena(h) + hs->used, 0xff, h->used - hs->used); +#endif + h->used = hs->used; +#ifdef ZSH_HEAP_DEBUG + if (heap_debug_verbosity & HDV_POP) { + fprintf(stderr, "HEAP DEBUG: heap " HEAPID_FMT + " popped, old heap was " HEAPID_FMT ".\n", + h->heap_id, hs->heap_id); + } + h->heap_id = hs->heap_id; +#endif +#ifdef ZSH_VALGRIND + VALGRIND_MEMPOOL_TRIM((char *)h, (char *)arena(h), h->used); +#endif + if (!fheap) { + if (h->used < ARENA_SIZEOF(h)) + fheap = h; + } else if (ARENA_SIZEOF(h) - h->used > + ARENA_SIZEOF(fheap) - fheap->used) + fheap = h; + zfree(hs, sizeof(*hs)); + + hl = h; + } else { + if (h->next) { + /* We want to cut this out of the arena list if we can */ + if (h == heaps) + hl = heaps = h->next; + else if (hl && hl->next == h) + hl->next = h->next; + else { + DPUTS(hl, "hl->next != h when popping"); + hl = h; + continue; + } + h->next = NULL; + } else if (hl == h) /* This is the last arena of all */ + hl = NULL; +#ifdef USE_MMAP + munmap((void *) h, h->size); +#else + zfree(h, HEAPSIZE); +#endif +#ifdef ZSH_VALGRIND + VALGRIND_DESTROY_MEMPOOL((char *)h); +#endif + } + } + if (hl) + hl->next = NULL; + else + heaps = NULL; + + unqueue_signals(); +} + +#ifdef USE_MMAP +/* + * Utility function to allocate a heap area of at least *n bytes. + * *n will be rounded up to the next page boundary. + */ +static Heap +mmap_heap_alloc(size_t *n) +{ + Heap h; + static size_t pgsz = 0; + + if (!pgsz) { + +#ifdef _SC_PAGESIZE + pgsz = sysconf(_SC_PAGESIZE); /* SVR4 */ +#else +# ifdef _SC_PAGE_SIZE + pgsz = sysconf(_SC_PAGE_SIZE); /* HPUX */ +# else + pgsz = getpagesize(); +# endif +#endif + + pgsz--; + } + *n = (*n + pgsz) & ~pgsz; + h = (Heap) mmap(NULL, *n, PROT_READ | PROT_WRITE, + MMAP_FLAGS, -1, 0); + if (h == ((Heap) -1)) { + zerr("fatal error: out of heap memory"); + exit(1); + } + + return h; +} +#endif + +/* check whether a pointer is within a memory pool */ + +/**/ +mod_export void * +zheapptr(void *p) +{ + Heap h; + queue_signals(); + for (h = heaps; h; h = h->next) + if ((char *)p >= arena(h) && + (char *)p + H_ISIZE < arena(h) + ARENA_SIZEOF(h)) + break; + unqueue_signals(); + return (h ? p : 0); +} + +/* allocate memory from the current memory pool */ + +/**/ +mod_export void * +zhalloc(size_t size) +{ + Heap h, hp = NULL; + size_t n; +#ifdef ZSH_VALGRIND + size_t req_size = size; + + if (size == 0) + return NULL; +#endif + + size = (size + H_ISIZE - 1) & ~(H_ISIZE - 1); + + queue_signals(); + +#if defined(ZSH_MEM) && defined(ZSH_MEM_DEBUG) + h_m[size < (1024 * H_ISIZE) ? (size / H_ISIZE) : 1024]++; +#endif + + /* find a heap with enough free space */ + + /* + * This previously assigned: + * h = ((fheap && ARENA_SIZEOF(fheap) >= (size + fheap->used)) + * ? fheap : heaps); + * but we think that nothing upstream of fheap has more free space, + * so why start over at heaps just because fheap has too little? + */ + for (h = (fheap ? fheap : heaps); h; h = h->next) { + hp = h; + if (ARENA_SIZEOF(h) >= (n = size + h->used)) { + void *ret; + + h->used = n; + ret = arena(h) + n - size; + unqueue_signals(); +#ifdef ZSH_HEAP_DEBUG + last_heap_id = h->heap_id; + if (heap_debug_verbosity & HDV_ALLOC) { + fprintf(stderr, "HEAP DEBUG: allocated memory from heap " + HEAPID_FMT ".\n", h->heap_id); + } +#endif +#ifdef ZSH_VALGRIND + VALGRIND_MEMPOOL_ALLOC((char *)h, (char *)ret, req_size); +#endif + return ret; + } + } + { + /* not found, allocate new heap */ +#if defined(ZSH_MEM) && !defined(USE_MMAP) + static int called = 0; + void *foo = called ? (void *)malloc(HEAPFREE) : NULL; + /* tricky, see above */ +#endif + + n = HEAP_ARENA_SIZE > size ? HEAPSIZE : size + sizeof(*h); + +#ifdef USE_MMAP + h = mmap_heap_alloc(&n); +#else + h = (Heap) zalloc(n); +#endif + +#if defined(ZSH_MEM) && !defined(USE_MMAP) + if (called) + zfree(foo, HEAPFREE); + called = 1; +#endif + + h->size = n; + h->used = size; + h->next = NULL; + h->sp = NULL; +#ifdef ZSH_HEAP_DEBUG + h->heap_id = new_heap_id(); + if (heap_debug_verbosity & HDV_CREATE) { + fprintf(stderr, "HEAP DEBUG: create new heap " HEAPID_FMT ".\n", + h->heap_id); + } +#endif +#ifdef ZSH_VALGRIND + VALGRIND_CREATE_MEMPOOL((char *)h, 0, 0); + VALGRIND_MAKE_MEM_NOACCESS((char *)arena(h), + n - ((char *)arena(h)-(char *)h)); + VALGRIND_MEMPOOL_ALLOC((char *)h, (char *)arena(h), req_size); +#endif + + DPUTS(hp && hp->next, "failed to find end of chain in zhalloc"); + if (hp) + hp->next = h; + else + heaps = h; + fheap = h; + + unqueue_signals(); +#ifdef ZSH_HEAP_DEBUG + last_heap_id = h->heap_id; + if (heap_debug_verbosity & HDV_ALLOC) { + fprintf(stderr, "HEAP DEBUG: allocated memory from heap " + HEAPID_FMT ".\n", h->heap_id); + } +#endif + return arena(h); + } +} + +/**/ +mod_export void * +hrealloc(char *p, size_t old, size_t new) +{ + Heap h, ph; + +#ifdef ZSH_VALGRIND + size_t new_req = new; +#endif + + old = (old + H_ISIZE - 1) & ~(H_ISIZE - 1); + new = (new + H_ISIZE - 1) & ~(H_ISIZE - 1); + + if (old == new) + return p; + if (!old && !p) +#ifdef ZSH_VALGRIND + return zhalloc(new_req); +#else + return zhalloc(new); +#endif + + /* find the heap with p */ + + queue_signals(); + for (h = heaps, ph = NULL; h; ph = h, h = h->next) + if (p >= arena(h) && p < arena(h) + ARENA_SIZEOF(h)) + break; + + DPUTS(!h, "BUG: hrealloc() called for non-heap memory."); + DPUTS(h->sp && arena(h) + h->sp->used > p, + "BUG: hrealloc() wants to realloc pushed memory"); + + /* + * If the end of the old chunk is before the used pointer, + * more memory has been zhalloc'ed afterwards. + * We can't tell if that's still in use, obviously, since + * that's the whole point of heap memory. + * We have no choice other than to grab some more memory + * somewhere else and copy in the old stuff. + */ + if (p + old < arena(h) + h->used) { + if (new > old) { +#ifdef ZSH_VALGRIND + char *ptr = (char *) zhalloc(new_req); +#else + char *ptr = (char *) zhalloc(new); +#endif + memcpy(ptr, p, old); +#ifdef ZSH_MEM_DEBUG + memset(p, 0xff, old); +#endif +#ifdef ZSH_VALGRIND + VALGRIND_MEMPOOL_FREE((char *)h, (char *)p); + /* + * zhalloc() marked h,ptr,new as an allocation so we don't + * need to do that here. + */ +#endif + unqueue_signals(); + return ptr; + } else { +#ifdef ZSH_VALGRIND + VALGRIND_MEMPOOL_FREE((char *)h, (char *)p); + if (p) { + VALGRIND_MEMPOOL_ALLOC((char *)h, (char *)p, + new_req); + VALGRIND_MAKE_MEM_DEFINED((char *)h, (char *)p); + } +#endif + unqueue_signals(); + return new ? p : NULL; + } + } + + DPUTS(p + old != arena(h) + h->used, "BUG: hrealloc more than allocated"); + + /* + * We now know there's nothing afterwards in the heap, now see if + * there's nothing before. Then we can reallocate the whole thing. + * Otherwise, we need to keep the stuff at the start of the heap, + * then allocate a new one too; this is handled below. (This will + * guarantee we occupy a full heap next time round, provided we + * don't use the heap for anything else.) + */ + if (p == arena(h)) { +#ifdef ZSH_HEAP_DEBUG + Heapid heap_id = h->heap_id; +#endif + /* + * Zero new seems to be a special case saying we've finished + * with the specially reallocated memory, see scanner() in glob.c. + */ + if (!new) { + if (ph) + ph->next = h->next; + else + heaps = h->next; + fheap = NULL; +#ifdef USE_MMAP + munmap((void *) h, h->size); +#else + zfree(h, HEAPSIZE); +#endif +#ifdef ZSH_VALGRIND + VALGRIND_DESTROY_MEMPOOL((char *)h); +#endif + unqueue_signals(); + return NULL; + } + if (new > ARENA_SIZEOF(h)) { + Heap hnew; + /* + * Not enough memory in this heap. Allocate a new + * one of sufficient size. + * + * To avoid this happening too often, allocate + * chunks in multiples of HEAPSIZE. + * (Historical note: there didn't used to be any + * point in this since we didn't consistently record + * the allocated size of the heap, but now we do.) + */ + size_t n = (new + sizeof(*h) + HEAPSIZE); + n -= n % HEAPSIZE; + fheap = NULL; + +#ifdef USE_MMAP + { + /* + * I don't know any easy portable way of requesting + * a mmap'd segment be extended, so simply allocate + * a new one and copy. + */ + hnew = mmap_heap_alloc(&n); + /* Copy the entire heap, header (with next pointer) included */ + memcpy(hnew, h, h->size); + munmap((void *)h, h->size); + } +#else + hnew = (Heap) realloc(h, n); +#endif +#ifdef ZSH_VALGRIND + VALGRIND_MEMPOOL_FREE((char *)h, p); + VALGRIND_DESTROY_MEMPOOL((char *)h); + VALGRIND_CREATE_MEMPOOL((char *)hnew, 0, 0); + VALGRIND_MEMPOOL_ALLOC((char *)hnew, (char *)arena(hnew), + new_req); + VALGRIND_MAKE_MEM_DEFINED((char *)hnew, (char *)arena(hnew)); +#endif + h = hnew; + + h->size = n; + if (ph) + ph->next = h; + else + heaps = h; + } +#ifdef ZSH_VALGRIND + else { + VALGRIND_MEMPOOL_FREE((char *)h, (char *)p); + VALGRIND_MEMPOOL_ALLOC((char *)h, (char *)p, new_req); + VALGRIND_MAKE_MEM_DEFINED((char *)h, (char *)p); + } +#endif + h->used = new; +#ifdef ZSH_HEAP_DEBUG + h->heap_id = heap_id; +#endif + unqueue_signals(); + return arena(h); + } +#ifndef USE_MMAP + DPUTS(h->used > ARENA_SIZEOF(h), "BUG: hrealloc at invalid address"); +#endif + if (h->used + (new - old) <= ARENA_SIZEOF(h)) { + h->used += new - old; + unqueue_signals(); +#ifdef ZSH_VALGRIND + VALGRIND_MEMPOOL_FREE((char *)h, (char *)p); + VALGRIND_MEMPOOL_ALLOC((char *)h, (char *)p, new_req); + VALGRIND_MAKE_MEM_DEFINED((char *)h, (char *)p); +#endif + return p; + } else { + char *t = zhalloc(new); + memcpy(t, p, old > new ? new : old); + h->used -= old; +#ifdef ZSH_MEM_DEBUG + memset(p, 0xff, old); +#endif +#ifdef ZSH_VALGRIND + VALGRIND_MEMPOOL_FREE((char *)h, (char *)p); + /* t already marked as allocated by zhalloc() */ +#endif + unqueue_signals(); + return t; + } +} + +/**/ +#ifdef ZSH_HEAP_DEBUG +/* + * Check if heap_id is the identifier of a currently valid heap, + * including any heap buried on the stack, or of permanent memory. + * Return 0 if so, else 1. + * + * This gets confused by use of switch_heaps(). That's because so do I. + */ + +/**/ +mod_export int +memory_validate(Heapid heap_id) +{ + Heap h; + Heapstack hs; + LinkNode node; + + if (heap_id == HEAPID_PERMANENT) + return 0; + + queue_signals(); + for (h = heaps; h; h = h->next) { + if (h->heap_id == heap_id) { + unqueue_signals(); + return 0; + } + for (hs = heaps->sp; hs; hs = hs->next) { + if (hs->heap_id == heap_id) { + unqueue_signals(); + return 0; + } + } + } + + if (heaps_saved) { + for (node = firstnode(heaps_saved); node; incnode(node)) { + for (h = (Heap)getdata(node); h; h = h->next) { + if (h->heap_id == heap_id) { + unqueue_signals(); + return 0; + } + for (hs = heaps->sp; hs; hs = hs->next) { + if (hs->heap_id == heap_id) { + unqueue_signals(); + return 0; + } + } + } + } + } + + unqueue_signals(); + return 1; +} +/**/ +#endif + +/* allocate memory from the current memory pool and clear it */ + +/**/ +mod_export void * +hcalloc(size_t size) +{ + void *ptr; + + ptr = zhalloc(size); + memset(ptr, 0, size); + return ptr; +} + +/* allocate permanent memory */ + +/**/ +mod_export void * +zalloc(size_t size) +{ + void *ptr; + + if (!size) + size = 1; + queue_signals(); + if (!(ptr = (void *) malloc(size))) { + zerr("fatal error: out of memory"); + exit(1); + } + unqueue_signals(); + + return ptr; +} + +/**/ +mod_export void * +zshcalloc(size_t size) +{ + void *ptr = zalloc(size); + if (!size) + size = 1; + memset(ptr, 0, size); + return ptr; +} + +/* This front-end to realloc is used to make sure we have a realloc * + * that conforms to POSIX realloc. Older realloc's can fail if * + * passed a NULL pointer, but POSIX realloc should handle this. A * + * better solution would be for configure to check if realloc is * + * POSIX compliant, but I'm not sure how to do that. */ + +/**/ +mod_export void * +zrealloc(void *ptr, size_t size) +{ + queue_signals(); + if (ptr) { + if (size) { + /* Do normal realloc */ + if (!(ptr = (void *) realloc(ptr, size))) { + zerr("fatal error: out of memory"); + exit(1); + } + unqueue_signals(); + return ptr; + } + else + /* If ptr is not NULL, but size is zero, * + * then object pointed to is freed. */ + free(ptr); + + ptr = NULL; + } else { + /* If ptr is NULL, then behave like malloc */ + if (!(ptr = (void *) malloc(size))) { + zerr("fatal error: out of memory"); + exit(1); + } + } + unqueue_signals(); + + return ptr; +} + +/**/ +#ifdef ZSH_MEM + +/* + Below is a simple segment oriented memory allocator for systems on + which it is better than the system's one. Memory is given in blocks + aligned to an integer multiple of sizeof(union mem_align), which will + probably be 64-bit as it is the longer of zlong or double. Each block is + preceded by a header which contains the length of the data part (in + bytes). In allocated blocks only this field of the structure m_hdr is + senseful. In free blocks the second field (next) is a pointer to the next + free segment on the free list. + + On top of this simple allocator there is a second allocator for small + chunks of data. It should be both faster and less space-consuming than + using the normal segment mechanism for such blocks. + For the first M_NSMALL-1 possible sizes memory is allocated in arrays + that can hold M_SNUM blocks. Each array is stored in one segment of the + main allocator. In these segments the third field of the header structure + (free) contains a pointer to the first free block in the array. The + last field (used) gives the number of already used blocks in the array. + + If the macro name ZSH_MEM_DEBUG is defined, some information about the memory + usage is stored. This information can than be viewed by calling the + builtin `mem' (which is only available if ZSH_MEM_DEBUG is set). + + If ZSH_MEM_WARNING is defined, error messages are printed in case of errors. + + If ZSH_SECURE_FREE is defined, free() checks if the given address is really + one that was returned by malloc(), it ignores it if it wasn't (printing + an error message if ZSH_MEM_WARNING is also defined). +*/ +#if !defined(__hpux) && !defined(DGUX) && !defined(__osf__) +# if defined(_BSD) +# ifndef HAVE_BRK_PROTO + extern int brk _((caddr_t)); +# endif +# ifndef HAVE_SBRK_PROTO + extern caddr_t sbrk _((int)); +# endif +# else +# ifndef HAVE_BRK_PROTO + extern int brk _((void *)); +# endif +# ifndef HAVE_SBRK_PROTO + extern void *sbrk _((int)); +# endif +# endif +#endif + +#if defined(_BSD) && !defined(STDC_HEADERS) +# define FREE_RET_T int +# define FREE_ARG_T char * +# define FREE_DO_RET +# define MALLOC_RET_T char * +# define MALLOC_ARG_T size_t +#else +# define FREE_RET_T void +# define FREE_ARG_T void * +# define MALLOC_RET_T void * +# define MALLOC_ARG_T size_t +#endif + +/* structure for building free list in blocks holding small blocks */ + +struct m_shdr { + struct m_shdr *next; /* next one on free list */ +#ifdef PAD_64_BIT + /* dummy to make this 64-bit aligned */ + struct m_shdr *dummy; +#endif +}; + +struct m_hdr { + zlong len; /* length of memory block */ +#if defined(PAD_64_BIT) && !defined(ZSH_64_BIT_TYPE) + /* either 1 or 2 zlong's, whichever makes up 64 bits. */ + zlong dummy1; +#endif + struct m_hdr *next; /* if free: next on free list + if block of small blocks: next one with + small blocks of same size*/ + struct m_shdr *free; /* if block of small blocks: free list */ + zlong used; /* if block of small blocks: number of used + blocks */ +#if defined(PAD_64_BIT) && !defined(ZSH_64_BIT_TYPE) + zlong dummy2; +#endif +}; + + +/* alignment for memory blocks */ + +#define M_ALIGN (sizeof(union mem_align)) + +/* length of memory header, length of first field of memory header and + minimal size of a block left free (if we allocate memory and take a + block from the free list that is larger than needed, it must have at + least M_MIN extra bytes to be splitted; if it has, the rest is put on + the free list) */ + +#define M_HSIZE (sizeof(struct m_hdr)) +#if defined(PAD_64_BIT) && !defined(ZSH_64_BIT_TYPE) +# define M_ISIZE (2*sizeof(zlong)) +#else +# define M_ISIZE (sizeof(zlong)) +#endif +#define M_MIN (2 * M_ISIZE) + +/* M_FREE is the number of bytes that have to be free before memory is + * given back to the system + * M_KEEP is the number of bytes that will be kept when memory is given + * back; note that this has to be less than M_FREE + * M_ALLOC is the number of extra bytes to request from the system */ + +#define M_FREE 32768 +#define M_KEEP 16384 +#define M_ALLOC M_KEEP + +/* a pointer to the last free block, a pointer to the free list (the blocks + on this list are kept in order - lowest address first) */ + +static struct m_hdr *m_lfree, *m_free; + +/* system's pagesize */ + +static long m_pgsz = 0; + +/* the highest and the lowest valid memory addresses, kept for fast validity + checks in free() and to find out if and when we can give memory back to + the system */ + +static char *m_high, *m_low; + +/* Management of blocks for small blocks: + Such blocks are kept in lists (one list for each of the sizes that are + allocated in such blocks). The lists are stored in the m_small array. + M_SIDX() calculates the index into this array for a given size. M_SNUM + is the size (in small blocks) of such blocks. M_SLEN() calculates the + size of the small blocks held in a memory block, given a pointer to the + header of it. M_SBLEN() gives the size of a memory block that can hold + an array of small blocks, given the size of these small blocks. M_BSLEN() + calculates the size of the small blocks held in a memory block, given the + length of that block (including the header of the memory block. M_NSMALL + is the number of possible block sizes that small blocks should be used + for. */ + + +#define M_SIDX(S) ((S) / M_ISIZE) +#define M_SNUM 128 +#define M_SLEN(M) ((M)->len / M_SNUM) +#if defined(PAD_64_BIT) && !defined(ZSH_64_BIT_TYPE) +/* Include the dummy in the alignment */ +#define M_SBLEN(S) ((S) * M_SNUM + sizeof(struct m_shdr *) + \ + 2*sizeof(zlong) + sizeof(struct m_hdr *)) +#define M_BSLEN(S) (((S) - sizeof(struct m_shdr *) - \ + 2*sizeof(zlong) - sizeof(struct m_hdr *)) / M_SNUM) +#else +#define M_SBLEN(S) ((S) * M_SNUM + sizeof(struct m_shdr *) + \ + sizeof(zlong) + sizeof(struct m_hdr *)) +#define M_BSLEN(S) (((S) - sizeof(struct m_shdr *) - \ + sizeof(zlong) - sizeof(struct m_hdr *)) / M_SNUM) +#endif +#define M_NSMALL 8 + +static struct m_hdr *m_small[M_NSMALL]; + +#ifdef ZSH_MEM_DEBUG + +static int m_s = 0, m_b = 0; +static int m_m[1025], m_f[1025]; + +static struct m_hdr *m_l; + +#endif /* ZSH_MEM_DEBUG */ + +MALLOC_RET_T +malloc(MALLOC_ARG_T size) +{ + struct m_hdr *m, *mp, *mt; + long n, s, os = 0; +#ifndef USE_MMAP + struct heap *h, *hp, *hf = NULL, *hfp = NULL; +#endif + + /* some systems want malloc to return the highest valid address plus one + if it is called with an argument of zero. + + TODO: really? Suppose we allocate more memory, so + that this is now in bounds, then a more rational application + that thinks it can free() anything it malloc'ed, even + of zero length, calls free for it? Aren't we in big + trouble? Wouldn't it be safer just to allocate some + memory anyway? + + If the above comment is really correct, then at least + we need to check in free() if we're freeing memory + at m_high. + */ + + if (!size) +#if 1 + size = 1; +#else + return (MALLOC_RET_T) m_high; +#endif + + queue_signals(); /* just queue signals rather than handling them */ + + /* first call, get page size */ + + if (!m_pgsz) { + +#ifdef _SC_PAGESIZE + m_pgsz = sysconf(_SC_PAGESIZE); /* SVR4 */ +#else +# ifdef _SC_PAGE_SIZE + m_pgsz = sysconf(_SC_PAGE_SIZE); /* HPUX */ +# else + m_pgsz = getpagesize(); +# endif +#endif + + m_free = m_lfree = NULL; + } + size = (size + M_ALIGN - 1) & ~(M_ALIGN - 1); + + /* Do we need a small block? */ + + if ((s = M_SIDX(size)) && s < M_NSMALL) { + /* yep, find a memory block with free small blocks of the + appropriate size (if we find it in this list, this means that + it has room for at least one more small block) */ + for (mp = NULL, m = m_small[s]; m && !m->free; mp = m, m = m->next); + + if (m) { + /* we found one */ + struct m_shdr *sh = m->free; + + m->free = sh->next; + m->used++; + + /* if all small blocks in this block are allocated, the block is + put at the end of the list blocks with small blocks of this + size (i.e., we try to keep blocks with free blocks at the + beginning of the list, to make the search faster) */ + + if (m->used == M_SNUM && m->next) { + for (mt = m; mt->next; mt = mt->next); + + mt->next = m; + if (mp) + mp->next = m->next; + else + m_small[s] = m->next; + m->next = NULL; + } +#ifdef ZSH_MEM_DEBUG + m_m[size / M_ISIZE]++; +#endif + + unqueue_signals(); + return (MALLOC_RET_T) sh; + } + /* we still want a small block but there were no block with a free + small block of the requested size; so we use the real allocation + routine to allocate a block for small blocks of this size */ + os = size; + size = M_SBLEN(size); + } else + s = 0; + + /* search the free list for an block of at least the requested size */ + for (mp = NULL, m = m_free; m && m->len < size; mp = m, m = m->next); + +#ifndef USE_MMAP + + /* if there is an empty zsh heap at a lower address we steal it and take + the memory from it, putting the rest on the free list (remember + that the blocks on the free list are ordered) */ + + for (hp = NULL, h = heaps; h; hp = h, h = h->next) + if (!h->used && + (!hf || h < hf) && + (!m || ((char *)m) > ((char *)h))) + hf = h, hfp = hp; + + if (hf) { + /* we found such a heap */ + Heapstack hso, hsn; + + /* delete structures on the list holding the heap states */ + for (hso = hf->sp; hso; hso = hsn) { + hsn = hso->next; + zfree(hso, sizeof(*hso)); + } + /* take it from the list of heaps */ + if (hfp) + hfp->next = hf->next; + else + heaps = hf->next; + /* now we simply free it and than search the free list again */ + zfree(hf, HEAPSIZE); + + for (mp = NULL, m = m_free; m && m->len < size; mp = m, m = m->next); + } +#endif + if (!m) { + long nal; + /* no matching free block was found, we have to request new + memory from the system */ + n = (size + M_HSIZE + M_ALLOC + m_pgsz - 1) & ~(m_pgsz - 1); + + if (((char *)(m = (struct m_hdr *)sbrk(n))) == ((char *)-1)) { + DPUTS1(1, "MEM: allocation error at sbrk, size %L.", n); + unqueue_signals(); + return NULL; + } + if ((nal = ((long)(char *)m) & (M_ALIGN-1))) { + if ((char *)sbrk(M_ALIGN - nal) == (char *)-1) { + DPUTS(1, "MEM: allocation error at sbrk."); + unqueue_signals(); + return NULL; + } + m = (struct m_hdr *) ((char *)m + (M_ALIGN - nal)); + } + /* set m_low, for the check in free() */ + if (!m_low) + m_low = (char *)m; + +#ifdef ZSH_MEM_DEBUG + m_s += n; + + if (!m_l) + m_l = m; +#endif + + /* save new highest address */ + m_high = ((char *)m) + n; + + /* initialize header */ + m->len = n - M_ISIZE; + m->next = NULL; + + /* put it on the free list and set m_lfree pointing to it */ + if ((mp = m_lfree)) + m_lfree->next = m; + m_lfree = m; + } + if ((n = m->len - size) > M_MIN) { + /* the block we want to use has more than M_MIN bytes plus the + number of bytes that were requested; we split it in two and + leave the rest on the free list */ + struct m_hdr *mtt = (struct m_hdr *)(((char *)m) + M_ISIZE + size); + + mtt->len = n - M_ISIZE; + mtt->next = m->next; + + m->len = size; + + /* put the rest on the list */ + if (m_lfree == m) + m_lfree = mtt; + + if (mp) + mp->next = mtt; + else + m_free = mtt; + } else if (mp) { + /* the block we found wasn't the first one on the free list */ + if (m == m_lfree) + m_lfree = mp; + mp->next = m->next; + } else { + /* it was the first one */ + m_free = m->next; + if (m == m_lfree) + m_lfree = m_free; + } + + if (s) { + /* we are allocating a block that should hold small blocks */ + struct m_shdr *sh, *shn; + + /* build the free list in this block and set `used' filed */ + m->free = sh = (struct m_shdr *)(((char *)m) + + sizeof(struct m_hdr) + os); + + for (n = M_SNUM - 2; n--; sh = shn) + shn = sh->next = sh + s; + sh->next = NULL; + + m->used = 1; + + /* put the block on the list of blocks holding small blocks if + this size */ + m->next = m_small[s]; + m_small[s] = m; + +#ifdef ZSH_MEM_DEBUG + m_m[os / M_ISIZE]++; +#endif + + unqueue_signals(); + return (MALLOC_RET_T) (((char *)m) + sizeof(struct m_hdr)); + } +#ifdef ZSH_MEM_DEBUG + m_m[m->len < (1024 * M_ISIZE) ? (m->len / M_ISIZE) : 1024]++; +#endif + + unqueue_signals(); + return (MALLOC_RET_T) & m->next; +} + +/* this is an internal free(); the second argument may, but need not hold + the size of the block the first argument is pointing to; if it is the + right size of this block, freeing it will be faster, though; the value + 0 for this parameter means: `don't know' */ + +/**/ +mod_export void +zfree(void *p, int sz) +{ + struct m_hdr *m = (struct m_hdr *)(((char *)p) - M_ISIZE), *mp, *mt = NULL; + int i; +# ifdef DEBUG + int osz = sz; +# endif + +#ifdef ZSH_SECURE_FREE + sz = 0; +#else + sz = (sz + M_ALIGN - 1) & ~(M_ALIGN - 1); +#endif + + if (!p) + return; + + /* first a simple check if the given address is valid */ + if (((char *)p) < m_low || ((char *)p) > m_high || + ((long)p) & (M_ALIGN - 1)) { + DPUTS(1, "BUG: attempt to free storage at invalid address"); + return; + } + + queue_signals(); + + fr_rec: + + if ((i = sz / M_ISIZE) < M_NSMALL || !sz) + /* if the given sizes says that it is a small block, find the + memory block holding it; we search all blocks with blocks + of at least the given size; if the size parameter is zero, + this means, that all blocks are searched */ + for (; i < M_NSMALL; i++) { + for (mp = NULL, mt = m_small[i]; + mt && (((char *)mt) > ((char *)p) || + (((char *)mt) + mt->len) < ((char *)p)); + mp = mt, mt = mt->next); + + if (mt) { + /* we found the block holding the small block */ + struct m_shdr *sh = (struct m_shdr *)p; + +#ifdef ZSH_SECURE_FREE + struct m_shdr *sh2; + + /* check if the given address is equal to the address of + the first small block plus an integer multiple of the + block size */ + if ((((char *)p) - (((char *)mt) + sizeof(struct m_hdr))) % + M_BSLEN(mt->len)) { + + DPUTS(1, "BUG: attempt to free storage at invalid address"); + unqueue_signals(); + return; + } + /* check, if the address is on the (block-intern) free list */ + for (sh2 = mt->free; sh2; sh2 = sh2->next) + if (((char *)p) == ((char *)sh2)) { + + DPUTS(1, "BUG: attempt to free already free storage"); + unqueue_signals(); + return; + } +#endif + DPUTS(M_BSLEN(mt->len) < osz, + "BUG: attempt to free more than allocated."); + +#ifdef ZSH_MEM_DEBUG + m_f[M_BSLEN(mt->len) / M_ISIZE]++; + memset(sh, 0xff, M_BSLEN(mt->len)); +#endif + + /* put the block onto the free list */ + sh->next = mt->free; + mt->free = sh; + + if (--mt->used) { + /* if there are still used blocks in this block, we + put it at the beginning of the list with blocks + holding small blocks of the same size (since we + know that there is at least one free block in it, + this will make allocation of small blocks faster; + it also guarantees that long living memory blocks + are preferred over younger ones */ + if (mp) { + mp->next = mt->next; + mt->next = m_small[i]; + m_small[i] = mt; + } + unqueue_signals(); + return; + } + /* if there are no more used small blocks in this + block, we free the whole block */ + if (mp) + mp->next = mt->next; + else + m_small[i] = mt->next; + + m = mt; + p = (void *) & m->next; + + break; + } else if (sz) { + /* if we didn't find a block and a size was given, try it + again as if no size were given */ + sz = 0; + goto fr_rec; + } + } +#ifdef ZSH_MEM_DEBUG + if (!mt) + m_f[m->len < (1024 * M_ISIZE) ? (m->len / M_ISIZE) : 1024]++; +#endif + +#ifdef ZSH_SECURE_FREE + /* search all memory blocks, if one of them is at the given address */ + for (mt = (struct m_hdr *)m_low; + ((char *)mt) < m_high; + mt = (struct m_hdr *)(((char *)mt) + M_ISIZE + mt->len)) + if (((char *)p) == ((char *)&mt->next)) + break; + + /* no block was found at the given address */ + if (((char *)mt) >= m_high) { + DPUTS(1, "BUG: attempt to free storage at invalid address"); + unqueue_signals(); + return; + } +#endif + + /* see if the block is on the free list */ + for (mp = NULL, mt = m_free; mt && mt < m; mp = mt, mt = mt->next); + + if (m == mt) { + /* it is, ouch! */ + DPUTS(1, "BUG: attempt to free already free storage"); + unqueue_signals(); + return; + } + DPUTS(m->len < osz, "BUG: attempt to free more than allocated"); +#ifdef ZSH_MEM_DEBUG + memset(p, 0xff, m->len); +#endif + if (mt && ((char *)mt) == (((char *)m) + M_ISIZE + m->len)) { + /* the block after the one we are freeing is free, we put them + together */ + m->len += mt->len + M_ISIZE; + m->next = mt->next; + + if (mt == m_lfree) + m_lfree = m; + } else + m->next = mt; + + if (mp && ((char *)m) == (((char *)mp) + M_ISIZE + mp->len)) { + /* the block before the one we are freeing is free, we put them + together */ + mp->len += m->len + M_ISIZE; + mp->next = m->next; + + if (m == m_lfree) + m_lfree = mp; + } else if (mp) + /* otherwise, we just put it on the free list */ + mp->next = m; + else { + m_free = m; + if (!m_lfree) + m_lfree = m_free; + } + + /* if the block we have just freed was at the end of the process heap + and now there is more than one page size of memory, we can give + it back to the system (and we do it ;-) */ + if ((((char *)m_lfree) + M_ISIZE + m_lfree->len) == m_high && + m_lfree->len >= m_pgsz + M_MIN + M_FREE) { + long n = (m_lfree->len - M_MIN - M_KEEP) & ~(m_pgsz - 1); + + m_lfree->len -= n; +#ifdef HAVE_BRK + if (brk(m_high -= n) == -1) { +#else + m_high -= n; + if (sbrk(-n) == (void *)-1) { +#endif /* HAVE_BRK */ + DPUTS(1, "MEM: allocation error at brk."); + } + +#ifdef ZSH_MEM_DEBUG + m_b += n; +#endif + } + unqueue_signals(); +} + +FREE_RET_T +free(FREE_ARG_T p) +{ + zfree(p, 0); /* 0 means: size is unknown */ + +#ifdef FREE_DO_RET + return 0; +#endif +} + +/* this one is for strings (and only strings, real strings, real C strings, + those that have a zero byte at the end) */ + +/**/ +mod_export void +zsfree(char *p) +{ + if (p) + zfree(p, strlen(p) + 1); +} + +MALLOC_RET_T +realloc(MALLOC_RET_T p, MALLOC_ARG_T size) +{ + struct m_hdr *m = (struct m_hdr *)(((char *)p) - M_ISIZE), *mt; + char *r; + int i, l = 0; + + /* some system..., see above */ + if (!p && size) { + queue_signals(); + r = malloc(size); + unqueue_signals(); + return (MALLOC_RET_T) r; + } + + /* and some systems even do this... */ + if (!p || !size) + return (MALLOC_RET_T) p; + + queue_signals(); /* just queue signals caught rather than handling them */ + + /* check if we are reallocating a small block, if we do, we have + to compute the size of the block from the sort of block it is in */ + for (i = 0; i < M_NSMALL; i++) { + for (mt = m_small[i]; + mt && (((char *)mt) > ((char *)p) || + (((char *)mt) + mt->len) < ((char *)p)); + mt = mt->next); + + if (mt) { + l = M_BSLEN(mt->len); + break; + } + } + if (!l) + /* otherwise the size of the block is in the memory just before + the given address */ + l = m->len; + + /* now allocate the new block, copy the old contents, and free the + old block */ + r = malloc(size); + memcpy(r, (char *)p, (size > l) ? l : size); + free(p); + + unqueue_signals(); + return (MALLOC_RET_T) r; +} + +MALLOC_RET_T +calloc(MALLOC_ARG_T n, MALLOC_ARG_T size) +{ + long l; + char *r; + + if (!(l = n * size)) + return (MALLOC_RET_T) m_high; + + /* + * use realloc() (with a NULL `p` argument it behaves exactly the same + * as malloc() does) to prevent an infinite loop caused by sibling-call + * optimizations (the malloc() call would otherwise be replaced by an + * unconditional branch back to line 1719 ad infinitum). + */ + r = realloc(NULL, l); + + memset(r, 0, l); + + return (MALLOC_RET_T) r; +} + +#ifdef ZSH_MEM_DEBUG + +/**/ +int +bin_mem(char *name, char **argv, Options ops, int func) +{ + int i, ii, fi, ui, j; + struct m_hdr *m, *mf, *ms; + char *b, *c, buf[40]; + long u = 0, f = 0, to, cu; + + queue_signals(); + if (OPT_ISSET(ops,'v')) { + printf("The lower and the upper addresses of the heap. Diff gives\n"); + printf("the difference between them, i.e. the size of the heap.\n\n"); + } + printf("low mem %ld\t high mem %ld\t diff %ld\n", + (long)m_l, (long)m_high, (long)(m_high - ((char *)m_l))); + + if (OPT_ISSET(ops,'v')) { + printf("\nThe number of bytes that were allocated using sbrk() and\n"); + printf("the number of bytes that were given back to the system\n"); + printf("via brk().\n"); + } + printf("\nsbrk %d\tbrk %d\n", m_s, m_b); + + if (OPT_ISSET(ops,'v')) { + printf("\nInformation about the sizes that were allocated or freed.\n"); + printf("For each size that were used the number of mallocs and\n"); + printf("frees is shown. Diff gives the difference between these\n"); + printf("values, i.e. the number of blocks of that size that is\n"); + printf("currently allocated. Total is the product of size and diff,\n"); + printf("i.e. the number of bytes that are allocated for blocks of\n"); + printf("this size. The last field gives the accumulated number of\n"); + printf("bytes for all sizes.\n"); + } + printf("\nsize\tmalloc\tfree\tdiff\ttotal\tcum\n"); + for (i = 0, cu = 0; i < 1024; i++) + if (m_m[i] || m_f[i]) { + to = (long) i * M_ISIZE * (m_m[i] - m_f[i]); + printf("%ld\t%d\t%d\t%d\t%ld\t%ld\n", + (long)i * M_ISIZE, m_m[i], m_f[i], m_m[i] - m_f[i], + to, (cu += to)); + } + + if (m_m[i] || m_f[i]) + printf("big\t%d\t%d\t%d\n", m_m[i], m_f[i], m_m[i] - m_f[i]); + + if (OPT_ISSET(ops,'v')) { + printf("\nThe list of memory blocks. For each block the following\n"); + printf("information is shown:\n\n"); + printf("num\tthe number of this block\n"); + printf("tnum\tlike num but counted separately for used and free\n"); + printf("\tblocks\n"); + printf("addr\tthe address of this block\n"); + printf("len\tthe length of the block\n"); + printf("state\tthe state of this block, this can be:\n"); + printf("\t used\tthis block is used for one big block\n"); + printf("\t free\tthis block is free\n"); + printf("\t small\tthis block is used for an array of small blocks\n"); + printf("cum\tthe accumulated sizes of the blocks, counted\n"); + printf("\tseparately for used and free blocks\n"); + printf("\nFor blocks holding small blocks the number of free\n"); + printf("blocks, the number of used blocks and the size of the\n"); + printf("blocks is shown. For otherwise used blocks the first few\n"); + printf("bytes are shown as an ASCII dump.\n"); + } + printf("\nblock list:\nnum\ttnum\taddr\t\tlen\tstate\tcum\n"); + for (m = m_l, mf = m_free, ii = fi = ui = 1; ((char *)m) < m_high; + m = (struct m_hdr *)(((char *)m) + M_ISIZE + m->len), ii++) { + for (j = 0, ms = NULL; j < M_NSMALL && !ms; j++) + for (ms = m_small[j]; ms; ms = ms->next) + if (ms == m) + break; + + if (m == mf) + buf[0] = '\0'; + else if (m == ms) + sprintf(buf, "%ld %ld %ld", (long)(M_SNUM - ms->used), + (long)ms->used, + (long)(m->len - sizeof(struct m_hdr)) / M_SNUM + 1); + + else { + for (i = 0, b = buf, c = (char *)&m->next; i < 20 && i < m->len; + i++, c++) + *b++ = (*c >= ' ' && *c < 127) ? *c : '.'; + *b = '\0'; + } + + printf("%d\t%d\t%ld\t%ld\t%s\t%ld\t%s\n", ii, + (m == mf) ? fi++ : ui++, + (long)m, (long)m->len, + (m == mf) ? "free" : ((m == ms) ? "small" : "used"), + (m == mf) ? (f += m->len) : (u += m->len), + buf); + + if (m == mf) + mf = mf->next; + } + + if (OPT_ISSET(ops,'v')) { + printf("\nHere is some information about the small blocks used.\n"); + printf("For each size the arrays with the number of free and the\n"); + printf("number of used blocks are shown.\n"); + } + printf("\nsmall blocks:\nsize\tblocks (free/used)\n"); + + for (i = 0; i < M_NSMALL; i++) + if (m_small[i]) { + printf("%ld\t", (long)i * M_ISIZE); + + for (ii = 0, m = m_small[i]; m; m = m->next) { + printf("(%ld/%ld) ", (long)(M_SNUM - m->used), + (long)m->used); + if (!((++ii) & 7)) + printf("\n\t"); + } + putchar('\n'); + } + if (OPT_ISSET(ops,'v')) { + printf("\n\nBelow is some information about the allocation\n"); + printf("behaviour of the zsh heaps. First the number of times\n"); + printf("pushheap(), popheap(), and freeheap() were called.\n"); + } + printf("\nzsh heaps:\n\n"); + + printf("push %d\tpop %d\tfree %d\n\n", h_push, h_pop, h_free); + + if (OPT_ISSET(ops,'v')) { + printf("\nThe next list shows for several sizes the number of times\n"); + printf("memory of this size were taken from heaps.\n\n"); + } + printf("size\tmalloc\ttotal\n"); + for (i = 0; i < 1024; i++) + if (h_m[i]) + printf("%ld\t%d\t%ld\n", (long)i * H_ISIZE, h_m[i], + (long)i * H_ISIZE * h_m[i]); + if (h_m[1024]) + printf("big\t%d\n", h_m[1024]); + + unqueue_signals(); + return 0; +} + +#endif + +/**/ +#else /* not ZSH_MEM */ + +/**/ +mod_export void +zfree(void *p, UNUSED(int sz)) +{ + free(p); +} + +/**/ +mod_export void +zsfree(char *p) +{ + free(p); +} + +/**/ +#endif diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/mkbltnmlst.sh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/mkbltnmlst.sh new file mode 100644 index 00000000..c4611d8b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/mkbltnmlst.sh @@ -0,0 +1,116 @@ +#! /bin/sh +# +# mkbltnmlst.sh: generate boot code for linked-in modules +# +# Written by Andrew Main +# + +srcdir=${srcdir-`echo $0|sed 's%/[^/][^/]*$%%'`} +test "x$srcdir" = "x$0" && srcdir=. +test "x$srcdir" = "x" && srcdir=. +CFMOD=${CFMOD-$srcdir/../config.modules} + +bin_mods="`grep ' link=static' $CFMOD | sed -e '/^#/d' \ +-e 's/ .*/ /' -e 's/^name=/ /'`" + +x_mods="`grep ' load=yes' $CFMOD | sed -e '/^#/d' -e '/ link=no/d' \ +-e 's/ .*/ /' -e 's/^name=/ /'`" + +trap "rm -f $1; exit 1" 1 2 15 + +exec > $1 + +for x_mod in $x_mods; do + modfile="`grep '^name='$x_mod' ' $CFMOD | sed -e 's/^.* modfile=//' \ + -e 's/ .*//'`" + if test "x$modfile" = x; then + echo >&2 "WARNING: no name for \`$x_mod' in $CFMOD (ignored)" + continue + fi + case "$bin_mods" in + *" $x_mod "*) + echo "/* linked-in known module \`$x_mod' */" + linked=yes + ;; + *) + echo "#ifdef DYNAMIC" + echo "/* non-linked-in known module \`$x_mod' */" + linked=no + esac + unset moddeps autofeatures autofeatures_emu + . $srcdir/../$modfile + if test "x$autofeatures" != x; then + if test "x$autofeatures_emu" != x; then + echo " {" + echo " char *zsh_features[] = { " + for feature in $autofeatures; do + echo " \"$feature\"," + done + echo " NULL" + echo " }; " + echo " char *emu_features[] = { " + for feature in $autofeatures_emu; do + echo " \"$feature\"," + done + echo " NULL" + echo " }; " + echo " autofeatures(\"zsh\", \"$x_mod\"," + echo " EMULATION(EMULATE_ZSH) ? zsh_features : emu_features," + echo " 0, 1);" + echo " }" + else + echo " if (EMULATION(EMULATE_ZSH)) {" + echo " char *features[] = { " + for feature in $autofeatures; do + echo " \"$feature\"," + done + echo " NULL" + echo " }; " + echo " autofeatures(\"zsh\", \"$x_mod\", features, 0, 1);" + echo " }" + fi + fi + for dep in $moddeps; do + echo " add_dep(\"$x_mod\", \"$dep\");" + done + test "x$linked" = xno && echo "#endif" +done + +echo +done_mods=" " +for bin_mod in $bin_mods; do + q_bin_mod=`echo $bin_mod | sed 's,Q,Qq,g;s,_,Qu,g;s,/,Qs,g'` + modfile="`grep '^name='$bin_mod' ' $CFMOD | sed -e 's/^.* modfile=//' \ + -e 's/ .*//'`" + echo "/* linked-in module \`$bin_mod' */" + unset moddeps + . $srcdir/../$modfile + for dep in $moddeps; do + # This assumes there are no circular dependencies in the builtin + # modules. Better ordering of config.modules would be necessary + # to enforce stricter dependency checking. + case $bin_mods in + *" $dep "*) + echo " /* depends on \`$dep' */" ;; + *) echo >&2 "ERROR: linked-in module \`$bin_mod' depends on \`$dep'" + rm -f $1 + exit 1 ;; + esac + done + echo " {" + echo " extern int setup_${q_bin_mod} _((Module));" + echo " extern int boot_${q_bin_mod} _((Module));" + echo " extern int features_${q_bin_mod} _((Module,char***));" + echo " extern int enables_${q_bin_mod} _((Module,int**));" + echo " extern int cleanup_${q_bin_mod} _((Module));" + echo " extern int finish_${q_bin_mod} _((Module));" + echo + echo " register_module(\"$bin_mod\"," + echo " setup_${q_bin_mod}," + echo " features_${q_bin_mod}," + echo " enables_${q_bin_mod}," + echo " boot_${q_bin_mod}," + echo " cleanup_${q_bin_mod}, finish_${q_bin_mod});" + echo " }" + done_mods="$done_mods$bin_mod " +done diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/mkmakemod.sh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/mkmakemod.sh new file mode 100644 index 00000000..140bf706 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/mkmakemod.sh @@ -0,0 +1,468 @@ +#!/bin/sh +# +# mkmakemod.sh: generate Makefile.in files for module building +# +# Options: +# -m = file is already generated; only build the second stage +# -i = do not build second stage +# +# Args: +# $1 = subdirectory to look in, relative to $top_srcdir +# $2 = final output filename, within the $1 directory +# +# This script must be run from the top-level build directory, and $top_srcdir +# must be set correctly in the environment. +# +# This looks in $1, and uses all the *.mdd files there. Each .mdd file +# defines one module. The .mdd file is actually a shell script, which will +# be sourced. It may define the following shell variables: +# +# name name of this module +# moddeps modules on which this module depends (default none) +# nozshdep non-empty indicates no dependence on the `zsh/main' pseudo-module +# alwayslink if non-empty, always link the module into the executable +# autofeatures features defined by the module, for autoloading +# autofeatures_emu As autofeatures, but for non-zsh emulation modes +# objects .o files making up this module (*must* be defined) +# proto .syms files for this module (default generated from $objects) +# headers extra headers for this module (default none) +# hdrdeps extra headers on which the .mdh depends (default none) +# otherincs extra headers that are included indirectly (default none) +# +# The .mdd file may also include a Makefile.in fragment between lines +# `:<<\Make' and `Make' -- this will be copied into Makemod.in. +# +# The resulting Makemod.in knows how to build each module that is defined. +# For each module it also knows how to build a .mdh file. Each source file +# should #include the .mdh file for the module it is a part of. The .mdh +# file #includes the .mdh files for any module dependencies, then each of +# $headers, and then each .epro (for global declarations). It will +# be recreated if any of the dependency .mdh files changes, or if any of +# $headers or $hdrdeps changes. When anything depends on it, all the .epros +# and $otherincs will be made up to date, but the .mdh file won't actually +# be rebuilt if those files change. +# +# The order of sections of the output file is thus: +# simple generated macros +# macros generated from *.mdd +# included Makemod.in.in +# rules generated from *.mdd +# The order dependencies are basically that the generated macros are required +# in Makemod.in.in, but some of the macros that it creates are needed in the +# later rules. +# + +# sed script to normalise a pathname +sed_normalise=' + s,^,/, + s,$,/, + :1 + s,/\./,/, + t1 + :2 + s,/[^/.][^/]*/\.\./,/, + s,/\.[^/.][^/]*/\.\./,/, + s,/\.\.[^/][^/]*/\.\./,/, + t2 + s,^/$,., + s,^/,, + s,\(.\)/$,\1, +' + +# decide which stages to process +first_stage=true +second_stage=true +if test ."$1" = .-m; then + shift + first_stage=false +elif test ."$1" = .-i; then + shift + second_stage=false +fi + +top_srcdir=`echo $top_srcdir | sed "$sed_normalise"` +the_subdir=$1 +the_makefile=$2 + +if $first_stage; then + + dir_top=`echo $the_subdir | sed 's,[^/][^/]*,..,g'` + + trap "rm -f $the_subdir/${the_makefile}.in; exit 1" 1 2 15 + echo "creating $the_subdir/${the_makefile}.in" + exec 3>&1 >$the_subdir/${the_makefile}.in + echo "##### ${the_makefile}.in generated automatically by mkmakemod.sh" + echo "##### DO NOT EDIT!" + echo + echo "##### ===== DEFINITIONS ===== #####" + echo + echo "makefile = ${the_makefile}" + echo "dir_top = ${dir_top}" + echo "subdir = ${the_subdir}" + echo + + bin_mods=`grep link=static ./config.modules | \ + sed -e '/^#/d' -e 's/ .*/ /' -e 's/^name=/ /'` + dyn_mods="`grep link=dynamic ./config.modules | \ + sed -e '/^#/d' -e 's/ .*/ /' -e 's/^name=/ /'`" + module_list="${bin_mods}${dyn_mods}" + + if grep '^#define DYNAMIC ' config.h >/dev/null; then + is_dynamic=true + else + is_dynamic=false + fi + + here_mddnames= + all_subdirs= + all_modobjs= + all_modules= + all_mdds= + all_mdhs= + all_proto= + lastsub=// + for module in $module_list; do + modfile="`grep '^name='$module' ' ./config.modules | \ + sed -e 's/^.* modfile=//' -e 's/ .*//'`" + case $modfile in + $the_subdir/$lastsub/*) ;; + $the_subdir/*/*) + lastsub=`echo $modfile | sed 's,^'$the_subdir'/,,;s,/[^/]*$,,'` + case "$all_subdirs " in + *" $lastsub "* ) ;; + * ) + all_subdirs="$all_subdirs $lastsub" + ;; + esac + ;; + $the_subdir/*) + mddname=`echo $modfile | sed 's,^.*/,,;s,\.mdd$,,'` + here_mddnames="$here_mddnames $mddname" + build=$is_dynamic + case $is_dynamic@$bin_mods in + *" $module "*) + build=true + all_modobjs="$all_modobjs modobjs.${mddname}" ;; + true@*) + all_modules="$all_modules ${mddname}.\$(DL_EXT)" ;; + esac + all_mdds="$all_mdds ${mddname}.mdd" + $build && all_mdhs="$all_mdhs ${mddname}.mdh" + $build && all_proto="$all_proto proto.${mddname}" + ;; + esac + done + echo "MODOBJS =$all_modobjs" + echo "MODULES =$all_modules" + echo "MDDS =$all_mdds" + echo "MDHS =$all_mdhs" + echo "PROTOS =$all_proto" + echo "SUBDIRS =$all_subdirs" + echo + echo "ENTRYOBJ = \$(dir_src)/modentry..o" + echo "NNTRYOBJ =" + echo "ENTRYOPT = -emodentry" + echo "NNTRYOPT =" + echo + + echo "##### ===== INCLUDING Makemod.in.in ===== #####" + echo + cat $top_srcdir/Src/Makemod.in.in + echo + + case $the_subdir in + Src) modobjs_sed= ;; + Src/*) modobjs_sed="| sed 's\" \" "`echo $the_subdir | sed 's,^Src/,,'`"/\"g' " ;; + *) modobjs_sed="| sed 's\" \" ../$the_subdir/\"g' " ;; + esac + + other_mdhs= + remote_mdhs= + other_exports= + remote_exports= + other_modules= + remote_modules= + for mddname in $here_mddnames; do + + unset name moddeps nozshdep alwayslink hasexport + unset autofeatures autofeatures_emu + unset objects proto headers hdrdeps otherincs + . $top_srcdir/$the_subdir/${mddname}.mdd + q_name=`echo $name | sed 's,Q,Qq,g;s,_,Qu,g;s,/,Qs,g'` + test -n "${moddeps+set}" || moddeps= + test -n "$nozshdep" || moddeps="$moddeps zsh/main" + test -n "${proto+set}" || + proto=`echo $objects '' | sed 's,\.o ,.syms ,g'` + + dobjects=`echo $objects '' | sed 's,\.o ,..o ,g'` + modhdeps= + mododeps= + exportdeps= + imports= + q_moddeps= + for dep in $moddeps; do + depfile="`grep '^name='$dep' ' ./config.modules | \ + sed -e 's/^.* modfile=//' -e 's/ .*//'`" + q_dep=`echo $dep | sed 's,Q,Qq,g;s,_,Qu,g;s,/,Qs,g'` + q_moddeps="$q_moddeps $q_dep" + eval `echo $depfile | sed 's,/\([^/]*\)\.mdd$,;depbase=\1,;s,^,loc=,'` + case "$binmod" in + *" $dep "* ) + dep=zsh/main + ;; + esac + + case $the_subdir in + $loc) + mdh="${depbase}.mdh" + export="${depbase}.export" + case "$dep" in + zsh/main ) + mdll="\$(dir_top)/Src/libzsh-\$(VERSION).\$(DL_EXT) " + ;; + * ) + mdll="${depbase}.\$(DL_EXT) " + ;; + esac + ;; + $loc/*) + mdh="\$(dir_top)/$loc/${depbase}.mdh" + case "$other_mdhs " in + *" $mdh "*) ;; + *) other_mdhs="$other_mdhs $mdh" ;; + esac + export="\$(dir_top)/$loc/${depbase}.export" + case "$other_exports " in + *" $export "*) ;; + *) other_exports="$other_exports $export" ;; + esac + case "$dep" in + zsh/main ) + mdll="\$(dir_top)/Src/libzsh-\$(VERSION).\$(DL_EXT) " + ;; + * ) + mdll="\$(dir_top)/$loc/${depbase}.\$(DL_EXT) " + ;; + esac + case "$other_modules " in + *" $mdll "*) ;; + *) other_modules="$other_modules $mdll" ;; + esac + ;; + *) + mdh="\$(dir_top)/$loc/${depbase}.mdh" + case "$remote_mdhs " in + *" $mdh "*) ;; + *) remote_mdhs="$remote_mdhs $mdh" ;; + esac + export="\$(dir_top)/$loc/${depbase}.export" + case "$remote_exports " in + *" $export "*) ;; + *) remote_exports="$remote_exports $export" ;; + esac + case "$dep" in + zsh/main ) + mdll="\$(dir_top)/Src/libzsh-\$(VERSION).\$(DL_EXT) " + ;; + * ) + mdll="\$(dir_top)/$loc/${depbase}.\$(DL_EXT) " + ;; + esac + case "$remote_modules " in + *" $mdll "*) ;; + *) remote_modules="$remote_modules $mdll" ;; + esac + ;; + esac + modhdeps="$modhdeps $mdh" + exportdeps="$exportdeps $export" + imports="$imports \$(IMPOPT)$export" + case "$mododeps " in + *" $mdll "* ) + : + ;; + * ) + mododeps="$mododeps $mdll" + ;; + esac + done + + echo "##### ===== DEPENDENCIES GENERATED FROM ${mddname}.mdd ===== #####" + echo + echo "MODOBJS_${mddname} = $objects" + echo "MODDOBJS_${mddname} = $dobjects \$(@E@NTRYOBJ)" + echo "SYMS_${mddname} = $proto" + echo "EPRO_${mddname} = "`echo $proto '' | sed 's,\.syms ,.epro ,g'` + echo "INCS_${mddname} = \$(EPRO_${mddname}) $otherincs" + echo "EXPIMP_${mddname} = $imports \$(EXPOPT)$mddname.export" + echo "NXPIMP_${mddname} =" + echo "LINKMODS_${mddname} = $mododeps" + echo "NOLINKMODS_${mddname} = " + echo + echo "proto.${mddname}: \$(EPRO_${mddname})" + echo "\$(SYMS_${mddname}): \$(PROTODEPS)" + echo + echo "${mddname}.export: \$(SYMS_${mddname})" + echo " @( echo '#!'; cat \$(SYMS_${mddname}) | sed -n '/^X/{s/^X//;p;}' | sort -u ) > \$@" + echo + echo "modobjs.${mddname}: \$(MODOBJS_${mddname})" + echo " @echo '' \$(MODOBJS_${mddname}) $modobjs_sed>> \$(dir_src)/stamp-modobjs.tmp" + echo + if test -z "$alwayslink"; then + case " $all_modules" in *" ${mddname}."*) + echo "install.modules-here: install.modules.${mddname}" + echo "uninstall.modules-here: uninstall.modules.${mddname}" + echo + ;; esac + instsubdir=`echo $name | sed 's,^,/,;s,/[^/]*$,,'` + echo "install.modules.${mddname}: ${mddname}.\$(DL_EXT)" + echo " \$(SHELL) \$(sdir_top)/mkinstalldirs \$(DESTDIR)\$(MODDIR)${instsubdir}" + echo " \$(INSTALL_PROGRAM) \$(STRIPFLAGS) ${mddname}.\$(DL_EXT) \$(DESTDIR)\$(MODDIR)/${name}.\$(DL_EXT)" + echo + echo "uninstall.modules.${mddname}:" + echo " rm -f \$(DESTDIR)\$(MODDIR)/${name}.\$(DL_EXT)" + echo + echo "${mddname}.\$(DL_EXT): \$(MODDOBJS_${mddname}) ${mddname}.export $exportdeps \$(@LINKMODS@_${mddname})" + echo ' rm -f $@' + echo " \$(DLLINK) \$(@E@XPIMP_$mddname) \$(@E@NTRYOPT) \$(MODDOBJS_${mddname}) \$(@LINKMODS@_${mddname}) \$(LIBS) " + echo + fi + echo "${mddname}.mdhi: ${mddname}.mdhs \$(INCS_${mddname})" + echo " @test -f \$@ || echo 'do not delete this file' > \$@" + echo + echo "${mddname}.mdhs: ${mddname}.mdd" + echo " @\$(MAKE) -f \$(makefile) \$(MAKEDEFS) ${mddname}.mdh.tmp" + echo " @if cmp -s ${mddname}.mdh ${mddname}.mdh.tmp; then \\" + echo " rm -f ${mddname}.mdh.tmp; \\" + echo " echo \"\\\`${mddname}.mdh' is up to date.\"; \\" + echo " else \\" + echo " mv -f ${mddname}.mdh.tmp ${mddname}.mdh; \\" + echo " echo \"Updated \\\`${mddname}.mdh'.\"; \\" + echo " fi" + echo " echo 'timestamp for ${mddname}.mdh against ${mddname}.mdd' > \$@" + echo + echo "${mddname}.mdh: ${modhdeps} ${headers} ${hdrdeps} ${mddname}.mdhi" + echo " @\$(MAKE) -f \$(makefile) \$(MAKEDEFS) ${mddname}.mdh.tmp" + echo " @mv -f ${mddname}.mdh.tmp ${mddname}.mdh" + echo " @echo \"Updated \\\`${mddname}.mdh'.\"" + echo + echo "${mddname}.mdh.tmp:" + echo " @( \\" + echo " echo '#ifndef have_${q_name}_module'; \\" + echo " echo '#define have_${q_name}_module'; \\" + echo " echo; \\" + echo " echo '# ifndef IMPORTING_MODULE_${q_name}'; \\" + echo " if test @SHORTBOOTNAMES@ = yes; then \\" + echo " echo '# ifndef MODULE'; \\" + echo " fi; \\" + echo " echo '# define boot_ boot_${q_name}'; \\" + echo " echo '# define cleanup_ cleanup_${q_name}'; \\" + echo " echo '# define features_ features_${q_name}'; \\" + echo " echo '# define enables_ enables_${q_name}'; \\" + echo " echo '# define setup_ setup_${q_name}'; \\" + echo " echo '# define finish_ finish_${q_name}'; \\" + echo " if test @SHORTBOOTNAMES@ = yes; then \\" + echo " echo '# endif /* !MODULE */'; \\" + echo " fi; \\" + echo " echo '# endif /* !IMPORTING_MODULE_${q_name} */'; \\" + echo " echo; \\" + if test -n "$moddeps"; then ( + set x $q_moddeps + echo " echo '/* Module dependencies */'; \\" + for hdep in $modhdeps; do + shift + echo " echo '# define IMPORTING_MODULE_${1} 1'; \\" + echo " echo '# include \"${hdep}\"'; \\" + done + echo " echo; \\" + ) fi + if test -n "$headers"; then + echo " echo '/* Extra headers for this module */'; \\" + echo " for hdr in $headers; do \\" + echo " echo '# include \"'\$\$hdr'\"'; \\" + echo " done; \\" + echo " echo; \\" + fi + if test -n "$proto"; then + echo " echo '# undef mod_import_variable'; \\" + echo " echo '# undef mod_import_function'; \\" + echo " echo '# if defined(IMPORTING_MODULE_${q_name}) && defined(MODULE)'; \\" + echo " echo '# define mod_import_variable @MOD_IMPORT_VARIABLE@'; \\" + echo " echo '# define mod_import_function @MOD_IMPORT_FUNCTION@'; \\" + echo " echo '# else'; \\" + echo " echo '# define mod_import_function'; \\" + echo " echo '# define mod_import_variable'; \\" + echo " echo '# endif /* IMPORTING_MODULE_${q_name} && MODULE */'; \\" + echo " for epro in \$(EPRO_${mddname}); do \\" + echo " echo '# include \"'\$\$epro'\"'; \\" + echo " done; \\" + echo " echo '# undef mod_import_variable'; \\" + echo " echo '# define mod_import_variable'; \\" + echo " echo '# undef mod_import_variable'; \\" + echo " echo '# define mod_import_variable'; \\" + echo " echo '# ifndef mod_export'; \\" + echo " echo '# define mod_export @MOD_EXPORT@'; \\" + echo " echo '# endif /* mod_export */'; \\" + echo " echo; \\" + fi + echo " echo '#endif /* !have_${q_name}_module */'; \\" + echo " ) > \$@" + echo + echo "\$(MODOBJS_${mddname}) \$(MODDOBJS_${mddname}): ${mddname}.mdh" + sed -e '/^ *: *<< *\\Make *$/,/^Make$/!d' \ + -e 's/^ *: *<< *\\Make *$//; /^Make$/d' \ + < $top_srcdir/$the_subdir/${mddname}.mdd + echo + + done + + if test -n "$remote_mdhs$other_mdhs$remote_exports$other_exports$remote_modules$other_modules"; then + echo "##### ===== DEPENDENCIES FOR REMOTE MODULES ===== #####" + echo + for mdh in $remote_mdhs; do + echo "$mdh: FORCE" + echo " @cd @%@ && \$(MAKE) \$(MAKEDEFS) @%@$mdh" + echo + done | sed 's,^\(.*\)@%@\(.*\)@%@\(.*\)/\([^/]*\)$,\1\3\2\4,' + if test -n "$other_mdhs"; then + echo "${other_mdhs}:" | sed 's,^ ,,' + echo " false # A. should only happen with make -n" + echo + fi + for export in $remote_exports; do + echo "$export: FORCE" + echo " @cd @%@ && \$(MAKE) \$(MAKEDEFS) @%@$export" + echo + done | sed 's,^\(.*\)@%@\(.*\)@%@\(.*\)/\([^/]*\)$,\1\3\2\4,' + if test -n "$other_exports"; then + echo "${other_exports}:" | sed 's,^ ,,' + echo " false # B. should only happen with make -n" + echo + fi + for mdll in $remote_modules; do + echo "$mdll: FORCE" + echo " @cd @%@ && \$(MAKE) \$(MAKEDEFS) @%@$mdll" + echo + done | sed 's,^\(.*\)@%@\(.*\)@%@\(.*\)/\([^/]*\)$,\1\3\2\4,' + if test -n "$other_modules"; then + echo "${other_modules}:" | sed 's,^ ,,' + echo " false # C. should only happen with make -n" + echo + fi + fi + + echo "##### End of ${the_makefile}.in" + + exec >&3 3>&- + +fi + +if $second_stage ; then + trap "rm -f $the_subdir/${the_makefile}; exit 1" 1 2 15 + + ${CONFIG_SHELL-/bin/sh} ./config.status \ + --file=$the_subdir/${the_makefile}:$the_subdir/${the_makefile}.in || + exit 1 +fi + +exit 0 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/module.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/module.c new file mode 100644 index 00000000..4ae78310 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/module.c @@ -0,0 +1,3641 @@ +/* + * module.c - deal with dynamic modules + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1996-1997 Zoltán Hidvégi + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Zoltán Hidvégi or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Zoltán Hidvégi and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Zoltán Hidvégi and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Zoltán Hidvégi and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + */ + +#include "zsh.mdh" +#include "module.pro" + +/* + * List of linked-in modules. + * This is set up at boot and remains for the life of the shell; + * entries do not appear in "zmodload" listings. + */ + +/**/ +LinkList linkedmodules; + +/* $module_path ($MODULE_PATH) */ + +/**/ +char **module_path; + +/* Hash of modules */ + +/**/ +mod_export HashTable modulestab; + +/* + * Bit flags passed as the "flags" argument of a autofeaturefn_t. + * Used in other places, such as the final argument to + * do_module_features(). + */ +enum { + /* + * `-i' option: ignore errors pertaining to redefinitions, + * or indicate to do_module_features() that it should be + * silent. + */ + FEAT_IGNORE = 0x0001, + /* If a condition, condition is infix rather than prefix */ + FEAT_INFIX = 0x0002, + /* + * Enable all features in the module when autoloading. + * This is the traditional zmodload -a behaviour; + * zmodload -Fa only enables features explicitly marked for + * autoloading. + */ + FEAT_AUTOALL = 0x0004, + /* + * Remove feature: alternative to "-X:NAME" used if + * X is passed separately from NAME. + */ + FEAT_REMOVE = 0x0008, + /* + * For do_module_features(). Check that any autoloads + * for the module are actually provided. + */ + FEAT_CHECKAUTO = 0x0010 +}; + +/* + * All functions to add or remove autoloadable features fit + * the following prototype. + * + * "module" is the name of the module. + * + * "feature" is the name of the feature, minus any type prefix. + * + * "flags" is a set of the bits above. + * + * The return value is 0 for success, -1 for failure with no + * message needed, and one of the following to indicate the calling + * function should print a message: + * + * 1: failed to add [type] `[feature]' + * 2: [feature]: no such [type] + * 3: [feature]: [type] is already defined + */ +typedef int (*autofeaturefn_t)(const char *module, const char *feature, + int flags); + +/* Bits in the second argument to find_module. */ +enum { + /* + * Resolve any aliases to the underlying module. + */ + FINDMOD_ALIASP = 0x0001, + /* + * Create an element for the module in the list if + * it is not found. + */ + FINDMOD_CREATE = 0x0002, +}; + +static void +freemodulenode(HashNode hn) +{ + Module m = (Module) hn; + + if (m->node.flags & MOD_ALIAS) + zsfree(m->u.alias); + zsfree(m->node.nam); + if (m->autoloads) + freelinklist(m->autoloads, freestr); + if (m->deps) + freelinklist(m->deps, freestr); + zfree(m, sizeof(*m)); +} + +/* flags argument to printmodulenode */ +enum { + /* -L flag, output zmodload commands */ + PRINTMOD_LIST = 0x0001, + /* -e flag */ + PRINTMOD_EXIST = 0x0002, + /* -A flag */ + PRINTMOD_ALIAS = 0x0004, + /* -d flag */ + PRINTMOD_DEPS = 0x0008, + /* -F flag */ + PRINTMOD_FEATURES = 0x0010, + /* -l flag in combination with -L flag */ + PRINTMOD_LISTALL = 0x0020, + /* -a flag */ + PRINTMOD_AUTO = 0x0040 +}; + +/* Scan function for printing module details */ + +static void +printmodulenode(HashNode hn, int flags) +{ + Module m = (Module)hn; + /* + * If we check for a module loaded under an alias, we + * need the name of the alias. We can use it in other + * cases, too. + */ + const char *modname = m->node.nam; + + if (flags & PRINTMOD_DEPS) { + /* + * Print the module's dependencies. + */ + LinkNode n; + + if (!m->deps) + return; + + if (flags & PRINTMOD_LIST) { + printf("zmodload -d "); + if (modname[0] == '-') + fputs("-- ", stdout); + quotedzputs(modname, stdout); + } else { + nicezputs(modname, stdout); + putchar(':'); + } + for (n = firstnode(m->deps); n; incnode(n)) { + putchar(' '); + if (flags & PRINTMOD_LIST) + quotedzputs((char *) getdata(n), stdout); + else + nicezputs((char *) getdata(n), stdout); + } + } else if (flags & PRINTMOD_EXIST) { + /* + * Just print the module name, provided the module is + * present under an alias or otherwise. + */ + if (m->node.flags & MOD_ALIAS) { + if (!(flags & PRINTMOD_ALIAS) || + !(m = find_module(m->u.alias, FINDMOD_ALIASP, NULL))) + return; + } + if (!m->u.handle || (m->node.flags & MOD_UNLOAD)) + return; + nicezputs(modname, stdout); + } else if (m->node.flags & MOD_ALIAS) { + /* + * Normal listing, but for aliases. + */ + if (flags & PRINTMOD_LIST) { + printf("zmodload -A "); + if (modname[0] == '-') + fputs("-- ", stdout); + quotedzputs(modname, stdout); + putchar('='); + quotedzputs(m->u.alias, stdout); + } else { + nicezputs(modname, stdout); + fputs(" -> ", stdout); + nicezputs(m->u.alias, stdout); + } + } else if (m->u.handle || (flags & PRINTMOD_AUTO)) { + /* + * Loaded module. + */ + if (flags & PRINTMOD_LIST) { + /* + * List with -L format. Possibly we are printing + * features, either enables or autoloads. + */ + char **features = NULL; + int *enables = NULL; + if (flags & PRINTMOD_AUTO) { + if (!m->autoloads || !firstnode(m->autoloads)) + return; + } else if (flags & PRINTMOD_FEATURES) { + if (features_module(m, &features) || + enables_module(m, &enables) || + !*features) + return; + } + printf("zmodload "); + if (flags & PRINTMOD_AUTO) { + fputs("-Fa ", stdout); + } else if (features) + fputs("-F ", stdout); + if(modname[0] == '-') + fputs("-- ", stdout); + quotedzputs(modname, stdout); + if (flags & PRINTMOD_AUTO) { + LinkNode an; + for (an = firstnode(m->autoloads); an; incnode(an)) { + putchar(' '); + quotedzputs((char *)getdata(an), stdout); + } + } else if (features) { + const char *f; + while ((f = *features++)) { + int on = *enables++; + if (flags & PRINTMOD_LISTALL) + printf(" %s", on ? "+" : "-"); + else if (!on) + continue; + else + putchar(' '); + quotedzputs(f, stdout); + } + } + } else /* -l */ + nicezputs(modname, stdout); + } else + return; + putchar('\n'); +} + +/**/ +HashTable +newmoduletable(int size, char const *name) +{ + HashTable ht; + ht = newhashtable(size, name, NULL); + + ht->hash = hasher; + ht->emptytable = emptyhashtable; + ht->filltable = NULL; + ht->cmpnodes = strcmp; + ht->addnode = addhashnode; + /* DISABLED is not supported */ + ht->getnode = gethashnode2; + ht->getnode2 = gethashnode2; + ht->removenode = removehashnode; + ht->disablenode = NULL; + ht->enablenode = NULL; + ht->freenode = freemodulenode; + ht->printnode = printmodulenode; + + return ht; +} + +/************************************************************************ + * zsh/main standard module functions + ************************************************************************/ + +/* The `zsh/main' module contains all the base code that can't actually be * + * built as a separate module. It is initialised by main(), so there's * + * nothing for the boot function to do. */ + +/**/ +int +setup_(UNUSED(Module m)) +{ + return 0; +} + +/**/ +int +features_(UNUSED(Module m), UNUSED(char ***features)) +{ + /* + * There are lots and lots of features, but they're not + * handled here. + */ + return 1; +} + +/**/ +int +enables_(UNUSED(Module m), UNUSED(int **enables)) +{ + return 1; +} + +/**/ +int +boot_(UNUSED(Module m)) +{ + return 0; +} + +/**/ +int +cleanup_(UNUSED(Module m)) +{ + return 0; +} + +/**/ +int +finish_(UNUSED(Module m)) +{ + return 0; +} + + +/************************************************************************ + * Module utility functions + ************************************************************************/ + +/* This registers a builtin module. */ + +/**/ +void +register_module(char *n, Module_void_func setup, + Module_features_func features, + Module_enables_func enables, + Module_void_func boot, + Module_void_func cleanup, + Module_void_func finish) +{ + Linkedmod m; + + m = (Linkedmod) zalloc(sizeof(*m)); + + m->name = ztrdup(n); + m->setup = setup; + m->features = features; + m->enables = enables; + m->boot = boot; + m->cleanup = cleanup; + m->finish = finish; + + zaddlinknode(linkedmodules, m); +} + +/* Check if a module is linked in. */ + +/**/ +Linkedmod +module_linked(char const *name) +{ + LinkNode node; + + for (node = firstnode(linkedmodules); node; incnode(node)) + if (!strcmp(((Linkedmod) getdata(node))->name, name)) + return (Linkedmod) getdata(node); + + return NULL; +} + + +/************************************************************************ + * Support for the various feature types. + * First, builtins. + ************************************************************************/ + +/* addbuiltin() can be used to add a new builtin. It returns zero on * + * success, 1 on failure. The only possible type of failure is that * + * a builtin with the specified name already exists. An autoloaded * + * builtin can be replaced using this function. */ + +/**/ +static int +addbuiltin(Builtin b) +{ + Builtin bn = (Builtin) builtintab->getnode2(builtintab, b->node.nam); + if (bn && (bn->node.flags & BINF_ADDED)) + return 1; + if (bn) + builtintab->freenode(builtintab->removenode(builtintab, b->node.nam)); + builtintab->addnode(builtintab, b->node.nam, b); + return 0; +} + +/* Define an autoloadable builtin. It returns 0 on success, or 1 on * + * failure. The only possible cause of failure is that a builtin * + * with the specified name already exists. */ + +/**/ +static int +add_autobin(const char *module, const char *bnam, int flags) +{ + Builtin bn; + int ret; + + bn = zshcalloc(sizeof(*bn)); + bn->node.nam = ztrdup(bnam); + bn->optstr = ztrdup(module); + if (flags & FEAT_AUTOALL) + bn->node.flags |= BINF_AUTOALL; + if ((ret = addbuiltin(bn))) { + builtintab->freenode(&bn->node); + if (!(flags & FEAT_IGNORE)) + return 1; + } + return 0; +} + +/* Remove the builtin added previously by addbuiltin(). Returns * + * zero on succes and -1 if there is no builtin with that name. */ + +/**/ +int +deletebuiltin(const char *nam) +{ + Builtin bn; + + bn = (Builtin) builtintab->removenode(builtintab, nam); + if (!bn) + return -1; + builtintab->freenode(&bn->node); + return 0; +} + +/* Remove an autoloaded added by add_autobin */ + +/**/ +static int +del_autobin(UNUSED(const char *module), const char *bnam, int flags) +{ + Builtin bn = (Builtin) builtintab->getnode2(builtintab, bnam); + if (!bn) { + if(!(flags & FEAT_IGNORE)) + return 2; + } else if (bn->node.flags & BINF_ADDED) { + if (!(flags & FEAT_IGNORE)) + return 3; + } else + deletebuiltin(bnam); + + return 0; +} + +/* + * Manipulate a set of builtins. This should be called + * via setfeatureenables() (or, usually, via the next level up, + * handlefeatures()). + * + * "nam" is the name of the calling code builtin, probably "zmodload". + * + * "binl" is the builtin table containing an array of "size" builtins. + * + * "e" is either NULL, in which case all builtins in the + * table are removed, or else an array corresponding to "binl" + * with a 1 for builtins that are to be added and a 0 for builtins + * that are to be removed. Any builtin already in the appropriate + * state is left alone. + * + * Returns 1 on any error, 0 for success. The recommended way + * of handling errors is to compare the enables passed down + * with the set retrieved after the error to find what failed. + */ + +/**/ +static int +setbuiltins(char const *nam, Builtin binl, int size, int *e) +{ + int ret = 0, n; + + for(n = 0; n < size; n++) { + Builtin b = &binl[n]; + if (e && *e++) { + if (b->node.flags & BINF_ADDED) + continue; + if (addbuiltin(b)) { + zwarnnam(nam, + "name clash when adding builtin `%s'", b->node.nam); + ret = 1; + } else { + b->node.flags |= BINF_ADDED; + } + } else { + if (!(b->node.flags & BINF_ADDED)) + continue; + if (deletebuiltin(b->node.nam)) { + zwarnnam(nam, "builtin `%s' already deleted", b->node.nam); + ret = 1; + } else { + b->node.flags &= ~BINF_ADDED; + } + } + } + return ret; +} + +/* + * Add multiple builtins. binl points to a table of `size' builtin + * structures. Those for which (.flags & BINF_ADDED) is false are to be + * added; that flag is set if they succeed. + * + * If any fail, an error message is printed, using nam as the leading name. + * Returns 0 on success, 1 for any failure. + * + * This should not be used from a module; instead, use handlefeatures(). + */ + +/**/ +mod_export int +addbuiltins(char const *nam, Builtin binl, int size) +{ + int ret = 0, n; + + for(n = 0; n < size; n++) { + Builtin b = &binl[n]; + if(b->node.flags & BINF_ADDED) + continue; + if(addbuiltin(b)) { + zwarnnam(nam, "name clash when adding builtin `%s'", b->node.nam); + ret = 1; + } else { + b->node.flags |= BINF_ADDED; + } + } + return ret; +} + + +/************************************************************************ + * Function wrappers. + ************************************************************************/ + +/* The list of function wrappers defined. */ + +/**/ +FuncWrap wrappers; + +/* This adds a definition for a wrapper. Return value is one in case of * + * error and zero if all went fine. */ + +/**/ +mod_export int +addwrapper(Module m, FuncWrap w) +{ + FuncWrap p, q; + + /* + * We can't add a wrapper to an alias, since it's supposed + * to behave identically to the resolved module. This shouldn't + * happen since we usually add wrappers when a real module is + * loaded. + */ + if (m->node.flags & MOD_ALIAS) + return 1; + + if (w->flags & WRAPF_ADDED) + return 1; + for (p = wrappers, q = NULL; p; q = p, p = p->next); + if (q) + q->next = w; + else + wrappers = w; + w->next = NULL; + w->flags |= WRAPF_ADDED; + w->module = m; + + return 0; +} + +/* This removes the given wrapper definition from the list. Returned is * + * one in case of error and zero otherwise. */ + +/**/ +mod_export int +deletewrapper(Module m, FuncWrap w) +{ + FuncWrap p, q; + + if (m->node.flags & MOD_ALIAS) + return 1; + + if (w->flags & WRAPF_ADDED) { + for (p = wrappers, q = NULL; p && p != w; q = p, p = p->next); + + if (p) { + if (q) + q->next = p->next; + else + wrappers = p->next; + p->flags &= ~WRAPF_ADDED; + + return 0; + } + } + return 1; +} + + +/************************************************************************ + * Conditions. + ************************************************************************/ + +/* The list of module-defined conditions. */ + +/**/ +mod_export Conddef condtab; + +/* This gets a condition definition with the given name. The first * + * argument says if we have to look for an infix condition. The last * + * argument is non-zero if we should autoload modules if needed. */ + +/**/ +Conddef +getconddef(int inf, const char *name, int autol) +{ + Conddef p; + int f = 1; + char *lookup, *s; + + /* detokenize the Dash to the form encoded in lookup tables */ + lookup = dupstring(name); + if (!lookup) + return NULL; + for (s = lookup; *s != '\0'; s++) { + if (*s == Dash) + *s = '-'; + } + + do { + for (p = condtab; p; p = p->next) { + if ((!!inf == !!(p->flags & CONDF_INFIX)) && + !strcmp(lookup, p->name)) + break; + } + if (autol && p && p->module) { + /* + * This is a definition for an autoloaded condition; load the + * module if we haven't tried that already. + */ + if (f) { + (void)ensurefeature(p->module, + (p->flags & CONDF_INFIX) ? "C:" : "c:", + (p->flags & CONDF_AUTOALL) ? NULL : lookup); + f = 0; + p = NULL; + } else { + deleteconddef(p); + return NULL; + } + } else + break; + } while (!p); + + return p; +} + +/* + * This adds the given condition definition. The return value is zero on * + * success and 1 on failure. If there is a matching definition for an * + * autoloaded condition, it is removed. + * + * This is used for adding both an autoload definition or + * a real condition. In the latter case the caller is responsible + * for setting the CONDF_ADDED flag. + */ + +/**/ +static int +addconddef(Conddef c) +{ + Conddef p = getconddef((c->flags & CONDF_INFIX), c->name, 0); + + if (p) { + if (!p->module || (p->flags & CONDF_ADDED)) + return 1; + /* There is an autoload definition. */ + + deleteconddef(p); + } + c->next = condtab; + condtab = c; + return 0; +} + +/* This removes the given condition definition from the list(s). If this * + * is a definition for a autoloaded condition, the memory is freed. */ + +/**/ +int +deleteconddef(Conddef c) +{ + Conddef p, q; + + for (p = condtab, q = NULL; p && p != c; q = p, p = p->next); + + if (p) { + if (q) + q->next = p->next; + else + condtab = p->next; + + if (p->module) { + /* autoloaded, free it */ + zsfree(p->name); + zsfree(p->module); + zfree(p, sizeof(*p)); + } + return 0; + } + return -1; +} + +/* + * Add or remove sets of conditions. The interface is + * identical to setbuiltins(). + */ + +/**/ +static int +setconddefs(char const *nam, Conddef c, int size, int *e) +{ + int ret = 0; + + while (size--) { + if (e && *e++) { + if (c->flags & CONDF_ADDED) { + c++; + continue; + } + if (addconddef(c)) { + zwarnnam(nam, "name clash when adding condition `%s'", + c->name); + ret = 1; + } else { + c->flags |= CONDF_ADDED; + } + } else { + if (!(c->flags & CONDF_ADDED)) { + c++; + continue; + } + if (deleteconddef(c)) { + zwarnnam(nam, "condition `%s' already deleted", c->name); + ret = 1; + } else { + c->flags &= ~CONDF_ADDED; + } + } + c++; + } + return ret; +} + +/* This adds a definition for autoloading a module for a condition. */ + +/**/ +static int +add_autocond(const char *module, const char *cnam, int flags) +{ + Conddef c; + + c = (Conddef) zalloc(sizeof(*c)); + + c->name = ztrdup(cnam); + c->flags = ((flags & FEAT_INFIX) ? CONDF_INFIX : 0); + if (flags & FEAT_AUTOALL) + c->flags |= CONDF_AUTOALL; + c->module = ztrdup(module); + + if (addconddef(c)) { + zsfree(c->name); + zsfree(c->module); + zfree(c, sizeof(*c)); + + if (!(flags & FEAT_IGNORE)) + return 1; + } + return 0; +} + +/* Remove a condition added with add_autocond */ + +/**/ +static int +del_autocond(UNUSED(const char *modnam), const char *cnam, int flags) +{ + Conddef cd = getconddef((flags & FEAT_INFIX) ? 1 : 0, cnam, 0); + + if (!cd) { + if (!(flags & FEAT_IGNORE)) { + return 2; + } + } else if (cd->flags & CONDF_ADDED) { + if (!(flags & FEAT_IGNORE)) + return 3; + } else + deleteconddef(cd); + + return 0; +} + +/************************************************************************ + * Hook functions. + ************************************************************************/ + +/* This list of hook functions defined. */ + +/**/ +Hookdef hooktab; + +/* Find a hook definition given the name. */ + +/**/ +Hookdef +gethookdef(char *n) +{ + Hookdef p; + + for (p = hooktab; p; p = p->next) + if (!strcmp(n, p->name)) + return p; + return NULL; +} + +/* This adds the given hook definition. The return value is zero on * + * success and 1 on failure. */ + +/**/ +int +addhookdef(Hookdef h) +{ + if (gethookdef(h->name)) + return 1; + + h->next = hooktab; + hooktab = h; + h->funcs = znewlinklist(); + + return 0; +} + +/* + * This adds multiple hook definitions. This is like addbuiltins(). + * This allows a NULL module because we call it from init.c. + */ + +/**/ +mod_export int +addhookdefs(Module m, Hookdef h, int size) +{ + int ret = 0; + + while (size--) { + if (addhookdef(h)) { + zwarnnam(m ? m->node.nam : NULL, + "name clash when adding hook `%s'", h->name); + ret = 1; + } + h++; + } + return ret; +} + +/* Delete hook definitions. */ + +/**/ +int +deletehookdef(Hookdef h) +{ + Hookdef p, q; + + for (p = hooktab, q = NULL; p && p != h; q = p, p = p->next); + + if (!p) + return 1; + + if (q) + q->next = p->next; + else + hooktab = p->next; + freelinklist(p->funcs, NULL); + return 0; +} + +/* Remove multiple hook definitions. */ + +/**/ +mod_export int +deletehookdefs(UNUSED(Module m), Hookdef h, int size) +{ + int ret = 0; + + while (size--) { + if (deletehookdef(h)) + ret = 1; + h++; + } + return ret; +} + +/* Add a function to a hook. */ + +/**/ +int +addhookdeffunc(Hookdef h, Hookfn f) +{ + zaddlinknode(h->funcs, (void *) f); + + return 0; +} + +/**/ +mod_export int +addhookfunc(char *n, Hookfn f) +{ + Hookdef h = gethookdef(n); + + if (h) + return addhookdeffunc(h, f); + return 1; +} + +/* Delete a function from a hook. */ + +/**/ +int +deletehookdeffunc(Hookdef h, Hookfn f) +{ + LinkNode p; + + for (p = firstnode(h->funcs); p; incnode(p)) + if (f == (Hookfn) getdata(p)) { + remnode(h->funcs, p); + return 0; + } + return 1; +} + +/* Delete a hook. */ + +/**/ +mod_export int +deletehookfunc(char *n, Hookfn f) +{ + Hookdef h = gethookdef(n); + + if (h) + return deletehookdeffunc(h, f); + return 1; +} + +/* Run the function(s) for a hook. */ + +/**/ +mod_export int +runhookdef(Hookdef h, void *d) +{ + if (empty(h->funcs)) { + if (h->def) + return h->def(h, d); + return 0; + } else if (h->flags & HOOKF_ALL) { + LinkNode p; + int r; + + for (p = firstnode(h->funcs); p; incnode(p)) + if ((r = ((Hookfn) getdata(p))(h, d))) + return r; + if (h->def) + return h->def(h, d); + return 0; + } else + return ((Hookfn) getdata(lastnode(h->funcs)))(h, d); +} + + + +/************************************************************************ + * Shell parameters. + ************************************************************************/ + +/* + * Check that it's possible to add a parameter. This + * requires that either there's no parameter already present, + * or it's a global parameter marked for autoloading. + * + * The special status 2 is to indicate it didn't work but + * -i was in use so we didn't print a warning. + */ + +static int +checkaddparam(const char *nam, int opt_i) +{ + Param pm; + + if (!(pm = (Param) gethashnode2(paramtab, nam))) + return 0; + + if (pm->level || !(pm->node.flags & PM_AUTOLOAD)) { + /* + * -i suppresses "it's already that way" warnings, + * but not "this can't possibly work" warnings, so we print + * the message anyway if there's a local parameter blocking + * the parameter we want to add, not if there's a + * non-autoloadable parameter already there. This + * is consistent with the way add_auto* functions work. + */ + if (!opt_i || !pm->level) { + zwarn("Can't add module parameter `%s': %s", + nam, pm->level ? + "local parameter exists" : + "parameter already exists"); + return 1; + } + return 2; + } + + unsetparam_pm(pm, 0, 1); + return 0; +} + +/* This adds the given parameter definition. The return value is zero on * + * success and 1 on failure. */ + +/**/ +int +addparamdef(Paramdef d) +{ + Param pm; + + if (checkaddparam(d->name, 0)) + return 1; + + if (d->getnfn) { + if (!(pm = createspecialhash(d->name, d->getnfn, + d->scantfn, d->flags))) + return 1; + } + else if (!(pm = createparam(d->name, d->flags)) && + !(pm = (Param) paramtab->getnode(paramtab, d->name))) + return 1; + + d->pm = pm; + pm->level = 0; + if (d->var) + pm->u.data = d->var; + if (d->var || d->gsu) { + /* + * If no get/set/unset class, use the appropriate + * variable type, else use the one supplied. + */ + switch (PM_TYPE(pm->node.flags)) { + case PM_SCALAR: + pm->gsu.s = d->gsu ? (GsuScalar)d->gsu : &varscalar_gsu; + break; + + case PM_INTEGER: + pm->gsu.i = d->gsu ? (GsuInteger)d->gsu : &varinteger_gsu; + break; + + case PM_FFLOAT: + case PM_EFLOAT: + pm->gsu.f = d->gsu; + break; + + case PM_ARRAY: + pm->gsu.a = d->gsu ? (GsuArray)d->gsu : &vararray_gsu; + break; + + case PM_HASHED: + /* hashes may behave like standard hashes */ + if (d->gsu) + pm->gsu.h = (GsuHash)d->gsu; + break; + + default: + unsetparam_pm(pm, 0, 1); + return 1; + } + } + + return 0; +} + +/* Delete parameters defined. No error checking yet. */ + +/**/ +int +deleteparamdef(Paramdef d) +{ + Param pm = (Param) paramtab->getnode(paramtab, d->name); + + if (!pm) + return 1; + if (pm != d->pm) { + /* + * See if the parameter has been hidden. If so, + * bring it to the front to unset it. + */ + Param prevpm, searchpm; + for (prevpm = pm, searchpm = pm->old; + searchpm; + prevpm = searchpm, searchpm = searchpm->old) + if (searchpm == d->pm) + break; + + if (!searchpm) + return 1; + + paramtab->removenode(paramtab, pm->node.nam); + prevpm->old = searchpm->old; + searchpm->old = pm; + paramtab->addnode(paramtab, searchpm->node.nam, searchpm); + + pm = searchpm; + } + pm->node.flags = (pm->node.flags & ~PM_READONLY) | PM_REMOVABLE; + unsetparam_pm(pm, 0, 1); + d->pm = NULL; + return 0; +} + +/* + * Add or remove sets of parameters. The interface is + * identical to setbuiltins(). + */ + +/**/ +static int +setparamdefs(char const *nam, Paramdef d, int size, int *e) +{ + int ret = 0; + + while (size--) { + if (e && *e++) { + if (d->pm) { + d++; + continue; + } + if (addparamdef(d)) { + zwarnnam(nam, "error when adding parameter `%s'", d->name); + ret = 1; + } + } else { + if (!d->pm) { + d++; + continue; + } + if (deleteparamdef(d)) { + zwarnnam(nam, "parameter `%s' already deleted", d->name); + ret = 1; + } + } + d++; + } + return ret; +} + +/* This adds a definition for autoloading a module for a parameter. */ + +/**/ +static int +add_autoparam(const char *module, const char *pnam, int flags) +{ + Param pm; + int ret; + + queue_signals(); + if ((ret = checkaddparam(pnam, (flags & FEAT_IGNORE)))) { + unqueue_signals(); + /* + * checkaddparam() has already printed a message if one was + * needed. If it wasn't owing to the presence of -i, ret is 2; + * for consistency with other add_auto* functions we return + * status 0 to indicate there's already such a parameter and + * we've been told not to worry if so. + */ + return ret == 2 ? 0 : -1; + } + + pm = setsparam(dupstring(pnam), ztrdup(module)); + + pm->node.flags |= PM_AUTOLOAD; + if (flags & FEAT_AUTOALL) + pm->node.flags |= PM_AUTOALL; + unqueue_signals(); + + return 0; +} + +/* Remove a parameter added with add_autoparam() */ + +/**/ +static int +del_autoparam(UNUSED(const char *modnam), const char *pnam, int flags) +{ + Param pm = (Param) gethashnode2(paramtab, pnam); + + if (!pm) { + if (!(flags & FEAT_IGNORE)) + return 2; + } else if (!(pm->node.flags & PM_AUTOLOAD)) { + if (!(flags & FEAT_IGNORE)) + return 3; + } else + unsetparam_pm(pm, 0, 1); + + return 0; +} + +/************************************************************************ + * Math functions. + ************************************************************************/ + +/* List of math functions. */ + +/**/ +MathFunc mathfuncs; + +/* + * Remove a single math function form the list (utility function). + * This does not delete a module math function, that's deletemathfunc(). + */ + +/**/ +void +removemathfunc(MathFunc previous, MathFunc current) +{ + if (previous) + previous->next = current->next; + else + mathfuncs = current->next; + + zsfree(current->name); + zsfree(current->module); + zfree(current, sizeof(*current)); +} + +/* Find a math function in the list, handling autoload if necessary. */ + +/**/ +MathFunc +getmathfunc(const char *name, int autol) +{ + MathFunc p, q = NULL; + + for (p = mathfuncs; p; q = p, p = p->next) + if (!strcmp(name, p->name)) { + if (autol && p->module && !(p->flags & MFF_USERFUNC)) { + char *n = dupstring(p->module); + int flags = p->flags; + + removemathfunc(q, p); + + (void)ensurefeature(n, "f:", (flags & MFF_AUTOALL) ? NULL : + name); + + p = getmathfunc(name, 0); + if (!p) { + zerr("autoloading module %s failed to define math function: %s", n, name); + } + } + return p; + } + + return NULL; +} + +/* Add a single math function */ + +/**/ +static int +addmathfunc(MathFunc f) +{ + MathFunc p, q = NULL; + + if (f->flags & MFF_ADDED) + return 1; + + for (p = mathfuncs; p; q = p, p = p->next) + if (!strcmp(f->name, p->name)) { + if (p->module && !(p->flags & MFF_USERFUNC)) { + /* + * Autoloadable, replace. + */ + removemathfunc(q, p); + break; + } + return 1; + } + + f->next = mathfuncs; + mathfuncs = f; + + return 0; +} + +/* Delete a single math function */ + +/**/ +mod_export int +deletemathfunc(MathFunc f) +{ + MathFunc p, q; + + for (p = mathfuncs, q = NULL; p && p != f; q = p, p = p->next); + + if (p) { + if (q) + q->next = f->next; + else + mathfuncs = f->next; + + /* the following applies to both unloaded and user-defined functions */ + if (f->module) { + zsfree(f->name); + zsfree(f->module); + zfree(f, sizeof(*f)); + } else + f->flags &= ~MFF_ADDED; + + return 0; + } + return -1; +} + +/* + * Add or remove sets of math functions. The interface is + * identical to setbuiltins(). + */ + +/**/ +static int +setmathfuncs(char const *nam, MathFunc f, int size, int *e) +{ + int ret = 0; + + while (size--) { + if (e && *e++) { + if (f->flags & MFF_ADDED) { + f++; + continue; + } + if (addmathfunc(f)) { + zwarnnam(nam, "name clash when adding math function `%s'", + f->name); + ret = 1; + } else { + f->flags |= MFF_ADDED; + } + } else { + if (!(f->flags & MFF_ADDED)) { + f++; + continue; + } + if (deletemathfunc(f)) { + zwarnnam(nam, "math function `%s' already deleted", f->name); + ret = 1; + } else { + f->flags &= ~MFF_ADDED; + } + } + f++; + } + return ret; +} + +/* Add an autoload definition for a math function. */ + +/**/ +static int +add_automathfunc(const char *module, const char *fnam, int flags) +{ + MathFunc f; + + f = (MathFunc) zalloc(sizeof(*f)); + + f->name = ztrdup(fnam); + f->module = ztrdup(module); + f->flags = 0; + + if (addmathfunc(f)) { + zsfree(f->name); + zsfree(f->module); + zfree(f, sizeof(*f)); + + if (!(flags & FEAT_IGNORE)) + return 1; + } + + return 0; +} + +/* Remove a math function added with add_automathfunc() */ + +/**/ +static int +del_automathfunc(UNUSED(const char *modnam), const char *fnam, int flags) +{ + MathFunc f = getmathfunc(fnam, 0); + + if (!f) { + if (!(flags & FEAT_IGNORE)) + return 2; + } else if (f->flags & MFF_ADDED) { + if (!(flags & FEAT_IGNORE)) + return 3; + } else + deletemathfunc(f); + + return 0; +} + +/************************************************************************ + * Now support for dynamical loading and the fallback functions + * we use for loading if dynamical loading is not available. + ************************************************************************/ + +/**/ +#ifdef DYNAMIC + +/**/ +#ifdef AIXDYNAMIC + +#include + +static char *dlerrstr[256]; + +static void * +load_and_bind(const char *fn) +{ + void *ret = (void *) load((char *) fn, L_NOAUTODEFER, NULL); + + if (ret) { + Module m; + int i, err = loadbind(0, (void *) addbuiltin, ret); + for (i = 0; i < modulestab->hsize && !err; i++) { + for (m = (Module)modulestab->nodes[i]; m && !err; + m = (Module)m->node.next) { + if (!(m->node.flags & MOD_ALIAS) && + m->u.handle && !(m->node.flags & MOD_LINKED)) + err |= loadbind(0, m->u.handle, ret); + } + } + + if (err) { + loadquery(L_GETMESSAGES, dlerrstr, sizeof(dlerrstr)); + unload(ret); + ret = NULL; + } + } else + loadquery(L_GETMESSAGES, dlerrstr, sizeof(dlerrstr)); + + return ret; +} + +#define dlopen(X,Y) load_and_bind(X) +#define dlclose(X) unload(X) +#define dlerror() (dlerrstr[0]) +#ifndef HAVE_DLERROR +# define HAVE_DLERROR 1 +#endif + +/**/ +#else + +#ifdef HAVE_DLFCN_H +# if defined(HAVE_DL_H) && defined(HPUX10DYNAMIC) +# include +# else +# include +# endif +#else +# ifdef HAVE_DL_H +# include +# define RTLD_LAZY BIND_DEFERRED +# define RTLD_GLOBAL DYNAMIC_PATH +# else +# include +# include +# include +# endif +#endif + +/**/ +#ifdef HPUX10DYNAMIC +# define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +# define dlclose(handle) shl_unload((shl_t)(handle)) + +static +void * +hpux_dlsym(void *handle, char *name) +{ + void *sym_addr; + if (!shl_findsym((shl_t *)&handle, name, TYPE_UNDEFINED, &sym_addr)) + return sym_addr; + return NULL; +} + +# define dlsym(handle,name) hpux_dlsym(handle,name) +# ifdef HAVE_DLERROR /* paranoia */ +# undef HAVE_DLERROR +# endif +#else +# ifndef HAVE_DLCLOSE +# define dlclose(X) ((X), 0) +# endif +/**/ +#endif + +#ifdef DLSYM_NEEDS_UNDERSCORE +# define STR_SETUP "_setup_" +# define STR_FEATURES "_features_" +# define STR_ENABLES "_enables_" +# define STR_BOOT "_boot_" +# define STR_CLEANUP "_cleanup_" +# define STR_FINISH "_finish_" +#else /* !DLSYM_NEEDS_UNDERSCORE */ +# define STR_SETUP "setup_" +# define STR_FEATURES "features_" +# define STR_ENABLES "enables_" +# define STR_BOOT "boot_" +# define STR_CLEANUP "cleanup_" +# define STR_FINISH "finish_" +#endif /* !DLSYM_NEEDS_UNDERSCORE */ + +/**/ +#endif /* !AIXDYNAMIC */ + +#ifndef RTLD_LAZY +# define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +# define RTLD_GLOBAL 0 +#endif + +/* + * Attempt to load a module. This is the lowest level of + * zsh function for dynamical modules. Returns the handle + * from the dynamic loader. + */ + +/**/ +static void * +try_load_module(char const *name) +{ + char buf[PATH_MAX + 1]; + char **pp; + void *ret = NULL; + int l; + + l = 1 + strlen(name) + 1 + strlen(DL_EXT); + for (pp = module_path; !ret && *pp; pp++) { + if (l + (**pp ? strlen(*pp) : 1) > PATH_MAX) + continue; + sprintf(buf, "%s/%s.%s", **pp ? *pp : ".", name, DL_EXT); + unmetafy(buf, NULL); + if (*buf) /* dlopen(NULL) returns a handle to the main binary */ + ret = dlopen(buf, RTLD_LAZY | RTLD_GLOBAL); + } + + return ret; +} + +/* + * Load a module, with option to complain or not. + * Returns the handle from the dynamic loader. + */ + +/**/ +static void * +do_load_module(char const *name, int silent) +{ + void *ret; + + ret = try_load_module(name); + if (!ret && !silent) { +#ifdef HAVE_DLERROR + char *errstr = dlerror(); + zwarn("failed to load module `%s': %s", name, + errstr ? metafy(errstr, -1, META_HEAPDUP) : "empty module path"); +#else + zwarn("failed to load module: %s", name); +#endif + } + return ret; +} + +/**/ +#else /* !DYNAMIC */ + +/* + * Dummy loader when no dynamic loading available; always fails. + */ + +/**/ +static void * +do_load_module(char const *name, int silent) +{ + if (!silent) + zwarn("failed to load module: %s", name); + + return NULL; +} + +/**/ +#endif /* !DYNAMIC */ + +/* + * Find a module in the list. + * flags is a set of bits defined in the enum above. + * If namep is set, this is set to point to the last alias value resolved, + * even if that module was not loaded. or the module name if no aliases. + * Hence this is always the physical module to load in a chain of aliases. + * Return NULL if the module named is not stored as a structure, or if we were + * resolving aliases and the final module named is not stored as a + * structure. + */ +/**/ +static Module +find_module(const char *name, int flags, const char **namep) +{ + Module m; + + m = (Module)modulestab->getnode2(modulestab, name); + if (m) { + if ((flags & FINDMOD_ALIASP) && (m->node.flags & MOD_ALIAS)) { + if (namep) + *namep = m->u.alias; + return find_module(m->u.alias, flags, namep); + } + if (namep) + *namep = m->node.nam; + return m; + } + if (!(flags & FINDMOD_CREATE)) + return NULL; + m = zshcalloc(sizeof(*m)); + modulestab->addnode(modulestab, ztrdup(name), m); + return m; +} + +/* + * Unlink and free a module node from the linked list. + */ + +/**/ +static void +delete_module(Module m) +{ + modulestab->removenode(modulestab, m->node.nam); + + modulestab->freenode(&m->node); +} + +/* + * Return 1 if a module is fully loaded else zero. + * A linked module may be marked as unloaded even though + * we can't fully unload it; this returns 0 to try to + * make that state transparently like an unloaded module. + */ + +/**/ +mod_export int +module_loaded(const char *name) +{ + Module m; + + return ((m = find_module(name, FINDMOD_ALIASP, NULL)) && + m->u.handle && + !(m->node.flags & MOD_UNLOAD)); +} + +/* + * Setup and cleanup functions: we don't search for aliases here, + * since they should have been resolved before we try to load or unload + * the module. + */ + +/**/ +#ifdef DYNAMIC + +/**/ +#ifdef AIXDYNAMIC + +/**/ +static int +dyn_setup_module(Module m) +{ + return ((int (*)_((int,Module, void*))) m->u.handle)(0, m, NULL); +} + +/**/ +static int +dyn_features_module(Module m, char ***features) +{ + return ((int (*)_((int,Module, void*))) m->u.handle)(4, m, features); +} + +/**/ +static int +dyn_enables_module(Module m, int **enables) +{ + return ((int (*)_((int,Module, void*))) m->u.handle)(5, m, enables); +} + +/**/ +static int +dyn_boot_module(Module m) +{ + return ((int (*)_((int,Module, void*))) m->u.handle)(1, m, NULL); +} + +/**/ +static int +dyn_cleanup_module(Module m) +{ + return ((int (*)_((int,Module, void*))) m->u.handle)(2, m, NULL); +} + +/**/ +static int +dyn_finish_module(Module m) +{ + return ((int (*)_((int,Module,void *))) m->u.handle)(3, m, NULL); +} + +/**/ +#else + +static Module_generic_func +module_func(Module m, char *name) +{ +#ifdef DYNAMIC_NAME_CLASH_OK + return (Module_generic_func) dlsym(m->u.handle, name); +#else /* !DYNAMIC_NAME_CLASH_OK */ + VARARR(char, buf, strlen(name) + strlen(m->node.nam)*2 + 1); + char const *p; + char *q; + strcpy(buf, name); + q = strchr(buf, 0); + for(p = m->node.nam; *p; p++) { + if(*p == '/') { + *q++ = 'Q'; + *q++ = 's'; + } else if(*p == '_') { + *q++ = 'Q'; + *q++ = 'u'; + } else if(*p == 'Q') { + *q++ = 'Q'; + *q++ = 'q'; + } else + *q++ = *p; + } + *q = 0; + return (Module_generic_func) dlsym(m->u.handle, buf); +#endif /* !DYNAMIC_NAME_CLASH_OK */ +} + +/**/ +static int +dyn_setup_module(Module m) +{ + Module_void_func fn = (Module_void_func)module_func(m, STR_SETUP); + + if (fn) + return fn(m); + zwarnnam(m->node.nam, "no setup function"); + return 1; +} + +/**/ +static int +dyn_features_module(Module m, char ***features) +{ + Module_features_func fn = + (Module_features_func)module_func(m, STR_FEATURES); + + if (fn) + return fn(m, features); + /* not a user-visible error if no features function */ + return 1; +} + +/**/ +static int +dyn_enables_module(Module m, int **enables) +{ + Module_enables_func fn = (Module_enables_func)module_func(m, STR_ENABLES); + + if (fn) + return fn(m, enables); + /* not a user-visible error if no enables function */ + return 1; +} + +/**/ +static int +dyn_boot_module(Module m) +{ + Module_void_func fn = (Module_void_func)module_func(m, STR_BOOT); + + if(fn) + return fn(m); + zwarnnam(m->node.nam, "no boot function"); + return 1; +} + +/**/ +static int +dyn_cleanup_module(Module m) +{ + Module_void_func fn = (Module_void_func)module_func(m, STR_CLEANUP); + + if(fn) + return fn(m); + zwarnnam(m->node.nam, "no cleanup function"); + return 1; +} + +/* Note that this function does more than just calling finish_foo(), * + * it really unloads the module. */ + +/**/ +static int +dyn_finish_module(Module m) +{ + Module_void_func fn = (Module_void_func)module_func(m, STR_FINISH); + int r; + + if (fn) + r = fn(m); + else { + zwarnnam(m->node.nam, "no finish function"); + r = 1; + } + dlclose(m->u.handle); + return r; +} + +/**/ +#endif /* !AIXDYNAMIC */ + +/**/ +static int +setup_module(Module m) +{ + return ((m->node.flags & MOD_LINKED) ? + (m->u.linked->setup)(m) : dyn_setup_module(m)); +} + +/**/ +static int +features_module(Module m, char ***features) +{ + return ((m->node.flags & MOD_LINKED) ? + (m->u.linked->features)(m, features) : + dyn_features_module(m, features)); +} + +/**/ +static int +enables_module(Module m, int **enables) +{ + return ((m->node.flags & MOD_LINKED) ? + (m->u.linked->enables)(m, enables) : + dyn_enables_module(m, enables)); +} + +/**/ +static int +boot_module(Module m) +{ + return ((m->node.flags & MOD_LINKED) ? + (m->u.linked->boot)(m) : dyn_boot_module(m)); +} + +/**/ +static int +cleanup_module(Module m) +{ + return ((m->node.flags & MOD_LINKED) ? + (m->u.linked->cleanup)(m) : dyn_cleanup_module(m)); +} + +/**/ +static int +finish_module(Module m) +{ + return ((m->node.flags & MOD_LINKED) ? + (m->u.linked->finish)(m) : dyn_finish_module(m)); +} + +/**/ +#else /* !DYNAMIC */ + +/**/ +static int +setup_module(Module m) +{ + return ((m->node.flags & MOD_LINKED) ? (m->u.linked->setup)(m) : 1); +} + +/**/ +static int +features_module(Module m, char ***features) +{ + return ((m->node.flags & MOD_LINKED) ? (m->u.linked->features)(m, features) + : 1); +} + +/**/ +static int +enables_module(Module m, int **enables) +{ + return ((m->node.flags & MOD_LINKED) ? (m->u.linked->enables)(m, enables) + : 1); +} + +/**/ +static int +boot_module(Module m) +{ + return ((m->node.flags & MOD_LINKED) ? (m->u.linked->boot)(m) : 1); +} + +/**/ +static int +cleanup_module(Module m) +{ + return ((m->node.flags & MOD_LINKED) ? (m->u.linked->cleanup)(m) : 1); +} + +/**/ +static int +finish_module(Module m) +{ + return ((m->node.flags & MOD_LINKED) ? (m->u.linked->finish)(m) : 1); +} + +/**/ +#endif /* !DYNAMIC */ + + +/************************************************************************ + * Functions called when manipulating modules + ************************************************************************/ + +/* + * Set the features for the module, which must be loaded + * by now (though may not be fully set up). + * + * Return 0 for success, 1 for failure, 2 if some features + * couldn't be set by the module itself (non-existent features + * are tested here and cause 1 to be returned). + */ + +/**/ +static int +do_module_features(Module m, Feature_enables enablesarr, int flags) +{ + char **features; + int ret = 0; + + if (features_module(m, &features) == 0) { + /* + * Features are supported. If we were passed + * a NULL array, enable all features, else + * enable only the features listed. + * (This may in principle be an empty array, + * although that's not very pointful.) + */ + int *enables = NULL; + if (enables_module(m, &enables)) { + /* If features are supported, enables should be, too */ + if (!(flags & FEAT_IGNORE)) + zwarn("error getting enabled features for module `%s'", + m->node.nam); + return 1; + } + + if ((flags & FEAT_CHECKAUTO) && m->autoloads) { + /* + * Check autoloads are available. Since these + * have been requested at some other point, they + * don't affect the return status unless something + * in enablesstr doesn't work. + */ + LinkNode an, nextn; + for (an = firstnode(m->autoloads); an; an = nextn) { + char *al = (char *)getdata(an), **ptr; + /* careful, we can delete the current node */ + nextn = nextnode(an); + for (ptr = features; *ptr; ptr++) + if (!strcmp(al, *ptr)) + break; + if (!*ptr) { + char *arg[2]; + if (!(flags & FEAT_IGNORE)) + zwarn( + "module `%s' has no such feature: `%s': autoload cancelled", + m->node.nam, al); + /* + * This shouldn't happen, so it's not worth optimising + * the call to autofeatures... + */ + arg[0] = al = dupstring(al); + arg[1] = NULL; + (void)autofeatures(NULL, m->node.nam, arg, 0, + FEAT_IGNORE|FEAT_REMOVE); + /* + * don't want to try to enable *that*... + * expunge it from the enable string. + */ + if (enablesarr) { + Feature_enables fep; + for (fep = enablesarr; fep->str; fep++) { + char *str = fep->str; + if (*str == '+' || *str == '-') + str++; + if (fep->pat ? pattry(fep->pat, al) : + !strcmp(al, str)) { + /* can't enable it after all, so return 1 */ + ret = 1; + while (fep->str) { + fep->str = fep[1].str; + fep->pat = fep[1].pat; + fep++; + } + if (!fep->pat) + break; + } + } + } + } + } + } + + if (enablesarr) { + Feature_enables fep; + for (fep = enablesarr; fep->str; fep++) { + char **fp, *esp = fep->str; + int on = 1, found = 0; + if (*esp == '+') + esp++; + else if (*esp == '-') { + on = 0; + esp++; + } + for (fp = features; *fp; fp++) + if (fep->pat ? pattry(fep->pat, *fp) : !strcmp(*fp, esp)) { + enables[fp - features] = on; + found++; + if (!fep->pat) + break; + } + if (!found) { + if (!(flags & FEAT_IGNORE)) + zwarn(fep->pat ? + "module `%s' has no feature matching: `%s'" : + "module `%s' has no such feature: `%s'", + m->node.nam, esp); + return 1; + } + } + } else { + /* + * Enable all features. This is used when loading + * without using zmodload -F. + */ + int n_features = arrlen(features); + int *ep; + for (ep = enables; n_features--; ep++) + *ep = 1; + } + + if (enables_module(m, &enables)) + return 2; + } else if (enablesarr) { + if (!(flags & FEAT_IGNORE)) + zwarn("module `%s' does not support features", m->node.nam); + return 1; + } + /* Else it doesn't support features but we don't care. */ + + return ret; +} + +/* + * Boot the module, including setting up features. + * As we've only just loaded the module, we don't yet + * know what features it supports, so we get them passed + * as a string. + * + * Returns 0 if OK, 1 if completely failed, 2 if some features + * couldn't be set up. + */ + +/**/ +static int +do_boot_module(Module m, Feature_enables enablesarr, int silent) +{ + int ret = do_module_features(m, enablesarr, + silent ? FEAT_IGNORE|FEAT_CHECKAUTO : + FEAT_CHECKAUTO); + + if (ret == 1) + return 1; + + if (boot_module(m)) + return 1; + return ret; +} + +/* + * Cleanup the module. + */ + +/**/ +static int +do_cleanup_module(Module m) +{ + return (m->node.flags & MOD_LINKED) ? + (m->u.linked && m->u.linked->cleanup(m)) : + (m->u.handle && cleanup_module(m)); +} + +/* + * Test a module name contains only valid characters: those + * allowed in a shell identifier plus slash. Return 1 if so. + */ + +/**/ +static int +modname_ok(char const *p) +{ + do { + p = itype_end(p, IIDENT, 0); + if (!*p) + return 1; + } while(*p++ == '/'); + return 0; +} + +/* + * High level function to load a module, encapsulating + * all the handling of module functions. + * + * "*enablesstr" is NULL if the caller is not feature-aware; + * then the module should turn on all features. If it + * is not NULL it points to an array of features to be + * turned on. This function is responsible for testing whether + * the module supports those features. + * + * If "silent" is 1, don't issue warnings for errors. + * + * Now returns 0 for success (changed post-4.3.4), + * 1 for complete failure, 2 if some features couldn't be set. + */ + +/**/ +mod_export int +load_module(char const *name, Feature_enables enablesarr, int silent) +{ + Module m; + void *handle = NULL; + Linkedmod linked; + int set, bootret; + + if (!modname_ok(name)) { + if (!silent) + zerr("invalid module name `%s'", name); + return 1; + } + /* + * The following function call may alter name to the final name in a + * chain of aliases. This makes sure the actual module loaded + * is the right one. + */ + queue_signals(); + if (!(m = find_module(name, FINDMOD_ALIASP, &name))) { + if (!(linked = module_linked(name)) && + !(handle = do_load_module(name, silent))) { + unqueue_signals(); + return 1; + } + m = zshcalloc(sizeof(*m)); + if (handle) { + m->u.handle = handle; + m->node.flags |= MOD_SETUP; + } else { + m->u.linked = linked; + m->node.flags |= MOD_SETUP | MOD_LINKED; + } + modulestab->addnode(modulestab, ztrdup(name), m); + + if ((set = setup_module(m)) || + (bootret = do_boot_module(m, enablesarr, silent)) == 1) { + if (!set) + do_cleanup_module(m); + finish_module(m); + delete_module(m); + unqueue_signals(); + return 1; + } + m->node.flags |= MOD_INIT_S | MOD_INIT_B; + m->node.flags &= ~MOD_SETUP; + unqueue_signals(); + return bootret; + } + if (m->node.flags & MOD_SETUP) { + unqueue_signals(); + return 0; + } + if (m->node.flags & MOD_UNLOAD) + m->node.flags &= ~MOD_UNLOAD; + else if ((m->node.flags & MOD_LINKED) ? m->u.linked : m->u.handle) { + unqueue_signals(); + return 0; + } + if (m->node.flags & MOD_BUSY) { + unqueue_signals(); + zerr("circular dependencies for module ;%s", name); + return 1; + } + m->node.flags |= MOD_BUSY; + /* + * TODO: shouldn't we unload the module if one of + * its dependencies fails? + */ + if (m->deps) { + LinkNode n; + for (n = firstnode(m->deps); n; incnode(n)) + if (load_module((char *) getdata(n), NULL, silent) == 1) { + m->node.flags &= ~MOD_BUSY; + unqueue_signals(); + return 1; + } + } + m->node.flags &= ~MOD_BUSY; + if (!m->u.handle) { + handle = NULL; + if (!(linked = module_linked(name)) && + !(handle = do_load_module(name, silent))) { + unqueue_signals(); + return 1; + } + if (handle) { + m->u.handle = handle; + m->node.flags |= MOD_SETUP; + } else { + m->u.linked = linked; + m->node.flags |= MOD_SETUP | MOD_LINKED; + } + if (setup_module(m)) { + finish_module(m); + if (handle) + m->u.handle = NULL; + else + m->u.linked = NULL; + m->node.flags &= ~MOD_SETUP; + unqueue_signals(); + return 1; + } + m->node.flags |= MOD_INIT_S; + } + m->node.flags |= MOD_SETUP; + if ((bootret = do_boot_module(m, enablesarr, silent)) == 1) { + do_cleanup_module(m); + finish_module(m); + if (m->node.flags & MOD_LINKED) + m->u.linked = NULL; + else + m->u.handle = NULL; + m->node.flags &= ~MOD_SETUP; + unqueue_signals(); + return 1; + } + m->node.flags |= MOD_INIT_B; + m->node.flags &= ~MOD_SETUP; + unqueue_signals(); + return bootret; +} + +/* This ensures that the module with the name given as the first argument + * is loaded. + * The other argument is the array of features to set. If this is NULL + * all features are enabled (even if the module was already loaded). + * + * If this is non-NULL the module features are set accordingly + * whether or not the module is loaded; it is an error if the + * module does not support the features passed (even if the feature + * is to be turned off) or if the module does not support features + * at all. + * The return value is 0 if the module was found or loaded + * (this changed post-4.3.4, because I got so confused---pws), + * 1 if loading failed completely, 2 if some features couldn't be set. + * + * This function behaves like load_module() except that it + * handles the case where the module was already loaded, and + * sets features accordingly. + */ + +/**/ +mod_export int +require_module(const char *module, Feature_enables features, int silent) +{ + Module m = NULL; + int ret = 0; + + /* Resolve aliases and actual loadable module as for load_module */ + queue_signals(); + m = find_module(module, FINDMOD_ALIASP, &module); + if (!m || !m->u.handle || + (m->node.flags & MOD_UNLOAD)) + ret = load_module(module, features, silent); + else + ret = do_module_features(m, features, 0); + unqueue_signals(); + + return ret; +} + +/* + * Indicate that the module named "name" depends on the module + * named "from". + */ + +/**/ +void +add_dep(const char *name, char *from) +{ + LinkNode node; + Module m; + + /* + * If we were passed an alias, we must resolve it to a final + * module name (and maybe add the corresponding struct), since otherwise + * we would need to check all modules to see if they happen + * to be aliased to the same thing to implement dependencies properly. + * + * This should mean that an attempt to add an alias which would + * have the same name as a module which has dependencies is correctly + * rejected, because then the module named already exists as a non-alias. + * Better make sure. (There's no problem making a an alias which + * *points* to a module with dependencies, of course.) + */ + m = find_module(name, FINDMOD_ALIASP|FINDMOD_CREATE, &name); + if (!m->deps) + m->deps = znewlinklist(); + for (node = firstnode(m->deps); + node && strcmp((char *) getdata(node), from); + incnode(node)); + if (!node) + zaddlinknode(m->deps, ztrdup(from)); +} + +/* + * Function to be used when scanning the builtins table to + * find and print autoloadable builtins. + */ + +/**/ +static void +autoloadscan(HashNode hn, int printflags) +{ + Builtin bn = (Builtin) hn; + + if(bn->node.flags & BINF_ADDED) + return; + if(printflags & PRINT_LIST) { + fputs("zmodload -ab ", stdout); + if(bn->optstr[0] == '-') + fputs("-- ", stdout); + quotedzputs(bn->optstr, stdout); + if(strcmp(bn->node.nam, bn->optstr)) { + putchar(' '); + quotedzputs(bn->node.nam, stdout); + } + } else { + nicezputs(bn->node.nam, stdout); + if(strcmp(bn->node.nam, bn->optstr)) { + fputs(" (", stdout); + nicezputs(bn->optstr, stdout); + putchar(')'); + } + } + putchar('\n'); +} + + +/************************************************************************ + * Handling for the zmodload builtin and its various options. + ************************************************************************/ + +/* + * Main builtin entry point for zmodload. + */ + +/**/ +int +bin_zmodload(char *nam, char **args, Options ops, UNUSED(int func)) +{ + int ops_bcpf = OPT_ISSET(ops,'b') || OPT_ISSET(ops,'c') || + OPT_ISSET(ops,'p') || OPT_ISSET(ops,'f'); + int ops_au = OPT_ISSET(ops,'a') || OPT_ISSET(ops,'u'); + int ret = 1, autoopts; + /* options only allowed with -F */ + char *fonly = "lP", *fp; + + if (ops_bcpf && !ops_au) { + zwarnnam(nam, "-b, -c, -f, and -p must be combined with -a or -u"); + return 1; + } + if (OPT_ISSET(ops,'F') && (ops_bcpf || OPT_ISSET(ops,'u'))) { + zwarnnam(nam, "-b, -c, -f, -p and -u cannot be combined with -F"); + return 1; + } + if (OPT_ISSET(ops,'A') || OPT_ISSET(ops,'R')) { + if (ops_bcpf || ops_au || OPT_ISSET(ops,'d') || + (OPT_ISSET(ops,'R') && OPT_ISSET(ops,'e'))) { + zwarnnam(nam, "illegal flags combined with -A or -R"); + return 1; + } + if (!OPT_ISSET(ops,'e')) + return bin_zmodload_alias(nam, args, ops); + } + if (OPT_ISSET(ops,'d') && OPT_ISSET(ops,'a')) { + zwarnnam(nam, "-d cannot be combined with -a"); + return 1; + } + if (OPT_ISSET(ops,'u') && !*args) { + zwarnnam(nam, "what do you want to unload?"); + return 1; + } + if (OPT_ISSET(ops,'e') && (OPT_ISSET(ops,'I') || OPT_ISSET(ops,'L') || + (OPT_ISSET(ops,'a') && !OPT_ISSET(ops,'F')) + || OPT_ISSET(ops,'d') || + OPT_ISSET(ops,'i') || OPT_ISSET(ops,'u'))) { + zwarnnam(nam, "-e cannot be combined with other options"); + /* except -F ... */ + return 1; + } + for (fp = fonly; *fp; fp++) { + if (OPT_ISSET(ops,STOUC(*fp)) && !OPT_ISSET(ops,'F')) { + zwarnnam(nam, "-%c is only allowed with -F", *fp); + return 1; + } + } + queue_signals(); + if (OPT_ISSET(ops, 'F')) + ret = bin_zmodload_features(nam, args, ops); + else if (OPT_ISSET(ops,'e')) + ret = bin_zmodload_exist(nam, args, ops); + else if (OPT_ISSET(ops,'d')) + ret = bin_zmodload_dep(nam, args, ops); + else if ((autoopts = OPT_ISSET(ops, 'b') + OPT_ISSET(ops, 'c') + + OPT_ISSET(ops, 'p') + OPT_ISSET(ops, 'f')) || + /* zmodload -a is equivalent to zmodload -ab, annoyingly */ + OPT_ISSET(ops, 'a')) { + if (autoopts > 1) { + zwarnnam(nam, "use only one of -b, -c, or -p"); + ret = 1; + } else + ret = bin_zmodload_auto(nam, args, ops); + } else + ret = bin_zmodload_load(nam, args, ops); + unqueue_signals(); + + return ret; +} + +/* zmodload -A */ + +/**/ +static int +bin_zmodload_alias(char *nam, char **args, Options ops) +{ + /* + * TODO: while it would be too nasty to have aliases, as opposed + * to real loadable modules, with dependencies --- just what would + * we need to load when, exactly? --- there is in principle no objection + * to making it possible to force an alias onto an existing unloaded + * module which has dependencies. This would simply transfer + * the dependencies down the line to the aliased-to module name. + * This is actually useful, since then you can alias zsh/zle=mytestzle + * to load another version of zle. But then what happens when the + * alias is removed? Do you transfer the dependencies back? And + * suppose other names are aliased to the same file? It might be + * kettle of fish best left unwormed. + */ + Module m; + + if (!*args) { + if (OPT_ISSET(ops,'R')) { + zwarnnam(nam, "no module alias to remove"); + return 1; + } + scanhashtable(modulestab, 1, MOD_ALIAS, 0, + modulestab->printnode, + OPT_ISSET(ops,'L') ? PRINTMOD_LIST : 0); + return 0; + } + + for (; *args; args++) { + char *eqpos = strchr(*args, '='); + char *aliasname = eqpos ? eqpos+1 : NULL; + if (eqpos) + *eqpos = '\0'; + if (!modname_ok(*args)) { + zwarnnam(nam, "invalid module name `%s'", *args); + return 1; + } + if (OPT_ISSET(ops,'R')) { + if (aliasname) { + zwarnnam(nam, "bad syntax for removing module alias: %s", + *args); + return 1; + } + m = find_module(*args, 0, NULL); + if (m) { + if (!(m->node.flags & MOD_ALIAS)) { + zwarnnam(nam, "module is not an alias: %s", *args); + return 1; + } + delete_module(m); + } else { + zwarnnam(nam, "no such module alias: %s", *args); + return 1; + } + } else { + if (aliasname) { + const char *mname = aliasname; + if (!modname_ok(aliasname)) { + zwarnnam(nam, "invalid module name `%s'", aliasname); + return 1; + } + do { + if (!strcmp(mname, *args)) { + zwarnnam(nam, "module alias would refer to itself: %s", + *args); + return 1; + } + } while ((m = find_module(mname, 0, NULL)) + && (m->node.flags & MOD_ALIAS) + && (mname = m->u.alias)); + m = find_module(*args, 0, NULL); + if (m) { + if (!(m->node.flags & MOD_ALIAS)) { + zwarnnam(nam, "module is not an alias: %s", *args); + return 1; + } + zsfree(m->u.alias); + } else { + m = (Module) zshcalloc(sizeof(*m)); + m->node.flags = MOD_ALIAS; + modulestab->addnode(modulestab, ztrdup(*args), m); + } + m->u.alias = ztrdup(aliasname); + } else { + if ((m = find_module(*args, 0, NULL))) { + if (m->node.flags & MOD_ALIAS) + modulestab->printnode(&m->node, + OPT_ISSET(ops,'L') ? + PRINTMOD_LIST : 0); + else { + zwarnnam(nam, "module is not an alias: %s", *args); + return 1; + } + } else { + zwarnnam(nam, "no such module alias: %s", *args); + return 1; + } + } + } + } + + return 0; +} + +/* zmodload -e (without -F) */ + +/**/ +static int +bin_zmodload_exist(UNUSED(char *nam), char **args, Options ops) +{ + Module m; + + if (!*args) { + scanhashtable(modulestab, 1, 0, 0, modulestab->printnode, + OPT_ISSET(ops,'A') ? PRINTMOD_EXIST|PRINTMOD_ALIAS : + PRINTMOD_EXIST); + return 0; + } else { + int ret = 0; + + for (; !ret && *args; args++) { + if (!(m = find_module(*args, FINDMOD_ALIASP, NULL)) + || !m->u.handle + || (m->node.flags & MOD_UNLOAD)) + ret = 1; + } + return ret; + } +} + +/* zmodload -d */ + +/**/ +static int +bin_zmodload_dep(UNUSED(char *nam), char **args, Options ops) +{ + Module m; + if (OPT_ISSET(ops,'u')) { + /* remove dependencies, which can't pertain to aliases */ + const char *tnam = *args++; + m = find_module(tnam, FINDMOD_ALIASP, &tnam); + if (!m) + return 0; + if (*args && m->deps) { + do { + LinkNode dnode; + for (dnode = firstnode(m->deps); dnode; incnode(dnode)) + if (!strcmp(*args, getdata(dnode))) { + zsfree(getdata(dnode)); + remnode(m->deps, dnode); + break; + } + } while(*++args); + if (empty(m->deps)) { + freelinklist(m->deps, freestr); + m->deps = NULL; + } + } else { + if (m->deps) { + freelinklist(m->deps, freestr); + m->deps = NULL; + } + } + if (!m->deps && !m->u.handle) + delete_module(m); + return 0; + } else if (!args[0] || !args[1]) { + /* list dependencies */ + int depflags = OPT_ISSET(ops,'L') ? + PRINTMOD_DEPS|PRINTMOD_LIST : PRINTMOD_DEPS; + if (args[0]) { + if ((m = (Module)modulestab->getnode2(modulestab, args[0]))) + modulestab->printnode(&m->node, depflags); + } else { + scanhashtable(modulestab, 1, 0, 0, modulestab->printnode, + depflags); + } + return 0; + } else { + /* add dependencies */ + int ret = 0; + char *tnam = *args++; + + for (; *args; args++) + add_dep(tnam, *args); + return ret; + } +} + +/* + * Function for scanning the parameter table to find and print + * out autoloadable parameters. + */ + +static void +printautoparams(HashNode hn, int lon) +{ + Param pm = (Param) hn; + + if (pm->node.flags & PM_AUTOLOAD) { + if (lon) + printf("zmodload -ap %s %s\n", pm->u.str, pm->node.nam); + else + printf("%s (%s)\n", pm->node.nam, pm->u.str); + } +} + +/* zmodload -a/u [bcpf] */ + +/**/ +static int +bin_zmodload_auto(char *nam, char **args, Options ops) +{ + int fchar, flags; + char *modnam; + + if (OPT_ISSET(ops,'c')) { + if (!*args) { + /* list autoloaded conditions */ + Conddef p; + + for (p = condtab; p; p = p->next) { + if (p->module) { + if (OPT_ISSET(ops,'L')) { + fputs("zmodload -ac", stdout); + if (p->flags & CONDF_INFIX) + putchar('I'); + printf(" %s %s\n", p->module, p->name); + } else { + if (p->flags & CONDF_INFIX) + fputs("infix ", stdout); + else + fputs("post ", stdout); + printf("%s (%s)\n",p->name, p->module); + } + } + } + return 0; + } + fchar = OPT_ISSET(ops,'I') ? 'C' : 'c'; + } else if (OPT_ISSET(ops,'p')) { + if (!*args) { + /* list autoloaded parameters */ + scanhashtable(paramtab, 1, 0, 0, printautoparams, + OPT_ISSET(ops,'L')); + return 0; + } + fchar = 'p'; + } else if (OPT_ISSET(ops,'f')) { + if (!*args) { + /* list autoloaded math functions */ + MathFunc p; + + for (p = mathfuncs; p; p = p->next) { + if (!(p->flags & MFF_USERFUNC) && p->module) { + if (OPT_ISSET(ops,'L')) { + fputs("zmodload -af", stdout); + printf(" %s %s\n", p->module, p->name); + } else + printf("%s (%s)\n",p->name, p->module); + } + } + return 0; + } + fchar = 'f'; + } else { + /* builtins are the default; zmodload -ab or just zmodload -a */ + if (!*args) { + /* list autoloaded builtins */ + scanhashtable(builtintab, 1, 0, 0, + autoloadscan, OPT_ISSET(ops,'L') ? PRINT_LIST : 0); + return 0; + } + fchar = 'b'; + } + + flags = FEAT_AUTOALL; + if (OPT_ISSET(ops,'i')) + flags |= FEAT_IGNORE; + if (OPT_ISSET(ops,'u')) { + /* remove autoload */ + flags |= FEAT_REMOVE; + modnam = NULL; + } else { + /* add autoload */ + modnam = *args; + + if (args[1]) + args++; + } + return autofeatures(nam, modnam, args, fchar, flags); +} + +/* Backend handler for zmodload -u */ + +/**/ +int +unload_module(Module m) +{ + int del; + + /* + * Only unload the real module, so resolve aliases. + */ + if (m->node.flags & MOD_ALIAS) { + m = find_module(m->u.alias, FINDMOD_ALIASP, NULL); + if (!m) + return 1; + } + /* + * We may need to clean up the module any time setup_ has been + * called. After cleanup_ is successful we are no longer in the + * booted state (because features etc. are deregistered), so remove + * MOD_INIT_B, and also MOD_INIT_S since we won't need to cleanup + * again if this succeeded. + */ + if ((m->node.flags & MOD_INIT_S) && + !(m->node.flags & MOD_UNLOAD) && + do_cleanup_module(m)) + return 1; + m->node.flags &= ~(MOD_INIT_B|MOD_INIT_S); + + del = (m->node.flags & MOD_UNLOAD); + + if (m->wrapper) { + m->node.flags |= MOD_UNLOAD; + return 0; + } + m->node.flags &= ~MOD_UNLOAD; + + /* + * We always need to finish the module (and unload it) + * if it is present. + */ + if (m->node.flags & MOD_LINKED) { + if (m->u.linked) { + m->u.linked->finish(m); + m->u.linked = NULL; + } + } else { + if (m->u.handle) { + finish_module(m); + m->u.handle = NULL; + } + } + + if (del && m->deps) { + /* The module was unloaded delayed, unload all modules * + * on which it depended. */ + LinkNode n; + + for (n = firstnode(m->deps); n; incnode(n)) { + Module dm = find_module((char *) getdata(n), + FINDMOD_ALIASP, NULL); + + if (dm && + (dm->node.flags & MOD_UNLOAD)) { + /* See if this is the only module depending on it. */ + Module am; + int du = 1, i; + /* Scan hash table the hard way */ + for (i = 0; du && i < modulestab->hsize; i++) { + for (am = (Module)modulestab->nodes[i]; du && am; + am = (Module)am->node.next) { + LinkNode sn; + /* + * Don't scan the module we're unloading; + * ignore if no dependencies. + */ + if (am == m || !am->deps) + continue; + /* Don't scan if not loaded nor linked */ + if ((am->node.flags & MOD_LINKED) ? + !am->u.linked : !am->u.handle) + continue; + for (sn = firstnode(am->deps); du && sn; + incnode(sn)) { + if (!strcmp((char *) getdata(sn), + dm->node.nam)) + du = 0; + } + } + } + if (du) + unload_module(dm); + } + } + } + if (m->autoloads && firstnode(m->autoloads)) { + /* + * Module has autoloadable features. Restore them + * so that the module will be reloaded when needed. + */ + autofeatures("zsh", m->node.nam, + hlinklist2array(m->autoloads, 0), 0, FEAT_IGNORE); + } else if (!m->deps) { + delete_module(m); + } + return 0; +} + +/* + * Unload a module by name (modname); nam is the command name. + * Optionally don't print some error messages (always print + * dependency errors). + */ + +/**/ +int +unload_named_module(char *modname, char *nam, int silent) +{ + const char *mname; + Module m; + int ret = 0; + + m = find_module(modname, FINDMOD_ALIASP, &mname); + if (m) { + int i, del = 0; + Module dm; + + for (i = 0; i < modulestab->hsize; i++) { + for (dm = (Module)modulestab->nodes[i]; dm; + dm = (Module)dm->node.next) { + LinkNode dn; + if (!dm->deps || !dm->u.handle) + continue; + for (dn = firstnode(dm->deps); dn; incnode(dn)) { + if (!strcmp((char *) getdata(dn), mname)) { + if (dm->node.flags & MOD_UNLOAD) + del = 1; + else { + zwarnnam(nam, "module %s is in use by another module and cannot be unloaded", mname); + return 1; + } + } + } + } + } + if (del) + m->wrapper++; + if (unload_module(m)) + ret = 1; + if (del) + m->wrapper--; + } else if (!silent) { + zwarnnam(nam, "no such module %s", modname); + ret = 1; + } + + return ret; +} + +/* zmodload -u without -d */ + +/**/ +static int +bin_zmodload_load(char *nam, char **args, Options ops) +{ + int ret = 0; + if(OPT_ISSET(ops,'u')) { + /* unload modules */ + for(; *args; args++) { + if (unload_named_module(*args, nam, OPT_ISSET(ops,'i'))) + ret = 1; + } + return ret; + } else if(!*args) { + /* list modules */ + scanhashtable(modulestab, 1, 0, MOD_UNLOAD|MOD_ALIAS, + modulestab->printnode, + OPT_ISSET(ops,'L') ? PRINTMOD_LIST : 0); + return 0; + } else { + /* load modules */ + for (; *args; args++) { + int tmpret = require_module(*args, NULL, OPT_ISSET(ops,'s')); + if (tmpret && ret != 1) + ret = tmpret; + } + + return ret; + } +} + +/* zmodload -F */ + +/**/ +static int +bin_zmodload_features(const char *nam, char **args, Options ops) +{ + int iarg; + char *modname = *args; + Patprog *patprogs; + Feature_enables features, fep; + + if (modname) + args++; + else if (OPT_ISSET(ops,'L')) { + int printflags = PRINTMOD_LIST|PRINTMOD_FEATURES; + if (OPT_ISSET(ops,'P')) { + zwarnnam(nam, "-P is only allowed with a module name"); + return 1; + } + if (OPT_ISSET(ops,'l')) + printflags |= PRINTMOD_LISTALL; + if (OPT_ISSET(ops,'a')) + printflags |= PRINTMOD_AUTO; + scanhashtable(modulestab, 1, 0, MOD_ALIAS, + modulestab->printnode, printflags); + return 0; + } + + if (!modname) { + zwarnnam(nam, "-F requires a module name"); + return 1; + } + + if (OPT_ISSET(ops,'m')) { + char **argp; + Patprog *patprogp; + + /* not NULL terminated */ + patprogp = patprogs = + (Patprog *)zhalloc(arrlen(args)*sizeof(Patprog)); + for (argp = args; *argp; argp++, patprogp++) { + char *arg = *argp; + if (*arg == '+' || *arg == '-') + arg++; + tokenize(arg); + *patprogp = patcompile(arg, 0, 0); + } + } else + patprogs = NULL; + + if (OPT_ISSET(ops,'l') || OPT_ISSET(ops,'L') || OPT_ISSET(ops,'e')) { + /* + * With option 'l', list all features one per line with + or -. + * With option 'L', list as zmodload statement showing + * only options turned on. + * With both options, list as zmodload showing options + * to be turned both on and off. + */ + Module m; + char **features, **fp, **arrset = NULL, **arrp = NULL; + int *enables = NULL, *ep; + char *param = OPT_ARG_SAFE(ops,'P'); + + m = find_module(modname, FINDMOD_ALIASP, NULL); + if (OPT_ISSET(ops,'a')) { + LinkNode ln; + /* + * If there are no autoloads defined, return status 1. + */ + if (!m || !m->autoloads) + return 1; + if (OPT_ISSET(ops,'e')) { + for (fp = args; *fp; fp++) { + char *fstr = *fp; + int sense = 1; + if (*fstr == '+') + fstr++; + else if (*fstr == '-') { + fstr++; + sense = 0; + } + if ((linknodebystring(m->autoloads, fstr) != NULL) != + sense) + return 1; + } + return 0; + } + if (param) { + arrp = arrset = (char **)zalloc(sizeof(char*) * + (countlinknodes(m->autoloads)+1)); + } else if (OPT_ISSET(ops,'L')) { + printf("zmodload -aF %s%c", m->node.nam, + m->autoloads && firstnode(m->autoloads) ? ' ' : '\n'); + arrp = NULL; + } + for (ln = firstnode(m->autoloads); ln; incnode(ln)) { + char *al = (char *)getdata(ln); + if (param) + *arrp++ = ztrdup(al); + else + printf("%s%c", al, + OPT_ISSET(ops,'L') && nextnode(ln) ? ' ' : '\n'); + } + if (param) { + *arrp = NULL; + if (!setaparam(param, arrset)) + return 1; + } + return 0; + } + if (!m || !m->u.handle || (m->node.flags & MOD_UNLOAD)) { + if (!OPT_ISSET(ops,'e')) + zwarnnam(nam, "module `%s' is not yet loaded", modname); + return 1; + } + if (features_module(m, &features)) { + if (!OPT_ISSET(ops,'e')) + zwarnnam(nam, "module `%s' does not support features", + m->node.nam); + return 1; + } + if (enables_module(m, &enables)) { + /* this shouldn't ever happen, so don't silence this error */ + zwarnnam(nam, "error getting enabled features for module `%s'", + m->node.nam); + return 1; + } + for (arrp = args, iarg = 0; *arrp; arrp++, iarg++) { + char *arg = *arrp; + int on, found = 0; + if (*arg == '-') { + on = 0; + arg++; + } else if (*arg == '+') { + on = 1; + arg++; + } else + on = -1; + for (fp = features, ep = enables; *fp; fp++, ep++) { + if (patprogs ? pattry(patprogs[iarg], *fp) : + !strcmp(arg, *fp)) { + /* for -e, check given state, if any */ + if (OPT_ISSET(ops,'e') && on != -1 && + on != (*ep & 1)) + return 1; + found++; + if (!patprogs) + break; + } + } + if (!found) { + if (!OPT_ISSET(ops,'e')) + zwarnnam(nam, patprogs ? + "module `%s' has no feature matching: `%s'" : + "module `%s' has no such feature: `%s'", + modname, *arrp); + return 1; + } + } + if (OPT_ISSET(ops,'e')) /* yep, everything we want exists */ + return 0; + if (param) { + int arrlen = 0; + for (fp = features, ep = enables; *fp; fp++, ep++) { + if (OPT_ISSET(ops, 'L') && !OPT_ISSET(ops, 'l') && + !*ep) + continue; + if (*args) { + char **argp; + for (argp = args, iarg = 0; *argp; argp++, iarg++) { + char *arg = *argp; + /* ignore +/- for consistency */ + if (*arg == '+' || *arg == '-') + arg++; + if (patprogs ? pattry(patprogs[iarg], *fp) : + !strcmp(*fp, arg)) + break; + } + if (!*argp) + continue; + } + arrlen++; + } + arrp = arrset = zalloc(sizeof(char *) * (arrlen+1)); + } else if (OPT_ISSET(ops, 'L')) + printf("zmodload -F %s ", m->node.nam); + for (fp = features, ep = enables; *fp; fp++, ep++) { + char *onoff; + int term; + if (*args) { + char **argp; + for (argp = args, iarg = 0; *argp; argp++, iarg++) { + char *arg = *argp; + if (*arg == '+' || *arg == '-') + arg++; + if (patprogs ? pattry(patprogs[iarg], *fp) : + !strcmp(*fp, *argp)) + break; + } + if (!*argp) + continue; + } + if (OPT_ISSET(ops, 'L') && !OPT_ISSET(ops, 'l')) { + if (!*ep) + continue; + onoff = ""; + } else if (*ep) { + onoff = "+"; + } else { + onoff = "-"; + } + if (param) { + *arrp++ = bicat(onoff, *fp); + } else { + if (OPT_ISSET(ops, 'L') && fp[1]) { + term = ' '; + } else { + term = '\n'; + } + printf("%s%s%c", onoff, *fp, term); + } + } + if (param) { + *arrp = NULL; + if (!setaparam(param, arrset)) + return 1; + } + return 0; + } else if (OPT_ISSET(ops,'P')) { + zwarnnam(nam, "-P can only be used with -l or -L"); + return 1; + } else if (OPT_ISSET(ops,'a')) { + if (OPT_ISSET(ops,'m')) { + zwarnnam(nam, "-m cannot be used with -a"); + return 1; + } + /* + * With zmodload -aF, we always use the effect of -i. + * The thinking is that marking a feature for + * autoload is separate from enabling or disabling it. + * Arguably we could do this with the zmodload -ab method + * but I've kept it there for old time's sake. + * The decoupling has meant FEAT_IGNORE/-i also + * suppresses an error for attempting to remove an + * autoload when the feature is enabled, which used + * to be a hard error before. + */ + return autofeatures(nam, modname, args, 0, FEAT_IGNORE); + } + + fep = features = + (Feature_enables)zhalloc((arrlen(args)+1)*sizeof(*fep)); + + while (*args) { + fep->str = *args++; + fep->pat = patprogs ? *patprogs++ : NULL; + fep++; + } + fep->str = NULL; + fep->pat = NULL; + + return require_module(modname, features, OPT_ISSET(ops,'s')); +} + + +/************************************************************************ + * Generic feature support. + * These functions are designed to be called by modules. + ************************************************************************/ + +/* + * Construct a features array out of the list of concrete + * features given, leaving space for any abstract features + * to be added by the module itself. + * + * Note the memory is from the heap. + */ + +/**/ +mod_export char ** +featuresarray(UNUSED(Module m), Features f) +{ + int bn_size = f->bn_size, cd_size = f->cd_size; + int mf_size = f->mf_size, pd_size = f->pd_size; + int features_size = bn_size + cd_size + pd_size + mf_size + f->n_abstract; + Builtin bnp = f->bn_list; + Conddef cdp = f->cd_list; + MathFunc mfp = f->mf_list; + Paramdef pdp = f->pd_list; + char **features = (char **)zhalloc((features_size + 1) * sizeof(char *)); + char **featurep = features; + + while (bn_size--) + *featurep++ = dyncat("b:", (bnp++)->node.nam); + while (cd_size--) { + *featurep++ = dyncat((cdp->flags & CONDF_INFIX) ? "C:" : "c:", + cdp->name); + cdp++; + } + while (mf_size--) + *featurep++ = dyncat("f:", (mfp++)->name); + while (pd_size--) + *featurep++ = dyncat("p:", (pdp++)->name); + + features[features_size] = NULL; + return features; +} + +/* + * Return the current set of enables for the features in a + * module using heap memory. Leave space for abstract + * features. The array is not zero terminated. + */ +/**/ +mod_export int * +getfeatureenables(UNUSED(Module m), Features f) +{ + int bn_size = f->bn_size, cd_size = f->cd_size; + int mf_size = f->mf_size, pd_size = f->pd_size; + int features_size = bn_size + cd_size + mf_size + pd_size + f->n_abstract; + Builtin bnp = f->bn_list; + Conddef cdp = f->cd_list; + MathFunc mfp = f->mf_list; + Paramdef pdp = f->pd_list; + int *enables = zhalloc(sizeof(int) * features_size); + int *enablep = enables; + + while (bn_size--) + *enablep++ = ((bnp++)->node.flags & BINF_ADDED) ? 1 : 0; + while (cd_size--) + *enablep++ = ((cdp++)->flags & CONDF_ADDED) ? 1 : 0; + while (mf_size--) + *enablep++ = ((mfp++)->flags & MFF_ADDED) ? 1 : 0; + while (pd_size--) + *enablep++ = (pdp++)->pm ? 1 : 0; + + return enables; +} + +/* + * Add or remove the concrete features passed in arguments, + * depending on the corresponding element of the array e. + * If e is NULL, disable everything. + * Return 0 for success, 1 for failure; does not attempt + * to imitate the return values of addbuiltins() etc. + * Any failure in adding a requested feature is an + * error. + */ + +/**/ +mod_export int +setfeatureenables(Module m, Features f, int *e) +{ + int ret = 0; + + if (f->bn_size) { + if (setbuiltins(m->node.nam, f->bn_list, f->bn_size, e)) + ret = 1; + if (e) + e += f->bn_size; + } + if (f->cd_size) { + if (setconddefs(m->node.nam, f->cd_list, f->cd_size, e)) + ret = 1; + if (e) + e += f->cd_size; + } + if (f->mf_size) { + if (setmathfuncs(m->node.nam, f->mf_list, f->mf_size, e)) + ret = 1; + if (e) + e += f->mf_size; + } + if (f->pd_size) { + if (setparamdefs(m->node.nam, f->pd_list, f->pd_size, e)) + ret = 1; + if (e) + e += f->pd_size; + } + return ret; +} + +/* + * Convenient front-end to get or set features which + * can be used in a module enables_() function. + */ + +/**/ +mod_export int +handlefeatures(Module m, Features f, int **enables) +{ + if (!enables || *enables) + return setfeatureenables(m, f, enables ? *enables : NULL); + *enables = getfeatureenables(m, f); + return 0; +} + +/* + * Ensure module "modname" is providing feature with "prefix" + * and "feature" (e.g. "b:", "limit"). If feature is NULL, + * ensure all features are loaded (used for compatibility + * with the pre-feature autoloading behaviour). + * + * This will usually be called from the main shell to handle + * loading of an autoloadable feature. + * + * Returns 0 on success, 1 for error in module, 2 for error + * setting the feature. However, this isn't actually all + * that useful for testing immediately on an autoload since + * it could be a failure to autoload a different feature + * from the one we want. We could fix this but it's + * possible to test other ways. + */ + +/**/ +mod_export int +ensurefeature(const char *modname, const char *prefix, const char *feature) +{ + char *f; + struct feature_enables features[2]; + + if (!feature) + return require_module(modname, NULL, 0); + f = dyncat(prefix, feature); + + features[0].str = f; + features[0].pat = NULL; + features[1].str = NULL; + features[1].pat = NULL; + return require_module(modname, features, 0); +} + +/* + * Add autoloadable features for a given module. + */ + +/**/ +int +autofeatures(const char *cmdnam, const char *module, char **features, + int prefchar, int defflags) +{ + int ret = 0, subret; + Module defm, m; + char **modfeatures = NULL; + int *modenables = NULL; + if (module) { + defm = (Module)find_module(module, + FINDMOD_ALIASP|FINDMOD_CREATE, NULL); + if ((defm->node.flags & MOD_LINKED) ? defm->u.linked : + defm->u.handle) { + (void)features_module(defm, &modfeatures); + (void)enables_module(defm, &modenables); + } + } else + defm = NULL; + + for (; *features; features++) { + char *fnam, *typnam, *feature; + int add, fchar, flags = defflags; + autofeaturefn_t fn; + + if (prefchar) { + /* + * "features" is list of bare features with no + * type prefix; prefchar gives type character. + */ + add = 1; /* unless overridden by flag */ + fchar = prefchar; + fnam = *features; + feature = zhalloc(strlen(fnam) + 3); + sprintf(feature, "%c:%s", fchar, fnam); + } else { + feature = *features; + if (*feature == '-') { + add = 0; + feature++; + } else { + add = 1; + if (*feature == '+') + feature++; + } + + if (!*feature || feature[1] != ':') { + zwarnnam(cmdnam, "bad format for autoloadable feature: `%s'", + feature); + ret = 1; + continue; + } + fnam = feature + 2; + fchar = feature[0]; + } + if (flags & FEAT_REMOVE) + add = 0; + + switch (fchar) { + case 'b': + fn = add ? add_autobin : del_autobin; + typnam = "builtin"; + break; + + case 'C': + flags |= FEAT_INFIX; + /* FALLTHROUGH */ + case 'c': + fn = add ? add_autocond : del_autocond; + typnam = "condition"; + break; + + case 'f': + fn = add ? add_automathfunc : del_automathfunc; + typnam = "math function"; + break; + + case 'p': + fn = add ? add_autoparam : del_autoparam; + typnam = "parameter"; + break; + + default: + zwarnnam(cmdnam, "bad autoloadable feature type: `%c'", + fchar); + ret = 1; + continue; + } + + if (strchr(fnam, '/')) { + zwarnnam(cmdnam, "%s: `/' is illegal in a %s", fnam, typnam); + ret = 1; + continue; + } + + if (!module) { + /* + * Traditional un-autoload syntax doesn't tell us + * which module this came from. + */ + int i; + for (i = 0, m = NULL; !m && i < modulestab->hsize; i++) { + for (m = (Module)modulestab->nodes[i]; m; + m = (Module)m->node.next) { + if (m->autoloads && + linknodebystring(m->autoloads, feature)) + break; + } + } + if (!m) { + if (!(flags & FEAT_IGNORE)) { + ret = 1; + zwarnnam(cmdnam, "%s: no such %s", fnam, typnam); + } + continue; + } + } else + m = defm; + + subret = 0; + if (add) { + char **ptr; + if (modfeatures) { + /* + * If the module is already available, check that + * it does in fact provide the necessary feature. + */ + for (ptr = modfeatures; *ptr; ptr++) + if (!strcmp(*ptr, feature)) + break; + if (!*ptr) { + zwarnnam(cmdnam, "module `%s' has no such feature: `%s'", + m->node.nam, feature); + ret = 1; + continue; + } + /* + * If the feature is already provided by the module, there's + * nothing more to do. + */ + if (modenables[ptr-modfeatures]) + continue; + /* + * Otherwise, marking it for autoload will do the + * right thing when the feature is eventually used. + */ + } + if (!m->autoloads) { + m->autoloads = znewlinklist(); + zaddlinknode(m->autoloads, ztrdup(feature)); + } else { + /* Insert in lexical order */ + LinkNode ln, prev = (LinkNode)m->autoloads; + while ((ln = nextnode(prev))) { + int cmp = strcmp(feature, (char *)getdata(ln)); + if (cmp == 0) { + /* Already there. Never an error. */ + break; + } + if (cmp < 0) { + zinsertlinknode(m->autoloads, prev, + ztrdup(feature)); + break; + } + prev = ln; + } + if (!ln) + zaddlinknode(m->autoloads, ztrdup(feature)); + } + } else if (m->autoloads) { + LinkNode ln; + if ((ln = linknodebystring(m->autoloads, feature))) + zsfree((char *)remnode(m->autoloads, ln)); + else { + /* + * With -i (or zmodload -Fa), removing an autoload + * that's not there is not an error. + */ + subret = (flags & FEAT_IGNORE) ? -2 : 2; + } + } + + if (subret == 0) + subret = fn(module, fnam, flags); + + if (subret != 0) { + /* -2 indicates not an error, just skip running fn() */ + if (subret != -2) + ret = 1; + switch (subret) { + case 1: + zwarnnam(cmdnam, "failed to add %s `%s'", typnam, fnam); + break; + + case 2: + zwarnnam(cmdnam, "%s: no such %s", fnam, typnam); + break; + + case 3: + zwarnnam(cmdnam, "%s: %s is already defined", fnam, typnam); + break; + + default: + /* no (further) message needed */ + break; + } + } + } + + return ret; +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/options.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/options.c new file mode 100644 index 00000000..600b649e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/options.c @@ -0,0 +1,955 @@ +/* + * options.c - shell options + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "options.pro" + +/* current emulation (used to decide which set of option letters is used) */ + +/**/ +mod_export int emulation; + +/* current sticky emulation: sticky = NULL means none */ + +/**/ +mod_export Emulation_options sticky; + +/* the options; e.g. if opts[SHGLOB] != 0, SH_GLOB is turned on */ + +/**/ +mod_export char opts[OPT_SIZE]; + +/* Option name hash table */ + +/**/ +mod_export HashTable optiontab; + +/* The canonical option name table */ + +#define OPT_CSH EMULATE_CSH +#define OPT_KSH EMULATE_KSH +#define OPT_SH EMULATE_SH +#define OPT_ZSH EMULATE_ZSH + +#define OPT_ALL (OPT_CSH|OPT_KSH|OPT_SH|OPT_ZSH) +#define OPT_BOURNE (OPT_KSH|OPT_SH) +#define OPT_BSHELL (OPT_KSH|OPT_SH|OPT_ZSH) +#define OPT_NONBOURNE (OPT_ALL & ~OPT_BOURNE) +#define OPT_NONZSH (OPT_ALL & ~OPT_ZSH) + +/* option is relevant to emulation */ +#define OPT_EMULATE (EMULATE_UNUSED) +/* option should never be set by emulate() */ +#define OPT_SPECIAL (EMULATE_UNUSED<<1) +/* option is an alias to an other option */ +#define OPT_ALIAS (EMULATE_UNUSED<<2) + +#define defset(X, my_emulation) (!!((X)->node.flags & my_emulation)) + +/* + * Note that option names should usually be fewer than 20 characters long + * to avoid formatting problems. + */ +static struct optname optns[] = { +{{NULL, "aliases", OPT_EMULATE|OPT_ALL}, ALIASESOPT}, +{{NULL, "aliasfuncdef", OPT_EMULATE|OPT_BOURNE}, ALIASFUNCDEF}, +{{NULL, "allexport", OPT_EMULATE}, ALLEXPORT}, +{{NULL, "alwayslastprompt", OPT_ALL}, ALWAYSLASTPROMPT}, +{{NULL, "alwaystoend", 0}, ALWAYSTOEND}, +{{NULL, "appendcreate", OPT_EMULATE|OPT_BOURNE}, APPENDCREATE}, +{{NULL, "appendhistory", OPT_ALL}, APPENDHISTORY}, +{{NULL, "autocd", OPT_EMULATE}, AUTOCD}, +{{NULL, "autocontinue", 0}, AUTOCONTINUE}, +{{NULL, "autolist", OPT_ALL}, AUTOLIST}, +{{NULL, "automenu", OPT_ALL}, AUTOMENU}, +{{NULL, "autonamedirs", 0}, AUTONAMEDIRS}, +{{NULL, "autoparamkeys", OPT_ALL}, AUTOPARAMKEYS}, +{{NULL, "autoparamslash", OPT_ALL}, AUTOPARAMSLASH}, +{{NULL, "autopushd", 0}, AUTOPUSHD}, +{{NULL, "autoremoveslash", OPT_ALL}, AUTOREMOVESLASH}, +{{NULL, "autoresume", 0}, AUTORESUME}, +{{NULL, "badpattern", OPT_EMULATE|OPT_NONBOURNE},BADPATTERN}, +{{NULL, "banghist", OPT_NONBOURNE}, BANGHIST}, +{{NULL, "bareglobqual", OPT_EMULATE|OPT_ZSH}, BAREGLOBQUAL}, +{{NULL, "bashautolist", 0}, BASHAUTOLIST}, +{{NULL, "bashrematch", 0}, BASHREMATCH}, +{{NULL, "beep", OPT_ALL}, BEEP}, +{{NULL, "bgnice", OPT_EMULATE|OPT_NONBOURNE},BGNICE}, +{{NULL, "braceccl", OPT_EMULATE}, BRACECCL}, +{{NULL, "bsdecho", OPT_EMULATE|OPT_SH}, BSDECHO}, +{{NULL, "caseglob", OPT_ALL}, CASEGLOB}, +{{NULL, "casematch", OPT_ALL}, CASEMATCH}, +{{NULL, "cbases", 0}, CBASES}, +{{NULL, "cprecedences", OPT_EMULATE|OPT_NONZSH}, CPRECEDENCES}, +{{NULL, "cdablevars", OPT_EMULATE}, CDABLEVARS}, +{{NULL, "chasedots", OPT_EMULATE}, CHASEDOTS}, +{{NULL, "chaselinks", OPT_EMULATE}, CHASELINKS}, +{{NULL, "checkjobs", OPT_EMULATE|OPT_ZSH}, CHECKJOBS}, +{{NULL, "checkrunningjobs", OPT_EMULATE|OPT_ZSH}, CHECKRUNNINGJOBS}, +{{NULL, "clobber", OPT_EMULATE|OPT_ALL}, CLOBBER}, +{{NULL, "combiningchars", 0}, COMBININGCHARS}, +{{NULL, "completealiases", 0}, COMPLETEALIASES}, +{{NULL, "completeinword", 0}, COMPLETEINWORD}, +{{NULL, "continueonerror", 0}, CONTINUEONERROR}, +{{NULL, "correct", 0}, CORRECT}, +{{NULL, "correctall", 0}, CORRECTALL}, +{{NULL, "cshjunkiehistory", OPT_EMULATE|OPT_CSH}, CSHJUNKIEHISTORY}, +{{NULL, "cshjunkieloops", OPT_EMULATE|OPT_CSH}, CSHJUNKIELOOPS}, +{{NULL, "cshjunkiequotes", OPT_EMULATE|OPT_CSH}, CSHJUNKIEQUOTES}, +{{NULL, "cshnullcmd", OPT_EMULATE|OPT_CSH}, CSHNULLCMD}, +{{NULL, "cshnullglob", OPT_EMULATE|OPT_CSH}, CSHNULLGLOB}, +{{NULL, "debugbeforecmd", OPT_ALL}, DEBUGBEFORECMD}, +{{NULL, "emacs", 0}, EMACSMODE}, +{{NULL, "equals", OPT_EMULATE|OPT_ZSH}, EQUALS}, +{{NULL, "errexit", OPT_EMULATE}, ERREXIT}, +{{NULL, "errreturn", OPT_EMULATE}, ERRRETURN}, +{{NULL, "exec", OPT_ALL}, EXECOPT}, +{{NULL, "extendedglob", OPT_EMULATE}, EXTENDEDGLOB}, +{{NULL, "extendedhistory", OPT_CSH}, EXTENDEDHISTORY}, +{{NULL, "evallineno", OPT_EMULATE|OPT_ZSH}, EVALLINENO}, +{{NULL, "flowcontrol", OPT_ALL}, FLOWCONTROL}, +{{NULL, "forcefloat", 0}, FORCEFLOAT}, +{{NULL, "functionargzero", OPT_EMULATE|OPT_NONBOURNE},FUNCTIONARGZERO}, +{{NULL, "glob", OPT_EMULATE|OPT_ALL}, GLOBOPT}, +{{NULL, "globalexport", OPT_EMULATE|OPT_ZSH}, GLOBALEXPORT}, +{{NULL, "globalrcs", OPT_ALL}, GLOBALRCS}, +{{NULL, "globassign", OPT_EMULATE|OPT_CSH}, GLOBASSIGN}, +{{NULL, "globcomplete", 0}, GLOBCOMPLETE}, +{{NULL, "globdots", OPT_EMULATE}, GLOBDOTS}, +{{NULL, "globstarshort", OPT_EMULATE}, GLOBSTARSHORT}, +{{NULL, "globsubst", OPT_EMULATE|OPT_NONZSH}, GLOBSUBST}, +{{NULL, "hashcmds", OPT_ALL}, HASHCMDS}, +{{NULL, "hashdirs", OPT_ALL}, HASHDIRS}, +{{NULL, "hashexecutablesonly", 0}, HASHEXECUTABLESONLY}, +{{NULL, "hashlistall", OPT_ALL}, HASHLISTALL}, +{{NULL, "histallowclobber", 0}, HISTALLOWCLOBBER}, +{{NULL, "histbeep", OPT_ALL}, HISTBEEP}, +{{NULL, "histexpiredupsfirst",0}, HISTEXPIREDUPSFIRST}, +{{NULL, "histfcntllock", 0}, HISTFCNTLLOCK}, +{{NULL, "histfindnodups", 0}, HISTFINDNODUPS}, +{{NULL, "histignorealldups", 0}, HISTIGNOREALLDUPS}, +{{NULL, "histignoredups", 0}, HISTIGNOREDUPS}, +{{NULL, "histignorespace", 0}, HISTIGNORESPACE}, +{{NULL, "histlexwords", 0}, HISTLEXWORDS}, +{{NULL, "histnofunctions", 0}, HISTNOFUNCTIONS}, +{{NULL, "histnostore", 0}, HISTNOSTORE}, +{{NULL, "histsubstpattern", OPT_EMULATE}, HISTSUBSTPATTERN}, +{{NULL, "histreduceblanks", 0}, HISTREDUCEBLANKS}, +{{NULL, "histsavebycopy", OPT_ALL}, HISTSAVEBYCOPY}, +{{NULL, "histsavenodups", 0}, HISTSAVENODUPS}, +{{NULL, "histverify", 0}, HISTVERIFY}, +{{NULL, "hup", OPT_EMULATE|OPT_ZSH}, HUP}, +{{NULL, "ignorebraces", OPT_EMULATE|OPT_SH}, IGNOREBRACES}, +{{NULL, "ignoreclosebraces", OPT_EMULATE}, IGNORECLOSEBRACES}, +{{NULL, "ignoreeof", 0}, IGNOREEOF}, +{{NULL, "incappendhistory", 0}, INCAPPENDHISTORY}, +{{NULL, "incappendhistorytime", 0}, INCAPPENDHISTORYTIME}, +{{NULL, "interactive", OPT_SPECIAL}, INTERACTIVE}, +{{NULL, "interactivecomments",OPT_BOURNE}, INTERACTIVECOMMENTS}, +{{NULL, "ksharrays", OPT_EMULATE|OPT_BOURNE}, KSHARRAYS}, +{{NULL, "kshautoload", OPT_EMULATE|OPT_BOURNE}, KSHAUTOLOAD}, +{{NULL, "kshglob", OPT_EMULATE|OPT_KSH}, KSHGLOB}, +{{NULL, "kshoptionprint", OPT_EMULATE|OPT_KSH}, KSHOPTIONPRINT}, +{{NULL, "kshtypeset", 0}, KSHTYPESET}, +{{NULL, "kshzerosubscript", 0}, KSHZEROSUBSCRIPT}, +{{NULL, "listambiguous", OPT_ALL}, LISTAMBIGUOUS}, +{{NULL, "listbeep", OPT_ALL}, LISTBEEP}, +{{NULL, "listpacked", 0}, LISTPACKED}, +{{NULL, "listrowsfirst", 0}, LISTROWSFIRST}, +{{NULL, "listtypes", OPT_ALL}, LISTTYPES}, +{{NULL, "localoptions", OPT_EMULATE|OPT_KSH}, LOCALOPTIONS}, +{{NULL, "localloops", OPT_EMULATE}, LOCALLOOPS}, +{{NULL, "localpatterns", OPT_EMULATE}, LOCALPATTERNS}, +{{NULL, "localtraps", OPT_EMULATE|OPT_KSH}, LOCALTRAPS}, +{{NULL, "login", OPT_SPECIAL}, LOGINSHELL}, +{{NULL, "longlistjobs", 0}, LONGLISTJOBS}, +{{NULL, "magicequalsubst", OPT_EMULATE}, MAGICEQUALSUBST}, +{{NULL, "mailwarning", 0}, MAILWARNING}, +{{NULL, "markdirs", 0}, MARKDIRS}, +{{NULL, "menucomplete", 0}, MENUCOMPLETE}, +{{NULL, "monitor", OPT_SPECIAL}, MONITOR}, +{{NULL, "multibyte", +#ifdef MULTIBYTE_SUPPORT + OPT_ALL +#else + 0 +#endif + }, MULTIBYTE}, +{{NULL, "multifuncdef", OPT_EMULATE|OPT_ZSH}, MULTIFUNCDEF}, +{{NULL, "multios", OPT_EMULATE|OPT_ZSH}, MULTIOS}, +{{NULL, "nomatch", OPT_EMULATE|OPT_NONBOURNE},NOMATCH}, +{{NULL, "notify", OPT_ZSH}, NOTIFY}, +{{NULL, "nullglob", OPT_EMULATE}, NULLGLOB}, +{{NULL, "numericglobsort", OPT_EMULATE}, NUMERICGLOBSORT}, +{{NULL, "octalzeroes", OPT_EMULATE|OPT_SH}, OCTALZEROES}, +{{NULL, "overstrike", 0}, OVERSTRIKE}, +{{NULL, "pathdirs", OPT_EMULATE}, PATHDIRS}, +{{NULL, "pathscript", OPT_EMULATE|OPT_BOURNE}, PATHSCRIPT}, +{{NULL, "pipefail", OPT_EMULATE}, PIPEFAIL}, +{{NULL, "posixaliases", OPT_EMULATE|OPT_BOURNE}, POSIXALIASES}, +{{NULL, "posixargzero", OPT_EMULATE}, POSIXARGZERO}, +{{NULL, "posixbuiltins", OPT_EMULATE|OPT_BOURNE}, POSIXBUILTINS}, +{{NULL, "posixcd", OPT_EMULATE|OPT_BOURNE}, POSIXCD}, +{{NULL, "posixidentifiers", OPT_EMULATE|OPT_BOURNE}, POSIXIDENTIFIERS}, +{{NULL, "posixjobs", OPT_EMULATE|OPT_BOURNE}, POSIXJOBS}, +{{NULL, "posixstrings", OPT_EMULATE|OPT_BOURNE}, POSIXSTRINGS}, +{{NULL, "posixtraps", OPT_EMULATE|OPT_BOURNE}, POSIXTRAPS}, +{{NULL, "printeightbit", 0}, PRINTEIGHTBIT}, +{{NULL, "printexitvalue", 0}, PRINTEXITVALUE}, +{{NULL, "privileged", OPT_SPECIAL}, PRIVILEGED}, +{{NULL, "promptbang", OPT_KSH}, PROMPTBANG}, +{{NULL, "promptcr", OPT_ALL}, PROMPTCR}, +{{NULL, "promptpercent", OPT_NONBOURNE}, PROMPTPERCENT}, +{{NULL, "promptsp", OPT_ALL}, PROMPTSP}, +{{NULL, "promptsubst", OPT_BOURNE}, PROMPTSUBST}, +{{NULL, "pushdignoredups", OPT_EMULATE}, PUSHDIGNOREDUPS}, +{{NULL, "pushdminus", OPT_EMULATE}, PUSHDMINUS}, +{{NULL, "pushdsilent", 0}, PUSHDSILENT}, +{{NULL, "pushdtohome", OPT_EMULATE}, PUSHDTOHOME}, +{{NULL, "rcexpandparam", OPT_EMULATE}, RCEXPANDPARAM}, +{{NULL, "rcquotes", OPT_EMULATE}, RCQUOTES}, +{{NULL, "rcs", OPT_ALL}, RCS}, +{{NULL, "recexact", 0}, RECEXACT}, +{{NULL, "rematchpcre", 0}, REMATCHPCRE}, +{{NULL, "restricted", OPT_SPECIAL}, RESTRICTED}, +{{NULL, "rmstarsilent", OPT_BOURNE}, RMSTARSILENT}, +{{NULL, "rmstarwait", 0}, RMSTARWAIT}, +{{NULL, "sharehistory", OPT_KSH}, SHAREHISTORY}, +{{NULL, "shfileexpansion", OPT_EMULATE|OPT_BOURNE}, SHFILEEXPANSION}, +{{NULL, "shglob", OPT_EMULATE|OPT_BOURNE}, SHGLOB}, +{{NULL, "shinstdin", OPT_SPECIAL}, SHINSTDIN}, +{{NULL, "shnullcmd", OPT_EMULATE|OPT_BOURNE}, SHNULLCMD}, +{{NULL, "shoptionletters", OPT_EMULATE|OPT_BOURNE}, SHOPTIONLETTERS}, +{{NULL, "shortloops", OPT_EMULATE|OPT_NONBOURNE},SHORTLOOPS}, +{{NULL, "shwordsplit", OPT_EMULATE|OPT_BOURNE}, SHWORDSPLIT}, +{{NULL, "singlecommand", OPT_SPECIAL}, SINGLECOMMAND}, +{{NULL, "singlelinezle", OPT_KSH}, SINGLELINEZLE}, +{{NULL, "sourcetrace", 0}, SOURCETRACE}, +{{NULL, "sunkeyboardhack", 0}, SUNKEYBOARDHACK}, +{{NULL, "transientrprompt", 0}, TRANSIENTRPROMPT}, +{{NULL, "trapsasync", 0}, TRAPSASYNC}, +{{NULL, "typesetsilent", OPT_EMULATE|OPT_BOURNE}, TYPESETSILENT}, +{{NULL, "unset", OPT_EMULATE|OPT_BSHELL}, UNSET}, +{{NULL, "verbose", 0}, VERBOSE}, +{{NULL, "vi", 0}, VIMODE}, +{{NULL, "warncreateglobal", OPT_EMULATE}, WARNCREATEGLOBAL}, +{{NULL, "warnnestedvar", OPT_EMULATE}, WARNNESTEDVAR}, +{{NULL, "xtrace", 0}, XTRACE}, +{{NULL, "zle", OPT_SPECIAL}, USEZLE}, +{{NULL, "braceexpand", OPT_ALIAS}, /* ksh/bash */ -IGNOREBRACES}, +{{NULL, "dotglob", OPT_ALIAS}, /* bash */ GLOBDOTS}, +{{NULL, "hashall", OPT_ALIAS}, /* bash */ HASHCMDS}, +{{NULL, "histappend", OPT_ALIAS}, /* bash */ APPENDHISTORY}, +{{NULL, "histexpand", OPT_ALIAS}, /* bash */ BANGHIST}, +{{NULL, "log", OPT_ALIAS}, /* ksh */ -HISTNOFUNCTIONS}, +{{NULL, "mailwarn", OPT_ALIAS}, /* bash */ MAILWARNING}, +{{NULL, "onecmd", OPT_ALIAS}, /* bash */ SINGLECOMMAND}, +{{NULL, "physical", OPT_ALIAS}, /* ksh/bash */ CHASELINKS}, +{{NULL, "promptvars", OPT_ALIAS}, /* bash */ PROMPTSUBST}, +{{NULL, "stdin", OPT_ALIAS}, /* ksh */ SHINSTDIN}, +{{NULL, "trackall", OPT_ALIAS}, /* ksh */ HASHCMDS}, +{{NULL, "dvorak", 0}, DVORAK}, +{{NULL, NULL, 0}, 0} +}; + +/* Option letters */ + +#define optletters (isset(SHOPTIONLETTERS) ? kshletters : zshletters) + +#define FIRST_OPT '0' +#define LAST_OPT 'y' + +static short zshletters[LAST_OPT - FIRST_OPT + 1] = { + /* 0 */ CORRECT, + /* 1 */ PRINTEXITVALUE, + /* 2 */ -BADPATTERN, + /* 3 */ -NOMATCH, + /* 4 */ GLOBDOTS, + /* 5 */ NOTIFY, + /* 6 */ BGNICE, + /* 7 */ IGNOREEOF, + /* 8 */ MARKDIRS, + /* 9 */ AUTOLIST, + /* : */ 0, + /* ; */ 0, + /* < */ 0, + /* = */ 0, + /* > */ 0, + /* ? */ 0, + /* @ */ 0, + /* A */ 0, /* use with set for arrays */ + /* B */ -BEEP, + /* C */ -CLOBBER, + /* D */ PUSHDTOHOME, + /* E */ PUSHDSILENT, + /* F */ -GLOBOPT, + /* G */ NULLGLOB, + /* H */ RMSTARSILENT, + /* I */ IGNOREBRACES, + /* J */ AUTOCD, + /* K */ -BANGHIST, + /* L */ SUNKEYBOARDHACK, + /* M */ SINGLELINEZLE, + /* N */ AUTOPUSHD, + /* O */ CORRECTALL, + /* P */ RCEXPANDPARAM, + /* Q */ PATHDIRS, + /* R */ LONGLISTJOBS, + /* S */ RECEXACT, + /* T */ CDABLEVARS, + /* U */ MAILWARNING, + /* V */ -PROMPTCR, + /* W */ AUTORESUME, + /* X */ LISTTYPES, + /* Y */ MENUCOMPLETE, + /* Z */ USEZLE, + /* [ */ 0, + /* \ */ 0, + /* ] */ 0, + /* ^ */ 0, + /* _ */ 0, + /* ` */ 0, + /* a */ ALLEXPORT, + /* b */ 0, /* in non-Bourne shells, end of options */ + /* c */ 0, /* command follows */ + /* d */ -GLOBALRCS, + /* e */ ERREXIT, + /* f */ -RCS, + /* g */ HISTIGNORESPACE, + /* h */ HISTIGNOREDUPS, + /* i */ INTERACTIVE, + /* j */ 0, + /* k */ INTERACTIVECOMMENTS, + /* l */ LOGINSHELL, + /* m */ MONITOR, + /* n */ -EXECOPT, + /* o */ 0, /* long option name follows */ + /* p */ PRIVILEGED, + /* q */ 0, + /* r */ RESTRICTED, + /* s */ SHINSTDIN, + /* t */ SINGLECOMMAND, + /* u */ -UNSET, + /* v */ VERBOSE, + /* w */ CHASELINKS, + /* x */ XTRACE, + /* y */ SHWORDSPLIT, +}; + +static short kshletters[LAST_OPT - FIRST_OPT + 1] = { + /* 0 */ 0, + /* 1 */ 0, + /* 2 */ 0, + /* 3 */ 0, + /* 4 */ 0, + /* 5 */ 0, + /* 6 */ 0, + /* 7 */ 0, + /* 8 */ 0, + /* 9 */ 0, + /* : */ 0, + /* ; */ 0, + /* < */ 0, + /* = */ 0, + /* > */ 0, + /* ? */ 0, + /* @ */ 0, + /* A */ 0, + /* B */ 0, + /* C */ -CLOBBER, + /* D */ 0, + /* E */ 0, + /* F */ 0, + /* G */ 0, + /* H */ 0, + /* I */ 0, + /* J */ 0, + /* K */ 0, + /* L */ 0, + /* M */ 0, + /* N */ 0, + /* O */ 0, + /* P */ 0, + /* Q */ 0, + /* R */ 0, + /* S */ 0, + /* T */ TRAPSASYNC, + /* U */ 0, + /* V */ 0, + /* W */ 0, + /* X */ MARKDIRS, + /* Y */ 0, + /* Z */ 0, + /* [ */ 0, + /* \ */ 0, + /* ] */ 0, + /* ^ */ 0, + /* _ */ 0, + /* ` */ 0, + /* a */ ALLEXPORT, + /* b */ NOTIFY, + /* c */ 0, + /* d */ 0, + /* e */ ERREXIT, + /* f */ -GLOBOPT, + /* g */ 0, + /* h */ 0, + /* i */ INTERACTIVE, + /* j */ 0, + /* k */ 0, + /* l */ LOGINSHELL, + /* m */ MONITOR, + /* n */ -EXECOPT, + /* o */ 0, + /* p */ PRIVILEGED, + /* q */ 0, + /* r */ RESTRICTED, + /* s */ SHINSTDIN, + /* t */ SINGLECOMMAND, + /* u */ -UNSET, + /* v */ VERBOSE, + /* w */ 0, + /* x */ XTRACE, + /* y */ 0, +}; + +/* Initialisation of the option name hash table */ + +/**/ +static void +printoptionnode(HashNode hn, int set) +{ + Optname on = (Optname) hn; + int optno = on->optno; + + if (optno < 0) + optno = -optno; + if (isset(KSHOPTIONPRINT)) { + if (defset(on, emulation)) + printf("no%-19s %s\n", on->node.nam, isset(optno) ? "off" : "on"); + else + printf("%-21s %s\n", on->node.nam, isset(optno) ? "on" : "off"); + } else if (set == (isset(optno) ^ defset(on, emulation))) { + if (set ^ isset(optno)) + fputs("no", stdout); + puts(on->node.nam); + } +} + +/**/ +void +createoptiontable(void) +{ + Optname on; + + optiontab = newhashtable(101, "optiontab", NULL); + + optiontab->hash = hasher; + optiontab->emptytable = NULL; + optiontab->filltable = NULL; + optiontab->cmpnodes = strcmp; + optiontab->addnode = addhashnode; + optiontab->getnode = gethashnode; + optiontab->getnode2 = gethashnode2; + optiontab->removenode = NULL; + optiontab->disablenode = disablehashnode; + optiontab->enablenode = enablehashnode; + optiontab->freenode = NULL; + optiontab->printnode = printoptionnode; + + for (on = optns; on->node.nam; on++) + optiontab->addnode(optiontab, on->node.nam, on); +} + +/* Emulation appropriate to the setemulate function */ + +static int setemulate_emulation; + +/* Option array manipulated within the setemulate function */ + +/**/ +static char *setemulate_opts; + +/* Setting of default options */ + +/**/ +static void +setemulate(HashNode hn, int fully) +{ + Optname on = (Optname) hn; + + /* Set options: each non-special option is set according to the * + * current emulation mode if either it is considered relevant * + * to emulation or we are doing a full emulation (as indicated * + * by the `fully' parameter). */ + if (!(on->node.flags & OPT_ALIAS) && + ((fully && !(on->node.flags & OPT_SPECIAL)) || + (on->node.flags & OPT_EMULATE))) + setemulate_opts[on->optno] = defset(on, setemulate_emulation); +} + +/**/ +void +installemulation(int new_emulation, char *new_opts) +{ + setemulate_emulation = new_emulation; + setemulate_opts = new_opts; + scanhashtable(optiontab, 0, 0, 0, setemulate, + !!(new_emulation & EMULATE_FULLY)); +} + +/**/ +void +emulate(const char *zsh_name, int fully, int *new_emulation, char *new_opts) +{ + char ch = *zsh_name; + + if (ch == 'r') + ch = zsh_name[1]; + + /* Work out the new emulation mode */ + if (ch == 'c') + *new_emulation = EMULATE_CSH; + else if (ch == 'k') + *new_emulation = EMULATE_KSH; + else if (ch == 's' || ch == 'b') + *new_emulation = EMULATE_SH; + else + *new_emulation = EMULATE_ZSH; + + if (fully) + *new_emulation |= EMULATE_FULLY; + installemulation(*new_emulation, new_opts); + + if (funcstack && funcstack->tp == FS_FUNC) { + /* + * We are inside a function. Decide if it's traced. + * Pedantic note: the function in the function table isn't + * guaranteed to be what we're executing, but it's + * close enough. + */ + Shfunc shf = (Shfunc)shfunctab->getnode(shfunctab, funcstack->name); + if (shf && (shf->node.flags & (PM_TAGGED|PM_TAGGED_LOCAL))) { + /* Tracing is on, so set xtrace */ + new_opts[XTRACE] = 1; + } + } +} + +/* setopt, unsetopt */ + +/**/ +static void +setoption(HashNode hn, int value) +{ + dosetopt(((Optname) hn)->optno, value, 0, opts); +} + +/**/ +int +bin_setopt(char *nam, char **args, UNUSED(Options ops), int isun) +{ + int action, optno, match = 0; + + /* With no arguments or options, display options. */ + if (!*args) { + scanhashtable(optiontab, 1, 0, OPT_ALIAS, optiontab->printnode, !isun); + return 0; + } + + /* loop through command line options (begins with "-" or "+") */ + while (*args && (**args == '-' || **args == '+')) { + action = (**args == '-') ^ isun; + if(!args[0][1]) + *args = "--"; + while (*++*args) { + if(**args == Meta) + *++*args ^= 32; + /* The pseudo-option `--' signifies the end of options. */ + if (**args == '-') { + args++; + goto doneoptions; + } else if (**args == 'o') { + if (!*++*args) + args++; + if (!*args) { + zwarnnam(nam, "string expected after -o"); + inittyptab(); + return 1; + } + if(!(optno = optlookup(*args))) + zwarnnam(nam, "no such option: %s", *args); + else if(dosetopt(optno, action, 0, opts)) + zwarnnam(nam, "can't change option: %s", *args); + break; + } else if(**args == 'm') { + match = 1; + } else { + if (!(optno = optlookupc(**args))) + zwarnnam(nam, "bad option: -%c", **args); + else if(dosetopt(optno, action, 0, opts)) + zwarnnam(nam, "can't change option: -%c", **args); + } + } + args++; + } + doneoptions: + + if (!match) { + /* Not globbing the arguments -- arguments are simply option names. */ + while (*args) { + if(!(optno = optlookup(*args++))) + zwarnnam(nam, "no such option: %s", args[-1]); + else if(dosetopt(optno, !isun, 0, opts)) + zwarnnam(nam, "can't change option: %s", args[-1]); + } + } else { + /* Globbing option (-m) set. */ + while (*args) { + Patprog pprog; + char *s, *t; + + t = s = dupstring(*args); + while (*t) + if (*t == '_') + chuck(t); + else { + /* See comment in optlookup() */ + if (*t >= 'A' && *t <= 'Z') + *t = (*t - 'A') + 'a'; + t++; + } + + /* Expand the current arg. */ + tokenize(s); + if (!(pprog = patcompile(s, PAT_HEAPDUP, NULL))) { + zwarnnam(nam, "bad pattern: %s", *args); + continue; + } + /* Loop over expansions. */ + scanmatchtable(optiontab, pprog, 0, 0, OPT_ALIAS, + setoption, !isun); + args++; + } + } + inittyptab(); + return 0; +} + +/* Identify an option name */ + +/**/ +mod_export int +optlookup(char const *name) +{ + char *s, *t; + Optname n; + + s = t = dupstring(name); + + /* exorcise underscores, and change to lowercase */ + while (*t) + if (*t == '_') + chuck(t); + else { + /* + * Some locales (in particular tr_TR.UTF-8) may + * have non-standard mappings of ASCII characters, + * so be careful. Option names must be ASCII so + * we don't need to be too clever. + */ + if (*t >= 'A' && *t <= 'Z') + *t = (*t - 'A') + 'a'; + t++; + } + + /* look up name in the table */ + if (s[0] == 'n' && s[1] == 'o' && + (n = (Optname) optiontab->getnode(optiontab, s + 2))) { + return -n->optno; + } else if ((n = (Optname) optiontab->getnode(optiontab, s))) + return n->optno; + else + return OPT_INVALID; +} + +/* Identify an option letter */ + +/**/ +int +optlookupc(char c) +{ + if(c < FIRST_OPT || c > LAST_OPT) + return 0; + + return optletters[c - FIRST_OPT]; +} + +/**/ +static void +restrictparam(char *nam) +{ + Param pm = (Param) paramtab->getnode(paramtab, nam); + + if (pm) { + pm->node.flags |= PM_SPECIAL | PM_RESTRICTED; + return; + } + createparam(nam, PM_SCALAR | PM_UNSET | PM_SPECIAL | PM_RESTRICTED); +} + +/* list of restricted parameters which are not otherwise special */ +static char *rparams[] = { + "SHELL", "HISTFILE", "LD_LIBRARY_PATH", "LD_AOUT_LIBRARY_PATH", + "LD_PRELOAD", "LD_AOUT_PRELOAD", NULL +}; + +/* Set or unset an option, as a result of user request. The option * + * number may be negative, indicating that the sense is reversed * + * from the usual meaning of the option. */ + +/**/ +mod_export int +dosetopt(int optno, int value, int force, char *new_opts) +{ + if(!optno) + return -1; + if(optno < 0) { + optno = -optno; + value = !value; + } + if (optno == RESTRICTED) { + if (isset(RESTRICTED)) + return value ? 0 : -1; + if (value) { + char **s; + + for (s = rparams; *s; s++) + restrictparam(*s); + } + } else if(!force && optno == EXECOPT && !value && interact) { + /* cannot set noexec when interactive */ + return -1; + } else if(!force && (optno == INTERACTIVE || optno == SHINSTDIN || + optno == SINGLECOMMAND)) { + if (new_opts[optno] == value) + return 0; + /* it is not permitted to change the value of these options */ + return -1; + } else if(!force && optno == USEZLE && value) { + /* we require a terminal in order to use ZLE */ + if(!interact || SHTTY == -1 || !shout) + return -1; + } else if(optno == PRIVILEGED && !value) { + /* unsetting PRIVILEGED causes the shell to make itself unprivileged */ +#ifdef HAVE_SETUID + int ignore_err; + errno = 0; + /* + * Set the GID first as if we set the UID to non-privileged it + * might be impossible to restore the GID. + * + * Some OSes (possibly no longer around) have been known to + * fail silently the first time, so we attempt the change twice. + * If it fails we are guaranteed to pick this up the second + * time, so ignore the first time. + * + * Some versions of gcc make it hard to ignore the results the + * first time, hence the following. (These are probably not + * systems that require the doubled calls.) + */ + ignore_err = setgid(getgid()); + (void)ignore_err; + ignore_err = setuid(getuid()); + (void)ignore_err; + if (setgid(getgid())) { + zwarn("failed to change group ID: %e", errno); + return -1; + } else if (setuid(getuid())) { + zwarn("failed to change user ID: %e", errno); + return -1; + } +#else + zwarn("setuid not available"); + return -1; +#endif /* not HAVE_SETUID */ +#ifdef JOB_CONTROL + } else if (!force && optno == MONITOR && value) { + if (new_opts[optno] == value) + return 0; + if (SHTTY != -1) { + origpgrp = GETPGRP(); + acquire_pgrp(); + } else + return -1; +#else + } else if(optno == MONITOR && value) { + return -1; +#endif /* not JOB_CONTROL */ +#ifdef GETPWNAM_FAKED + } else if(optno == CDABLEVARS && value) { + return -1; +#endif /* GETPWNAM_FAKED */ + } else if ((optno == EMACSMODE || optno == VIMODE) && value) { + if (sticky && sticky->emulation) + return -1; + zleentry(ZLE_CMD_SET_KEYMAP, optno); + new_opts[(optno == EMACSMODE) ? VIMODE : EMACSMODE] = 0; + } else if (optno == SUNKEYBOARDHACK) { + /* for backward compatibility */ + keyboardhackchar = (value ? '`' : '\0'); + } + new_opts[optno] = value; + if (optno == BANGHIST || optno == SHINSTDIN) + inittyptab(); + return 0; +} + +/* Function to get value for special parameter `-' */ + +/**/ +char * +dashgetfn(UNUSED(Param pm)) +{ + static char buf[LAST_OPT - FIRST_OPT + 2]; + char *val = buf; + int i; + + for(i = 0; i <= LAST_OPT - FIRST_OPT; i++) { + int optno = optletters[i]; + if(optno && ((optno > 0) ? isset(optno) : unset(-optno))) + *val++ = FIRST_OPT + i; + } + *val = '\0'; + return buf; +} + +/* print options for set -o/+o */ + +/**/ +void +printoptionstates(int hadplus) +{ + scanhashtable(optiontab, 1, 0, OPT_ALIAS, printoptionnodestate, hadplus); +} + +/**/ +static void +printoptionnodestate(HashNode hn, int hadplus) +{ + Optname on = (Optname) hn; + int optno = on->optno; + + if (hadplus) { + printf("set %co %s%s\n", + defset(on, emulation) != isset(optno) ? '-' : '+', + defset(on, emulation) ? "no" : "", + on->node.nam); + } else { + if (defset(on, emulation)) + printf("no%-19s %s\n", on->node.nam, isset(optno) ? "off" : "on"); + else + printf("%-21s %s\n", on->node.nam, isset(optno) ? "on" : "off"); + } +} + +/* Print option list for --help */ + +/**/ +void +printoptionlist(void) +{ + short *lp; + char c; + + printf("\nNamed options:\n"); + scanhashtable(optiontab, 1, 0, OPT_ALIAS, printoptionlist_printoption, 0); + printf("\nOption aliases:\n"); + scanhashtable(optiontab, 1, OPT_ALIAS, 0, printoptionlist_printoption, 0); + printf("\nOption letters:\n"); + for(lp = optletters, c = FIRST_OPT; c <= LAST_OPT; lp++, c++) { + if(!*lp) + continue; + printf(" -%c ", c); + printoptionlist_printequiv(*lp); + } +} + +/**/ +static void +printoptionlist_printoption(HashNode hn, UNUSED(int ignored)) +{ + Optname on = (Optname) hn; + + if(on->node.flags & OPT_ALIAS) { + printf(" --%-19s ", on->node.nam); + printoptionlist_printequiv(on->optno); + } else + printf(" --%s\n", on->node.nam); +} + +/**/ +static void +printoptionlist_printequiv(int optno) +{ + int isneg = optno < 0; + + optno *= (isneg ? -1 : 1); + printf(" equivalent to --%s%s\n", isneg ? "no-" : "", optns[optno-1].node.nam); +} + +/**/ +static char *print_emulate_opts; + +/**/ +static void +print_emulate_option(HashNode hn, int fully) +{ + Optname on = (Optname) hn; + + if (!(on->node.flags & OPT_ALIAS) && + ((fully && !(on->node.flags & OPT_SPECIAL)) || + (on->node.flags & OPT_EMULATE))) + { + if (!print_emulate_opts[on->optno]) + fputs("no", stdout); + puts(on->node.nam); + } +} + +/* + * List the settings of options associated with an emulation + */ + +/**/ +void list_emulate_options(char *cmdopts, int fully) +{ + print_emulate_opts = cmdopts; + scanhashtable(optiontab, 1, 0, 0, print_emulate_option, fully); +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/params.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/params.c new file mode 100644 index 00000000..a1c299f6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/params.c @@ -0,0 +1,5884 @@ +/* + * params.c - parameters + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "params.pro" + +#include "version.h" +#ifdef CUSTOM_PATCHLEVEL +#define ZSH_PATCHLEVEL CUSTOM_PATCHLEVEL +#else +#include "patchlevel.h" + +#include + +/* If removed from the ChangeLog for some reason */ +#ifndef ZSH_PATCHLEVEL +#define ZSH_PATCHLEVEL "unknown" +#endif +#endif + +/* what level of localness we are at */ + +/**/ +mod_export int locallevel; + +/* Variables holding values of special parameters */ + +/**/ +mod_export +char **pparams, /* $argv */ + **cdpath, /* $cdpath */ + **fpath, /* $fpath */ + **mailpath, /* $mailpath */ + **manpath, /* $manpath */ + **psvar, /* $psvar */ + **watch, /* $watch */ + **zsh_eval_context; /* $zsh_eval_context */ +/**/ +mod_export +char **path, /* $path */ + **fignore; /* $fignore */ + +/**/ +mod_export +char *argzero, /* $0 */ + *posixzero, /* $0 */ + *home, /* $HOME */ + *nullcmd, /* $NULLCMD */ + *oldpwd, /* $OLDPWD */ + *zoptarg, /* $OPTARG */ + *prompt, /* $PROMPT */ + *prompt2, /* $PROMPT2 */ + *prompt3, /* $PROMPT3 */ + *prompt4, /* $PROMPT4 */ + *readnullcmd, /* $READNULLCMD */ + *rprompt, /* $RPROMPT */ + *rprompt2, /* $RPROMPT2 */ + *sprompt, /* $SPROMPT */ + *wordchars; /* $WORDCHARS */ +/**/ +mod_export +char *ifs, /* $IFS */ + *postedit, /* $POSTEDIT */ + *term, /* $TERM */ + *zsh_terminfo, /* $TERMINFO */ + *zsh_terminfodirs, /* $TERMINFO_DIRS */ + *ttystrname, /* $TTY */ + *pwd; /* $PWD */ + +/**/ +mod_export +zlong lastval, /* $? */ + mypid, /* $$ */ + lastpid, /* $! */ + zterm_columns, /* $COLUMNS */ + zterm_lines, /* $LINES */ + rprompt_indent, /* $ZLE_RPROMPT_INDENT */ + ppid, /* $PPID */ + zsh_subshell; /* $ZSH_SUBSHELL */ + +/* $FUNCNEST */ +/**/ +mod_export +zlong zsh_funcnest = +#ifdef MAX_FUNCTION_DEPTH + MAX_FUNCTION_DEPTH +#else + /* Disabled by default but can be enabled at run time */ + -1 +#endif + ; + +/**/ +zlong lineno, /* $LINENO */ + zoptind, /* $OPTIND */ + shlvl; /* $SHLVL */ + +/* $histchars */ + +/**/ +mod_export unsigned char bangchar; +/**/ +unsigned char hatchar, hashchar; + +/**/ +unsigned char keyboardhackchar = '\0'; + +/* $SECONDS = now.tv_sec - shtimer.tv_sec + * + (now.tv_usec - shtimer.tv_usec) / 1000000.0 + * (rounded to an integer if the parameter is not set to float) */ + +/**/ +struct timeval shtimer; + +/* 0 if this $TERM setup is usable, otherwise it contains TERM_* flags */ + +/**/ +mod_export int termflags; + +/* Forward declaration */ + +static void +rprompt_indent_unsetfn(Param pm, int exp); + +/* Standard methods for get/set/unset pointers in parameters */ + +/**/ +mod_export const struct gsu_scalar stdscalar_gsu = +{ strgetfn, strsetfn, stdunsetfn }; +/**/ +mod_export const struct gsu_scalar varscalar_gsu = +{ strvargetfn, strvarsetfn, stdunsetfn }; +/**/ +mod_export const struct gsu_scalar nullsetscalar_gsu = +{ strgetfn, nullstrsetfn, NULL }; + +/**/ +mod_export const struct gsu_integer stdinteger_gsu = +{ intgetfn, intsetfn, stdunsetfn }; +/**/ +mod_export const struct gsu_integer varinteger_gsu = +{ intvargetfn, intvarsetfn, stdunsetfn }; +/**/ +mod_export const struct gsu_integer nullsetinteger_gsu = +{ intgetfn, NULL, NULL }; + +/**/ +mod_export const struct gsu_float stdfloat_gsu = +{ floatgetfn, floatsetfn, stdunsetfn }; + +/**/ +mod_export const struct gsu_array stdarray_gsu = +{ arrgetfn, arrsetfn, stdunsetfn }; +/**/ +mod_export const struct gsu_array vararray_gsu = +{ arrvargetfn, arrvarsetfn, stdunsetfn }; + +/**/ +mod_export const struct gsu_hash stdhash_gsu = +{ hashgetfn, hashsetfn, stdunsetfn }; +/**/ +mod_export const struct gsu_hash nullsethash_gsu = +{ hashgetfn, nullsethashfn, nullunsetfn }; + + +/* Non standard methods (not exported) */ +static const struct gsu_integer pound_gsu = +{ poundgetfn, nullintsetfn, stdunsetfn }; +static const struct gsu_integer errno_gsu = +{ errnogetfn, errnosetfn, stdunsetfn }; +static const struct gsu_integer gid_gsu = +{ gidgetfn, gidsetfn, stdunsetfn }; +static const struct gsu_integer egid_gsu = +{ egidgetfn, egidsetfn, stdunsetfn }; +static const struct gsu_integer histsize_gsu = +{ histsizegetfn, histsizesetfn, stdunsetfn }; +static const struct gsu_integer random_gsu = +{ randomgetfn, randomsetfn, stdunsetfn }; +static const struct gsu_integer savehist_gsu = +{ savehistsizegetfn, savehistsizesetfn, stdunsetfn }; +static const struct gsu_integer intseconds_gsu = +{ intsecondsgetfn, intsecondssetfn, stdunsetfn }; +static const struct gsu_float floatseconds_gsu = +{ floatsecondsgetfn, floatsecondssetfn, stdunsetfn }; +static const struct gsu_integer uid_gsu = +{ uidgetfn, uidsetfn, stdunsetfn }; +static const struct gsu_integer euid_gsu = +{ euidgetfn, euidsetfn, stdunsetfn }; +static const struct gsu_integer ttyidle_gsu = +{ ttyidlegetfn, nullintsetfn, stdunsetfn }; + +static const struct gsu_scalar argzero_gsu = +{ argzerogetfn, argzerosetfn, nullunsetfn }; +static const struct gsu_scalar username_gsu = +{ usernamegetfn, usernamesetfn, stdunsetfn }; +static const struct gsu_scalar dash_gsu = +{ dashgetfn, nullstrsetfn, stdunsetfn }; +static const struct gsu_scalar histchars_gsu = +{ histcharsgetfn, histcharssetfn, stdunsetfn }; +static const struct gsu_scalar home_gsu = +{ homegetfn, homesetfn, stdunsetfn }; +static const struct gsu_scalar term_gsu = +{ termgetfn, termsetfn, stdunsetfn }; +static const struct gsu_scalar terminfo_gsu = +{ terminfogetfn, terminfosetfn, stdunsetfn }; +static const struct gsu_scalar terminfodirs_gsu = +{ terminfodirsgetfn, terminfodirssetfn, stdunsetfn }; +static const struct gsu_scalar wordchars_gsu = +{ wordcharsgetfn, wordcharssetfn, stdunsetfn }; +static const struct gsu_scalar ifs_gsu = +{ ifsgetfn, ifssetfn, stdunsetfn }; +static const struct gsu_scalar underscore_gsu = +{ underscoregetfn, nullstrsetfn, stdunsetfn }; +static const struct gsu_scalar keyboard_hack_gsu = +{ keyboardhackgetfn, keyboardhacksetfn, stdunsetfn }; +#ifdef USE_LOCALE +static const struct gsu_scalar lc_blah_gsu = +{ strgetfn, lcsetfn, stdunsetfn }; +static const struct gsu_scalar lang_gsu = +{ strgetfn, langsetfn, stdunsetfn }; +static const struct gsu_scalar lc_all_gsu = +{ strgetfn, lc_allsetfn, stdunsetfn }; +#endif + +static const struct gsu_integer varint_readonly_gsu = +{ intvargetfn, nullintsetfn, stdunsetfn }; +static const struct gsu_integer zlevar_gsu = +{ intvargetfn, zlevarsetfn, stdunsetfn }; + +static const struct gsu_scalar colonarr_gsu = +{ colonarrgetfn, colonarrsetfn, stdunsetfn }; + +static const struct gsu_integer argc_gsu = +{ poundgetfn, nullintsetfn, stdunsetfn }; +static const struct gsu_array pipestatus_gsu = +{ pipestatgetfn, pipestatsetfn, stdunsetfn }; + +static const struct gsu_integer rprompt_indent_gsu = +{ intvargetfn, zlevarsetfn, rprompt_indent_unsetfn }; + +/* Nodes for special parameters for parameter hash table */ + +#ifdef HAVE_UNION_INIT +# define BR(X) {X} +typedef struct param initparam; +#else +# define BR(X) X +typedef struct iparam { + struct hashnode *next; + char *nam; /* hash data */ + int flags; /* PM_* flags (defined in zsh.h) */ + void *value; + void *gsu; /* get/set/unset methods */ + int base; /* output base */ + int width; /* output field width */ + char *env; /* location in environment, if exported */ + char *ename; /* name of corresponding environment var */ + Param old; /* old struct for use with local */ + int level; /* if (old != NULL), level of localness */ +} initparam; +#endif + +static initparam special_params[] ={ +#define GSU(X) BR((GsuScalar)(void *)(&(X))) +#define NULL_GSU BR((GsuScalar)(void *)NULL) +#define IPDEF1(A,B,C) {{NULL,A,PM_INTEGER|PM_SPECIAL|C},BR(NULL),GSU(B),10,0,NULL,NULL,NULL,0} +IPDEF1("#", pound_gsu, PM_READONLY), +IPDEF1("ERRNO", errno_gsu, PM_UNSET), +IPDEF1("GID", gid_gsu, PM_DONTIMPORT | PM_RESTRICTED), +IPDEF1("EGID", egid_gsu, PM_DONTIMPORT | PM_RESTRICTED), +IPDEF1("HISTSIZE", histsize_gsu, PM_RESTRICTED), +IPDEF1("RANDOM", random_gsu, 0), +IPDEF1("SAVEHIST", savehist_gsu, PM_RESTRICTED), +IPDEF1("SECONDS", intseconds_gsu, 0), +IPDEF1("UID", uid_gsu, PM_DONTIMPORT | PM_RESTRICTED), +IPDEF1("EUID", euid_gsu, PM_DONTIMPORT | PM_RESTRICTED), +IPDEF1("TTYIDLE", ttyidle_gsu, PM_READONLY), + +#define IPDEF2(A,B,C) {{NULL,A,PM_SCALAR|PM_SPECIAL|C},BR(NULL),GSU(B),0,0,NULL,NULL,NULL,0} +IPDEF2("USERNAME", username_gsu, PM_DONTIMPORT|PM_RESTRICTED), +IPDEF2("-", dash_gsu, PM_READONLY), +IPDEF2("histchars", histchars_gsu, PM_DONTIMPORT), +IPDEF2("HOME", home_gsu, PM_UNSET), +IPDEF2("TERM", term_gsu, PM_UNSET), +IPDEF2("TERMINFO", terminfo_gsu, PM_UNSET), +IPDEF2("TERMINFO_DIRS", terminfodirs_gsu, PM_UNSET), +IPDEF2("WORDCHARS", wordchars_gsu, 0), +IPDEF2("IFS", ifs_gsu, PM_DONTIMPORT | PM_RESTRICTED), +IPDEF2("_", underscore_gsu, PM_DONTIMPORT), +IPDEF2("KEYBOARD_HACK", keyboard_hack_gsu, PM_DONTIMPORT), +IPDEF2("0", argzero_gsu, 0), + +#ifdef USE_LOCALE +# define LCIPDEF(name) IPDEF2(name, lc_blah_gsu, PM_UNSET) +IPDEF2("LANG", lang_gsu, PM_UNSET), +IPDEF2("LC_ALL", lc_all_gsu, PM_UNSET), +# ifdef LC_COLLATE +LCIPDEF("LC_COLLATE"), +# endif +# ifdef LC_CTYPE +LCIPDEF("LC_CTYPE"), +# endif +# ifdef LC_MESSAGES +LCIPDEF("LC_MESSAGES"), +# endif +# ifdef LC_NUMERIC +LCIPDEF("LC_NUMERIC"), +# endif +# ifdef LC_TIME +LCIPDEF("LC_TIME"), +# endif +#endif /* USE_LOCALE */ + +#define IPDEF4(A,B) {{NULL,A,PM_INTEGER|PM_READONLY|PM_SPECIAL},BR((void *)B),GSU(varint_readonly_gsu),10,0,NULL,NULL,NULL,0} +IPDEF4("!", &lastpid), +IPDEF4("$", &mypid), +IPDEF4("?", &lastval), +IPDEF4("HISTCMD", &curhist), +IPDEF4("LINENO", &lineno), +IPDEF4("PPID", &ppid), +IPDEF4("ZSH_SUBSHELL", &zsh_subshell), + +#define IPDEF5(A,B,F) {{NULL,A,PM_INTEGER|PM_SPECIAL},BR((void *)B),GSU(F),10,0,NULL,NULL,NULL,0} +#define IPDEF5U(A,B,F) {{NULL,A,PM_INTEGER|PM_SPECIAL|PM_UNSET},BR((void *)B),GSU(F),10,0,NULL,NULL,NULL,0} +IPDEF5("COLUMNS", &zterm_columns, zlevar_gsu), +IPDEF5("LINES", &zterm_lines, zlevar_gsu), +IPDEF5U("ZLE_RPROMPT_INDENT", &rprompt_indent, rprompt_indent_gsu), +IPDEF5("SHLVL", &shlvl, varinteger_gsu), +IPDEF5("FUNCNEST", &zsh_funcnest, varinteger_gsu), + +/* Don't import internal integer status variables. */ +#define IPDEF6(A,B,F) {{NULL,A,PM_INTEGER|PM_SPECIAL|PM_DONTIMPORT},BR((void *)B),GSU(F),10,0,NULL,NULL,NULL,0} +IPDEF6("OPTIND", &zoptind, varinteger_gsu), +IPDEF6("TRY_BLOCK_ERROR", &try_errflag, varinteger_gsu), +IPDEF6("TRY_BLOCK_INTERRUPT", &try_interrupt, varinteger_gsu), + +#define IPDEF7(A,B) {{NULL,A,PM_SCALAR|PM_SPECIAL},BR((void *)B),GSU(varscalar_gsu),0,0,NULL,NULL,NULL,0} +#define IPDEF7R(A,B) {{NULL,A,PM_SCALAR|PM_SPECIAL|PM_DONTIMPORT_SUID},BR((void *)B),GSU(varscalar_gsu),0,0,NULL,NULL,NULL,0} +#define IPDEF7U(A,B) {{NULL,A,PM_SCALAR|PM_SPECIAL|PM_UNSET},BR((void *)B),GSU(varscalar_gsu),0,0,NULL,NULL,NULL,0} +IPDEF7("OPTARG", &zoptarg), +IPDEF7("NULLCMD", &nullcmd), +IPDEF7U("POSTEDIT", &postedit), +IPDEF7("READNULLCMD", &readnullcmd), +IPDEF7("PS1", &prompt), +IPDEF7U("RPS1", &rprompt), +IPDEF7U("RPROMPT", &rprompt), +IPDEF7("PS2", &prompt2), +IPDEF7U("RPS2", &rprompt2), +IPDEF7U("RPROMPT2", &rprompt2), +IPDEF7("PS3", &prompt3), +IPDEF7R("PS4", &prompt4), +IPDEF7("SPROMPT", &sprompt), + +#define IPDEF9F(A,B,C,D) {{NULL,A,D|PM_ARRAY|PM_SPECIAL|PM_DONTIMPORT},BR((void *)B),GSU(vararray_gsu),0,0,NULL,C,NULL,0} +#define IPDEF9(A,B,C) IPDEF9F(A,B,C,0) +IPDEF9F("*", &pparams, NULL, PM_ARRAY|PM_SPECIAL|PM_DONTIMPORT|PM_READONLY), +IPDEF9F("@", &pparams, NULL, PM_ARRAY|PM_SPECIAL|PM_DONTIMPORT|PM_READONLY), + +/* + * This empty row indicates the end of parameters available in + * all emulations. + */ +{{NULL,NULL,0},BR(NULL),NULL_GSU,0,0,NULL,NULL,NULL,0}, + +#define IPDEF8(A,B,C,D) {{NULL,A,D|PM_SCALAR|PM_SPECIAL},BR((void *)B),GSU(colonarr_gsu),0,0,NULL,C,NULL,0} +IPDEF8("CDPATH", &cdpath, "cdpath", 0), +IPDEF8("FIGNORE", &fignore, "fignore", 0), +IPDEF8("FPATH", &fpath, "fpath", 0), +IPDEF8("MAILPATH", &mailpath, "mailpath", 0), +IPDEF8("WATCH", &watch, "watch", 0), +IPDEF8("PATH", &path, "path", PM_RESTRICTED), +IPDEF8("PSVAR", &psvar, "psvar", 0), +IPDEF8("ZSH_EVAL_CONTEXT", &zsh_eval_context, "zsh_eval_context", PM_READONLY), + +/* MODULE_PATH is not imported for security reasons */ +IPDEF8("MODULE_PATH", &module_path, "module_path", PM_DONTIMPORT|PM_RESTRICTED), + +#define IPDEF10(A,B) {{NULL,A,PM_ARRAY|PM_SPECIAL},BR(NULL),GSU(B),10,0,NULL,NULL,NULL,0} + +/* + * The following parameters are not available in sh/ksh compatibility * + * mode. + */ + +/* All of these have sh compatible equivalents. */ +IPDEF1("ARGC", argc_gsu, PM_READONLY), +IPDEF2("HISTCHARS", histchars_gsu, PM_DONTIMPORT), +IPDEF4("status", &lastval), +IPDEF7("prompt", &prompt), +IPDEF7("PROMPT", &prompt), +IPDEF7("PROMPT2", &prompt2), +IPDEF7("PROMPT3", &prompt3), +IPDEF7("PROMPT4", &prompt4), +IPDEF8("MANPATH", &manpath, "manpath", 0), +IPDEF9("argv", &pparams, NULL), +IPDEF9("fignore", &fignore, "FIGNORE"), +IPDEF9("cdpath", &cdpath, "CDPATH"), +IPDEF9("fpath", &fpath, "FPATH"), +IPDEF9("mailpath", &mailpath, "MAILPATH"), +IPDEF9("manpath", &manpath, "MANPATH"), +IPDEF9("psvar", &psvar, "PSVAR"), +IPDEF9("watch", &watch, "WATCH"), + +IPDEF9F("zsh_eval_context", &zsh_eval_context, "ZSH_EVAL_CONTEXT", PM_READONLY), + +IPDEF9F("module_path", &module_path, "MODULE_PATH", PM_RESTRICTED), +IPDEF9F("path", &path, "PATH", PM_RESTRICTED), + +/* These are known to zsh alone. */ + +IPDEF10("pipestatus", pipestatus_gsu), + +{{NULL,NULL,0},BR(NULL),NULL_GSU,0,0,NULL,NULL,NULL,0}, +}; + +/* + * Alternative versions of colon-separated path parameters for + * sh emulation. These don't link to the array versions. + */ +static initparam special_params_sh[] = { +IPDEF8("CDPATH", &cdpath, NULL, 0), +IPDEF8("FIGNORE", &fignore, NULL, 0), +IPDEF8("FPATH", &fpath, NULL, 0), +IPDEF8("MAILPATH", &mailpath, NULL, 0), +IPDEF8("WATCH", &watch, NULL, 0), +IPDEF8("PATH", &path, NULL, PM_RESTRICTED), +IPDEF8("PSVAR", &psvar, NULL, 0), +IPDEF8("ZSH_EVAL_CONTEXT", &zsh_eval_context, NULL, PM_READONLY), + +/* MODULE_PATH is not imported for security reasons */ +IPDEF8("MODULE_PATH", &module_path, NULL, PM_DONTIMPORT|PM_RESTRICTED), + +{{NULL,NULL,0},BR(NULL),NULL_GSU,0,0,NULL,NULL,NULL,0}, +}; + +/* + * Special way of referring to the positional parameters. Unlike $* + * and $@, this is not readonly. This parameter is not directly + * visible in user space. + */ +static initparam argvparam_pm = IPDEF9F("", &pparams, NULL, \ + PM_ARRAY|PM_SPECIAL|PM_DONTIMPORT); + +#undef BR + +#define IS_UNSET_VALUE(V) \ + ((V) && (!(V)->pm || ((V)->pm->node.flags & PM_UNSET) || \ + !(V)->pm->node.nam || !*(V)->pm->node.nam)) + +static Param argvparam; + +/* hash table containing the parameters */ + +/**/ +mod_export HashTable paramtab, realparamtab; + +/**/ +mod_export HashTable +newparamtable(int size, char const *name) +{ + HashTable ht; + if (!size) + size = 17; + ht = newhashtable(size, name, NULL); + + ht->hash = hasher; + ht->emptytable = emptyhashtable; + ht->filltable = NULL; + ht->cmpnodes = strcmp; + ht->addnode = addhashnode; + ht->getnode = getparamnode; + ht->getnode2 = gethashnode2; + ht->removenode = removehashnode; + ht->disablenode = NULL; + ht->enablenode = NULL; + ht->freenode = freeparamnode; + ht->printnode = printparamnode; + + return ht; +} + +/**/ +static HashNode +getparamnode(HashTable ht, const char *nam) +{ + HashNode hn = gethashnode2(ht, nam); + Param pm = (Param) hn; + + if (pm && pm->u.str && (pm->node.flags & PM_AUTOLOAD)) { + char *mn = dupstring(pm->u.str); + + (void)ensurefeature(mn, "p:", (pm->node.flags & PM_AUTOALL) ? NULL : + nam); + hn = gethashnode2(ht, nam); + if (!hn) { + /* + * This used to be a warning, but surely if we allow + * stuff to go ahead with the autoload stub with + * no error status we're in for all sorts of mayhem? + */ + zerr("autoloading module %s failed to define parameter: %s", mn, + nam); + } + } + return hn; +} + +/* Copy a parameter hash table */ + +static HashTable outtable; + +/**/ +static void +scancopyparams(HashNode hn, UNUSED(int flags)) +{ + /* Going into a real parameter, so always use permanent storage */ + Param pm = (Param)hn; + Param tpm = (Param) zshcalloc(sizeof *tpm); + tpm->node.nam = ztrdup(pm->node.nam); + copyparam(tpm, pm, 0); + addhashnode(outtable, tpm->node.nam, tpm); +} + +/**/ +HashTable +copyparamtable(HashTable ht, char *name) +{ + HashTable nht = 0; + if (ht) { + nht = newparamtable(ht->hsize, name); + outtable = nht; + scanhashtable(ht, 0, 0, 0, scancopyparams, 0); + outtable = NULL; + } + return nht; +} + +/* Flag to freeparamnode to unset the struct */ + +static int delunset; + +/* Function to delete a parameter table. */ + +/**/ +mod_export void +deleteparamtable(HashTable t) +{ + /* The parameters in the hash table need to be unset * + * before being deleted. */ + int odelunset = delunset; + delunset = 1; + deletehashtable(t); + delunset = odelunset; +} + +static unsigned numparamvals; + +/**/ +mod_export void +scancountparams(UNUSED(HashNode hn), int flags) +{ + ++numparamvals; + if ((flags & SCANPM_WANTKEYS) && (flags & SCANPM_WANTVALS)) + ++numparamvals; +} + +static Patprog scanprog; +static char *scanstr; +static char **paramvals; +static Param foundparam; + +/**/ +static void +scanparamvals(HashNode hn, int flags) +{ + struct value v; + Patprog prog; + + if (numparamvals && !(flags & SCANPM_MATCHMANY) && + (flags & (SCANPM_MATCHVAL|SCANPM_MATCHKEY|SCANPM_KEYMATCH))) + return; + v.pm = (Param)hn; + if ((flags & SCANPM_KEYMATCH)) { + char *tmp = dupstring(v.pm->node.nam); + + tokenize(tmp); + remnulargs(tmp); + + if (!(prog = patcompile(tmp, 0, NULL)) || !pattry(prog, scanstr)) + return; + } else if ((flags & SCANPM_MATCHKEY) && !pattry(scanprog, v.pm->node.nam)) { + return; + } + foundparam = v.pm; + if (flags & SCANPM_WANTKEYS) { + paramvals[numparamvals++] = v.pm->node.nam; + if (!(flags & (SCANPM_WANTVALS|SCANPM_MATCHVAL))) + return; + } + v.isarr = (PM_TYPE(v.pm->node.flags) & (PM_ARRAY|PM_HASHED)); + v.flags = 0; + v.start = 0; + v.end = -1; + paramvals[numparamvals] = getstrvalue(&v); + if (flags & SCANPM_MATCHVAL) { + if (pattry(scanprog, paramvals[numparamvals])) { + numparamvals += ((flags & SCANPM_WANTVALS) ? 1 : + !(flags & SCANPM_WANTKEYS)); + } else if (flags & SCANPM_WANTKEYS) + --numparamvals; /* Value didn't match, discard key */ + } else + ++numparamvals; + foundparam = NULL; +} + +/**/ +char ** +paramvalarr(HashTable ht, int flags) +{ + DPUTS((flags & (SCANPM_MATCHKEY|SCANPM_MATCHVAL)) && !scanprog, + "BUG: scanning hash without scanprog set"); + numparamvals = 0; + if (ht) + scanhashtable(ht, 0, 0, PM_UNSET, scancountparams, flags); + paramvals = (char **) zhalloc((numparamvals + 1) * sizeof(char *)); + if (ht) { + numparamvals = 0; + scanhashtable(ht, 0, 0, PM_UNSET, scanparamvals, flags); + } + paramvals[numparamvals] = 0; + return paramvals; +} + +/* Return the full array (no indexing) referred to by a Value. * + * The array value is cached for the lifetime of the Value. */ + +/**/ +static char ** +getvaluearr(Value v) +{ + if (v->arr) + return v->arr; + else if (PM_TYPE(v->pm->node.flags) == PM_ARRAY) + return v->arr = v->pm->gsu.a->getfn(v->pm); + else if (PM_TYPE(v->pm->node.flags) == PM_HASHED) { + v->arr = paramvalarr(v->pm->gsu.h->getfn(v->pm), v->isarr); + /* Can't take numeric slices of associative arrays */ + v->start = 0; + v->end = numparamvals + 1; + return v->arr; + } else + return NULL; +} + +/* Return whether the variable is set * + * checks that array slices are within range * + * used for [[ -v ... ]] condition test */ + +/**/ +int +issetvar(char *name) +{ + struct value vbuf; + Value v; + int slice; + char **arr; + + if (!(v = getvalue(&vbuf, &name, 1)) || *name) + return 0; /* no value or more chars after the variable name */ + if (v->isarr & ~SCANPM_ARRONLY) + return v->end > 1; /* for extracted elements, end gives us a count */ + + slice = v->start != 0 || v->end != -1; + if (PM_TYPE(v->pm->node.flags) != PM_ARRAY || !slice) + return !slice && !(v->pm->node.flags & PM_UNSET); + + if (!v->end) /* empty array slice */ + return 0; + /* get the array and check end is within range */ + if (!(arr = getvaluearr(v))) + return 0; + return arrlen_ge(arr, v->end < 0 ? - v->end : v->end); +} + +/* + * Split environment string into (name, value) pair. + * this is used to avoid in-place editing of environment table + * that results in core dump on some systems + */ + +static int +split_env_string(char *env, char **name, char **value) +{ + char *str, *tenv; + + if (!env || !name || !value) + return 0; + + tenv = strcpy(zhalloc(strlen(env) + 1), env); + for (str = tenv; *str && *str != '='; str++) { + if (STOUC(*str) >= 128) { + /* + * We'll ignore environment variables with names not + * from the portable character set since we don't + * know of a good reason to accept them. + */ + return 0; + } + } + if (str != tenv && *str == '=') { + *str = '\0'; + *name = tenv; + *value = str + 1; + return 1; + } else + return 0; +} + +/** + * Check parameter flags to see if parameter shouldn't be imported + * from environment at start. + * + * return 1: don't import: 0: ok to import. + */ +static int dontimport(int flags) +{ + /* If explicitly marked as don't export */ + if (flags & PM_DONTIMPORT) + return 1; + /* If value already exported */ + if (flags & PM_EXPORTED) + return 1; + /* If security issue when importing and running with some privilege */ + if ((flags & PM_DONTIMPORT_SUID) && isset(PRIVILEGED)) + return 1; + /* OK to import */ + return 0; +} + +/* Set up parameter hash table. This will add predefined * + * parameter entries as well as setting up parameter table * + * entries for environment variables we inherit. */ + +/**/ +void +createparamtable(void) +{ + Param ip, pm; +#if !defined(HAVE_PUTENV) && !defined(USE_SET_UNSET_ENV) + char **new_environ; + int envsize; +#endif +#ifndef USE_SET_UNSET_ENV + char **envp; +#endif + char **envp2, **sigptr, **t; + char buf[50], *str, *iname, *ivalue, *hostnam; + int oae = opts[ALLEXPORT]; +#ifdef HAVE_UNAME + struct utsname unamebuf; + char *machinebuf; +#endif + + paramtab = realparamtab = newparamtable(151, "paramtab"); + + /* Add the special parameters to the hash table */ + for (ip = special_params; ip->node.nam; ip++) + paramtab->addnode(paramtab, ztrdup(ip->node.nam), ip); + if (EMULATION(EMULATE_SH|EMULATE_KSH)) { + for (ip = special_params_sh; ip->node.nam; ip++) + paramtab->addnode(paramtab, ztrdup(ip->node.nam), ip); + } else { + while ((++ip)->node.nam) + paramtab->addnode(paramtab, ztrdup(ip->node.nam), ip); + } + + argvparam = (Param) &argvparam_pm; + + noerrs = 2; + + /* Add the standard non-special parameters which have to * + * be initialized before we copy the environment variables. * + * We don't want to override whatever values the user has * + * given them in the environment. */ + opts[ALLEXPORT] = 0; + setiparam("MAILCHECK", 60); + setiparam("LOGCHECK", 60); + setiparam("KEYTIMEOUT", 40); + setiparam("LISTMAX", 100); + /* + * We used to get the output baud rate here. However, that's + * pretty irrelevant to a terminal on an X display and can lead + * to unnecessary delays if it's wrong (which it probably is). + * Furthermore, even if the output is slow it's very likely + * to be because of WAN delays, not covered by the output + * baud rate. + * So allow the user to set it in the special cases where it's + * useful. + */ + setsparam("TMPPREFIX", ztrdup_metafy(DEFAULT_TMPPREFIX)); + setsparam("TIMEFMT", ztrdup_metafy(DEFAULT_TIMEFMT)); + setsparam("WATCHFMT", ztrdup_metafy(default_watchfmt)); + + hostnam = (char *)zalloc(256); + gethostname(hostnam, 256); + setsparam("HOST", ztrdup_metafy(hostnam)); + zfree(hostnam, 256); + + setsparam("LOGNAME", + ztrdup_metafy((str = getlogin()) && *str ? + str : cached_username)); + +#if !defined(HAVE_PUTENV) && !defined(USE_SET_UNSET_ENV) + /* Copy the environment variables we are inheriting to dynamic * + * memory, so we can do mallocs and frees on it. */ + envsize = sizeof(char *)*(1 + arrlen(environ)); + new_environ = (char **) zalloc(envsize); + memcpy(new_environ, environ, envsize); + environ = new_environ; +#endif + + /* Use heap allocation to avoid many small alloc/free calls */ + pushheap(); + + /* Now incorporate environment variables we are inheriting * + * into the parameter hash table. Copy them into dynamic * + * memory so that we can free them if needed */ + for ( +#ifndef USE_SET_UNSET_ENV + envp = +#endif + envp2 = environ; *envp2; envp2++) { + if (split_env_string(*envp2, &iname, &ivalue)) { + if (!idigit(*iname) && isident(iname) && !strchr(iname, '[')) { + /* + * Parameters that aren't already in the parameter table + * aren't special to the shell, so it's always OK to + * import. Otherwise, check parameter flags. + */ + if ((!(pm = (Param) paramtab->getnode(paramtab, iname)) || + !dontimport(pm->node.flags)) && + (pm = assignsparam(iname, metafy(ivalue, -1, META_DUP), + ASSPM_ENV_IMPORT))) { + pm->node.flags |= PM_EXPORTED; + if (pm->node.flags & PM_SPECIAL) + pm->env = mkenvstr (pm->node.nam, + getsparam(pm->node.nam), pm->node.flags); + else + pm->env = ztrdup(*envp2); +#ifndef USE_SET_UNSET_ENV + *envp++ = pm->env; +#endif + } + } + } + } + popheap(); +#ifndef USE_SET_UNSET_ENV + *envp = NULL; +#endif + opts[ALLEXPORT] = oae; + + /* + * For native emulation we always set the variable home + * (see setupvals()). + */ + pm = (Param) paramtab->getnode(paramtab, "HOME"); + if (EMULATION(EMULATE_ZSH)) + { + pm->node.flags &= ~PM_UNSET; + if (!(pm->node.flags & PM_EXPORTED)) + addenv(pm, home); + } else if (!home) + pm->node.flags |= PM_UNSET; + pm = (Param) paramtab->getnode(paramtab, "LOGNAME"); + if (!(pm->node.flags & PM_EXPORTED)) + addenv(pm, pm->u.str); + pm = (Param) paramtab->getnode(paramtab, "SHLVL"); + sprintf(buf, "%d", (int)++shlvl); + /* shlvl value in environment needs updating unconditionally */ + addenv(pm, buf); + + /* Add the standard non-special parameters */ + set_pwd_env(); +#ifdef HAVE_UNAME + if(uname(&unamebuf)) setsparam("CPUTYPE", ztrdup("unknown")); + else + { + machinebuf = ztrdup_metafy(unamebuf.machine); + setsparam("CPUTYPE", machinebuf); + } + +#else + setsparam("CPUTYPE", ztrdup_metafy("unknown")); +#endif + setsparam("MACHTYPE", ztrdup_metafy(MACHTYPE)); + setsparam("OSTYPE", ztrdup_metafy(OSTYPE)); + setsparam("TTY", ztrdup_metafy(ttystrname)); + setsparam("VENDOR", ztrdup_metafy(VENDOR)); + setsparam("ZSH_ARGZERO", ztrdup(posixzero)); + setsparam("ZSH_VERSION", ztrdup_metafy(ZSH_VERSION)); + setsparam("ZSH_PATCHLEVEL", ztrdup_metafy(ZSH_PATCHLEVEL)); + setaparam("signals", sigptr = zalloc((SIGCOUNT+4) * sizeof(char *))); + for (t = sigs; (*sigptr++ = ztrdup_metafy(*t++)); ); + + noerrs = 0; +} + +/* assign various functions used for non-special parameters */ + +/**/ +mod_export void +assigngetset(Param pm) +{ + switch (PM_TYPE(pm->node.flags)) { + case PM_SCALAR: + pm->gsu.s = &stdscalar_gsu; + break; + case PM_INTEGER: + pm->gsu.i = &stdinteger_gsu; + break; + case PM_EFLOAT: + case PM_FFLOAT: + pm->gsu.f = &stdfloat_gsu; + break; + case PM_ARRAY: + pm->gsu.a = &stdarray_gsu; + break; + case PM_HASHED: + pm->gsu.h = &stdhash_gsu; + break; + default: + DPUTS(1, "BUG: tried to create param node without valid flag"); + break; + } +} + +/* Create a parameter, so that it can be assigned to. Returns NULL if the * + * parameter already exists or can't be created, otherwise returns the * + * parameter node. If a parameter of the same name exists in an outer * + * scope, it is hidden by a newly created parameter. An already existing * + * parameter node at the current level may be `created' and returned * + * provided it is unset and not special. If the parameter can't be * + * created because it already exists, the PM_UNSET flag is cleared. */ + +/**/ +mod_export Param +createparam(char *name, int flags) +{ + Param pm, oldpm; + + if (paramtab != realparamtab) + flags = (flags & ~PM_EXPORTED) | PM_HASHELEM; + + if (name != nulstring) { + oldpm = (Param) (paramtab == realparamtab ? + /* gethashnode2() for direct table read */ + gethashnode2(paramtab, name) : + paramtab->getnode(paramtab, name)); + + DPUTS(oldpm && oldpm->level > locallevel, + "BUG: old local parameter not deleted"); + if (oldpm && (oldpm->level == locallevel || !(flags & PM_LOCAL))) { + if (isset(POSIXBUILTINS) && (oldpm->node.flags & PM_READONLY)) { + zerr("read-only variable: %s", name); + return NULL; + } + if ((oldpm->node.flags & PM_RESTRICTED) && isset(RESTRICTED)) { + zerr("%s: restricted", name); + return NULL; + } + if (!(oldpm->node.flags & PM_UNSET) || + (oldpm->node.flags & PM_SPECIAL) || + /* POSIXBUILTINS horror: we need to retain 'export' flags */ + (isset(POSIXBUILTINS) && (oldpm->node.flags & PM_EXPORTED))) { + oldpm->node.flags &= ~PM_UNSET; + if ((oldpm->node.flags & PM_SPECIAL) && oldpm->ename) { + Param altpm = + (Param) paramtab->getnode(paramtab, oldpm->ename); + if (altpm) + altpm->node.flags &= ~PM_UNSET; + } + return NULL; + } + + pm = oldpm; + pm->base = pm->width = 0; + oldpm = pm->old; + } else { + pm = (Param) zshcalloc(sizeof *pm); + if ((pm->old = oldpm)) { + /* + * needed to avoid freeing oldpm, but we do take it + * out of the environment when it's hidden. + */ + if (oldpm->env) + delenv(oldpm); + paramtab->removenode(paramtab, name); + } + paramtab->addnode(paramtab, ztrdup(name), pm); + } + + if (isset(ALLEXPORT) && !(flags & PM_HASHELEM)) + flags |= PM_EXPORTED; + } else { + pm = (Param) hcalloc(sizeof *pm); + pm->node.nam = nulstring; + } + pm->node.flags = flags & ~PM_LOCAL; + + if(!(pm->node.flags & PM_SPECIAL)) + assigngetset(pm); + return pm; +} + +/* Empty dummy function for special hash parameters. */ + +/**/ +static void +shempty(void) +{ +} + +/* + * Create a simple special hash parameter. + * + * This is for hashes added internally --- it's not possible to add + * special hashes from shell commands. It's currently used + * - by addparamdef() for special parameters in the zsh/parameter + * module + * - by ztie for special parameters tied to databases. + */ + +/**/ +mod_export Param +createspecialhash(char *name, GetNodeFunc get, ScanTabFunc scan, int flags) +{ + Param pm; + HashTable ht; + + if (!(pm = createparam(name, PM_SPECIAL|PM_HASHED|flags))) + return NULL; + + /* + * If there's an old parameter, we'll put the new one at + * the current locallevel, so that the old parameter is + * exposed again after leaving the function. Otherwise, + * we'll leave it alone. Usually this means the parameter + * will stay in place until explicitly unloaded, however + * if the parameter was previously unset within a function + * we'll inherit the level of that function and follow the + * standard convention that the parameter remains local + * even if unset. + * + * These semantics are similar to those of a normal parameter set + * within a function without a local definition. + */ + if (pm->old) + pm->level = locallevel; + pm->gsu.h = (flags & PM_READONLY) ? &stdhash_gsu : + &nullsethash_gsu; + pm->u.hash = ht = newhashtable(0, name, NULL); + + ht->hash = hasher; + ht->emptytable = (TableFunc) shempty; + ht->filltable = NULL; + ht->addnode = (AddNodeFunc) shempty; + ht->getnode = ht->getnode2 = get; + ht->removenode = (RemoveNodeFunc) shempty; + ht->disablenode = NULL; + ht->enablenode = NULL; + ht->freenode = (FreeNodeFunc) shempty; + ht->printnode = printparamnode; + ht->scantab = scan; + + return pm; +} + + +/* + * Copy a parameter + * + * If fakecopy is set, we are just saving the details of a special + * parameter. Otherwise, the result will be used as a real parameter + * and we need to do more work. + */ + +/**/ +void +copyparam(Param tpm, Param pm, int fakecopy) +{ + /* + * Note that tpm, into which we're copying, may not be in permanent + * storage. However, the values themselves are later used directly + * to set the parameter, so must be permanently allocated (in accordance + * with sets.?fn() usage). + */ + tpm->node.flags = pm->node.flags; + tpm->base = pm->base; + tpm->width = pm->width; + tpm->level = pm->level; + if (!fakecopy) + tpm->node.flags &= ~PM_SPECIAL; + switch (PM_TYPE(pm->node.flags)) { + case PM_SCALAR: + tpm->u.str = ztrdup(pm->gsu.s->getfn(pm)); + break; + case PM_INTEGER: + tpm->u.val = pm->gsu.i->getfn(pm); + break; + case PM_EFLOAT: + case PM_FFLOAT: + tpm->u.dval = pm->gsu.f->getfn(pm); + break; + case PM_ARRAY: + tpm->u.arr = zarrdup(pm->gsu.a->getfn(pm)); + break; + case PM_HASHED: + tpm->u.hash = copyparamtable(pm->gsu.h->getfn(pm), pm->node.nam); + break; + } + /* + * If the value is going to be passed as a real parameter (e.g. this is + * called from inside an associative array), we need the gets and sets + * functions to be useful. + * + * In this case we assume the saved parameter is not itself special, + * so we just use the standard functions. This is also why we switch off + * PM_SPECIAL. + */ + if (!fakecopy) + assigngetset(tpm); +} + +/* Return 1 if the string s is a valid identifier, else return 0. */ + +/**/ +mod_export int +isident(char *s) +{ + char *ss; + + if (!*s) /* empty string is definitely not valid */ + return 0; + + if (idigit(*s)) { + /* If the first character is `s' is a digit, then all must be */ + for (ss = ++s; *ss; ss++) + if (!idigit(*ss)) + break; + } else { + /* Find the first character in `s' not in the iident type table */ + ss = itype_end(s, IIDENT, 0); + } + + /* If the next character is not [, then it is * + * definitely not a valid identifier. */ + if (!*ss) + return 1; + if (s == ss) + return 0; + if (*ss != '[') + return 0; + + /* Require balanced [ ] pairs with something between */ + if (!(ss = parse_subscript(++ss, 1, ']'))) + return 0; + untokenize(s); + return !ss[1]; +} + +/* + * Parse a single argument to a parameter subscript. + * The subscripts starts at *str; *str is updated (input/output) + * + * *inv is set to indicate if the subscript is reversed (output) + * v is the Value for the parameter being accessed (input; note + * v->isarr may be modified, and if v is a hash the parameter will + * be updated to the element of the hash) + * a2 is 1 if this is the second subscript of a range (input) + * *w is only set if we need to find the end of a word (input; should + * be set to 0 by the caller). + * + * The final two arguments are to support multibyte characters. + * If supplied they are set to the length of the character before + * the index position and the one at the index position. If + * multibyte characters are not in use they are set to 1 for + * consistency. Note they aren't fully handled if a2 is non-zero, + * since they aren't needed. + * + * Returns a raw offset into the value from the start or end (i.e. + * after the arithmetic for Meta and possible multibyte characters has + * been taken into account). This actually gives the offset *after* + * the character in question; subtract *prevcharlen if necessary. + */ + +/**/ +static zlong +getarg(char **str, int *inv, Value v, int a2, zlong *w, + int *prevcharlen, int *nextcharlen, int flags) +{ + int hasbeg = 0, word = 0, rev = 0, ind = 0, down = 0, l, i, ishash; + int keymatch = 0, needtok = 0, arglen, len, inpar = 0; + char *s = *str, *sep = NULL, *t, sav, *d, **ta, **p, *tt, c; + zlong num = 1, beg = 0, r = 0, quote_arg = 0; + Patprog pprog = NULL; + + /* + * If in NO_EXEC mode, the parameters won't be set up properly, + * so just pretend everything is a hash for subscript parsing + */ + + ishash = (unset(EXECOPT) || + (v->pm && PM_TYPE(v->pm->node.flags) == PM_HASHED)); + if (prevcharlen) + *prevcharlen = 1; + if (nextcharlen) + *nextcharlen = 1; + + /* first parse any subscription flags */ + if (v->pm && (*s == '(' || *s == Inpar)) { + int escapes = 0; + int waste; + for (s++; *s != ')' && *s != Outpar && s != *str; s++) { + switch (*s) { + case 'r': + rev = 1; + keymatch = down = ind = 0; + break; + case 'R': + rev = down = 1; + keymatch = ind = 0; + break; + case 'k': + keymatch = ishash; + rev = 1; + down = ind = 0; + break; + case 'K': + keymatch = ishash; + rev = down = 1; + ind = 0; + break; + case 'i': + rev = ind = 1; + down = keymatch = 0; + break; + case 'I': + rev = ind = down = 1; + keymatch = 0; + break; + case 'w': + /* If the parameter is a scalar, then make subscription * + * work on a per-word basis instead of characters. */ + word = 1; + break; + case 'f': + word = 1; + sep = "\n"; + break; + case 'e': + quote_arg = 1; + break; + case 'n': + t = get_strarg(++s, &arglen); + if (!*t) + goto flagerr; + sav = *t; + *t = '\0'; + num = mathevalarg(s + arglen, &d); + if (!num) + num = 1; + *t = sav; + s = t + arglen - 1; + break; + case 'b': + hasbeg = 1; + t = get_strarg(++s, &arglen); + if (!*t) + goto flagerr; + sav = *t; + *t = '\0'; + if ((beg = mathevalarg(s + arglen, &d)) > 0) + beg--; + *t = sav; + s = t + arglen - 1; + break; + case 'p': + escapes = 1; + break; + case 's': + /* This gives the string that separates words * + * (for use with the `w' flag). */ + t = get_strarg(++s, &arglen); + if (!*t) + goto flagerr; + sav = *t; + *t = '\0'; + s += arglen; + sep = escapes ? getkeystring(s, &waste, GETKEYS_SEP, NULL) + : dupstring(s); + *t = sav; + s = t + arglen - 1; + break; + default: + flagerr: + num = 1; + word = rev = ind = down = keymatch = 0; + sep = NULL; + s = *str - 1; + } + } + if (s != *str) + s++; + } + if (num < 0) { + down = !down; + num = -num; + } + if (v->isarr & SCANPM_WANTKEYS) + *inv = (ind || !(v->isarr & SCANPM_WANTVALS)); + else if (v->isarr & SCANPM_WANTVALS) + *inv = 0; + else { + if (v->isarr) { + if (ind) { + v->isarr |= SCANPM_WANTKEYS; + v->isarr &= ~SCANPM_WANTVALS; + } else if (rev) + v->isarr |= SCANPM_WANTVALS; + /* + * This catches the case where we are using "k" (rather + * than "K") on a hash. + */ + if (!down && keymatch && ishash) + v->isarr &= ~SCANPM_MATCHMANY; + } + *inv = ind; + } + + for (t = s, i = 0; + (c = *t) && + ((c != Outbrack && (ishash || c != ',')) || i || inpar); + t++) { + /* Untokenize inull() except before brackets and double-quotes */ + if (inull(c)) { + c = t[1]; + if (c == '[' || c == ']' || + c == '(' || c == ')' || + c == '{' || c == '}') { + /* This test handles nested subscripts in hash keys */ + if (ishash && i) + *t = ztokens[*t - Pound]; + needtok = 1; + ++t; + } else if (c != '"') + *t = ztokens[*t - Pound]; + continue; + } + /* Inbrack and Outbrack are probably never found here ... */ + if (c == '[' || c == Inbrack) + i++; + else if (c == ']' || c == Outbrack) + i--; + if (c == '(' || c == Inpar) + inpar++; + else if (c == ')' || c == Outpar) + inpar--; + if (ispecial(c)) + needtok = 1; + } + if (!c) + return 0; + *str = tt = t; + + /* + * If in NO_EXEC mode, the parameters won't be set up properly, + * so there's no additional sanity checking we can do. + * Just return 0 now. + */ + if (unset(EXECOPT)) + return 0; + + s = dupstrpfx(s, t - s); + + /* If we're NOT reverse subscripting, strip the inull()s so brackets * + * are not backslashed after parsestr(). Otherwise leave them alone * + * so that the brackets will be escaped when we patcompile() or when * + * subscript arithmetic is performed (for nested subscripts). */ + if (ishash && (keymatch || !rev)) + remnulargs(s); + if (needtok) { + s = dupstring(s); + if (parsestr(&s)) + return 0; + singsub(&s); + } else if (rev) + remnulargs(s); /* This is probably always a no-op, but ... */ + if (!rev) { + if (ishash) { + HashTable ht = v->pm->gsu.h->getfn(v->pm); + if (!ht) { + if (flags & SCANPM_CHECKING) + return 0; + ht = newparamtable(17, v->pm->node.nam); + v->pm->gsu.h->setfn(v->pm, ht); + } + untokenize(s); + if (!(v->pm = (Param) ht->getnode(ht, s))) { + HashTable tht = paramtab; + paramtab = ht; + v->pm = createparam(s, PM_SCALAR|PM_UNSET); + paramtab = tht; + } + v->isarr = (*inv ? SCANPM_WANTINDEX : 0); + v->start = 0; + *inv = 0; /* We've already obtained the "index" (key) */ + *w = v->end = -1; + r = isset(KSHARRAYS) ? 1 : 0; + } else { + r = mathevalarg(s, &s); + if (isset(KSHARRAYS) && r >= 0) + r++; + } + if (word && !v->isarr) { + s = t = getstrvalue(v); + i = wordcount(s, sep, 0); + if (r < 0) + r += i + 1; + if (r < 1) + r = 1; + if (r > i) + r = i; + if (!s || !*s) + return 0; + while ((d = findword(&s, sep)) && --r); + if (!d) + return 0; + + if (!a2 && *tt != ',') + *w = (zlong)(s - t); + + return (a2 ? s : d + 1) - t; + } else if (!v->isarr && !word) { + int lastcharlen = 1; + s = getstrvalue(v); + /* + * Note for the confused (= pws): the index r we + * have so far is that specified by the user. The value + * passed back is an offset from the start or end of + * the string. Hence it needs correcting at least + * for Meta characters and maybe for multibyte characters. + */ + if (r > 0) { + zlong nchars = r; + + MB_METACHARINIT(); + for (t = s; nchars && *t; nchars--) + t += (lastcharlen = MB_METACHARLEN(t)); + /* for consistency, keep any remainder off the end */ + r = (zlong)(t - s) + nchars; + if (prevcharlen && !nchars /* ignore if off the end */) + *prevcharlen = lastcharlen; + if (nextcharlen && *t) + *nextcharlen = MB_METACHARLEN(t); + } else if (r == 0) { + if (prevcharlen) + *prevcharlen = 0; + if (nextcharlen && *s) { + MB_METACHARINIT(); + *nextcharlen = MB_METACHARLEN(s); + } + } else { + zlong nchars = (zlong)MB_METASTRLEN(s) + r; + + if (nchars < 0) { + /* make sure this isn't valid as a raw pointer */ + r -= (zlong)strlen(s); + } else { + MB_METACHARINIT(); + for (t = s; nchars && *t; nchars--) + t += (lastcharlen = MB_METACHARLEN(t)); + r = - (zlong)strlen(t); /* keep negative */ + if (prevcharlen) + *prevcharlen = lastcharlen; + if (nextcharlen && *t) + *nextcharlen = MB_METACHARLEN(t); + } + } + } + } else { + if (!v->isarr && !word && !quote_arg) { + l = strlen(s); + if (a2) { + if (!l || *s != '*') { + d = (char *) hcalloc(l + 2); + *d = '*'; + strcpy(d + 1, s); + s = d; + } + } else { + if (!l || s[l - 1] != '*' || (l > 1 && s[l - 2] == '\\')) { + d = (char *) hcalloc(l + 2); + strcpy(d, s); + strcat(d, "*"); + s = d; + } + } + } + if (!keymatch) { + if (quote_arg) { + untokenize(s); + /* Scalar (e) needs implicit asterisk tokens */ + if (!v->isarr && !word) { + l = strlen(s); + d = (char *) hcalloc(l + 2); + if (a2) { + *d = Star; + strcpy(d + 1, s); + } else { + strcpy(d, s); + d[l] = Star; + d[l + 1] = '\0'; + } + s = d; + } + } else + tokenize(s); + remnulargs(s); + pprog = patcompile(s, 0, NULL); + } else + pprog = NULL; + + if (v->isarr) { + if (ishash) { + scanprog = pprog; + scanstr = s; + if (keymatch) + v->isarr |= SCANPM_KEYMATCH; + else { + if (!pprog) + return 1; + if (ind) + v->isarr |= SCANPM_MATCHKEY; + else + v->isarr |= SCANPM_MATCHVAL; + } + if (down) + v->isarr |= SCANPM_MATCHMANY; + if ((ta = getvaluearr(v)) && + (*ta || ((v->isarr & SCANPM_MATCHMANY) && + (v->isarr & (SCANPM_MATCHKEY | SCANPM_MATCHVAL | + SCANPM_KEYMATCH))))) { + *inv = (v->flags & VALFLAG_INV) ? 1 : 0; + *w = v->end; + scanprog = NULL; + return 1; + } + scanprog = NULL; + } else + ta = getarrvalue(v); + if (!ta || !*ta) + return !down; + len = arrlen(ta); + if (beg < 0) + beg += len; + if (down) { + if (beg < 0) + return 0; + } else if (beg >= len) + return len + 1; + if (beg >= 0 && beg < len) { + if (down) { + if (!hasbeg) + beg = len - 1; + for (r = 1 + beg, p = ta + beg; p >= ta; r--, p--) { + if (pprog && pattry(pprog, *p) && !--num) + return r; + } + } else + for (r = 1 + beg, p = ta + beg; *p; r++, p++) + if (pprog && pattry(pprog, *p) && !--num) + return r; + } + } else if (word) { + ta = sepsplit(d = s = getstrvalue(v), sep, 1, 1); + len = arrlen(ta); + if (beg < 0) + beg += len; + if (down) { + if (beg < 0) + return 0; + } else if (beg >= len) + return len + 1; + if (beg >= 0 && beg < len) { + if (down) { + if (!hasbeg) + beg = len - 1; + for (r = 1 + beg, p = ta + beg; p >= ta; p--, r--) + if (pprog && pattry(pprog, *p) && !--num) + break; + if (p < ta) + return 0; + } else { + for (r = 1 + beg, p = ta + beg; *p; r++, p++) + if (pprog && pattry(pprog, *p) && !--num) + break; + if (!*p) + return 0; + } + } + if (a2) + r++; + for (i = 0; (t = findword(&d, sep)) && *t; i++) + if (!--r) { + r = (zlong)(t - s + (a2 ? -1 : 1)); + if (!a2 && *tt != ',') + *w = r + strlen(ta[i]) - 1; + return r; + } + return a2 ? -1 : 0; + } else { + /* Searching characters */ + int slen; + d = getstrvalue(v); + if (!d || !*d) + return 0; + /* + * beg and len are character counts, not raw offsets. + * Remember we need to return a raw offset. + */ + len = MB_METASTRLEN(d); + slen = strlen(d); + if (beg < 0) + beg += len; + MB_METACHARINIT(); + if (beg >= 0 && beg < len) { + char *de = d + slen; + + if (a2) { + /* + * Second argument: we don't need to + * handle prevcharlen or nextcharlen, but + * we do need to handle characters appropriately. + */ + if (down) { + int nmatches = 0; + char *lastpos = NULL; + + if (!hasbeg) + beg = len; + + /* + * See below: we have to move forward, + * but need to count from the end. + */ + for (t = d, r = 0; r <= beg; r++) { + sav = *t; + *t = '\0'; + if (pprog && pattry(pprog, d)) { + nmatches++; + lastpos = t; + } + *t = sav; + if (t == de) + break; + t += MB_METACHARLEN(t); + } + + if (nmatches >= num) { + if (num > 1) { + nmatches -= num; + MB_METACHARINIT(); + for (t = d, r = 0; ; r++) { + sav = *t; + *t = '\0'; + if (pprog && pattry(pprog, d) && + nmatches-- == 0) { + lastpos = t; + *t = sav; + break; + } + *t = sav; + t += MB_METACHARLEN(t); + } + } + /* else lastpos is already OK */ + + return lastpos - d; + } + } else { + /* + * This handling of the b flag + * gives odd results, but this is the + * way it's always worked. + */ + for (t = d; beg && t <= de; beg--) + t += MB_METACHARLEN(t); + for (;;) { + sav = *t; + *t = '\0'; + if (pprog && pattry(pprog, d) && !--num) { + *t = sav; + /* + * This time, don't increment + * pointer, since it's already + * after everything we matched. + */ + return t - d; + } + *t = sav; + if (t == de) + break; + t += MB_METACHARLEN(t); + } + } + } else { + /* + * First argument: this is the only case + * where we need prevcharlen and nextcharlen. + */ + int lastcharlen; + + if (down) { + int nmatches = 0; + char *lastpos = NULL; + + if (!hasbeg) + beg = len; + + /* + * We can only move forward through + * multibyte strings, so record the + * matches. + * Unfortunately the count num works + * from the end, so it's easy to get the + * last one but we need to repeat if + * we want another one. + */ + for (t = d, r = 0; r <= beg; r++) { + if (pprog && pattry(pprog, t)) { + nmatches++; + lastpos = t; + } + if (t == de) + break; + t += MB_METACHARLEN(t); + } + + if (nmatches >= num) { + if (num > 1) { + /* + * Need to start again and repeat + * to get the right match. + */ + nmatches -= num; + MB_METACHARINIT(); + for (t = d, r = 0; ; r++) { + if (pprog && pattry(pprog, t) && + nmatches-- == 0) { + lastpos = t; + break; + } + t += MB_METACHARLEN(t); + } + } + /* else lastpos is already OK */ + + /* return pointer after matched char */ + lastpos += + (lastcharlen = MB_METACHARLEN(lastpos)); + if (prevcharlen) + *prevcharlen = lastcharlen; + if (nextcharlen) + *nextcharlen = MB_METACHARLEN(lastpos); + return lastpos - d; + } + + for (r = beg + 1, t = d + beg; t >= d; r--, t--) { + if (pprog && pattry(pprog, t) && + !--num) + return r; + } + } else { + for (t = d; beg && t <= de; beg--) + t += MB_METACHARLEN(t); + for (;;) { + if (pprog && pattry(pprog, t) && !--num) { + /* return pointer after matched char */ + t += (lastcharlen = MB_METACHARLEN(t)); + if (prevcharlen) + *prevcharlen = lastcharlen; + if (nextcharlen) + *nextcharlen = MB_METACHARLEN(t); + return t - d; + } + if (t == de) + break; + t += MB_METACHARLEN(t); + } + } + } + } + return down ? 0 : slen + 1; + } + } + return r; +} + +/* + * Parse a subscript. + * + * pptr: In/Out parameter. On entry, *ptr points to a "[foo]" string. On exit + * it will point one past the closing bracket. + * + * v: In/Out parameter. Its .start and .end members (at least) will be updated + * with the parsed indices. + * + * flags: can be either SCANPM_DQUOTED or zero. Other bits are not used. + */ + +/**/ +int +getindex(char **pptr, Value v, int flags) +{ + int start, end, inv = 0; + char *s = *pptr, *tbrack; + + *s++ = '['; + /* Error handled after untokenizing */ + s = parse_subscript(s, flags & SCANPM_DQUOTED, ']'); + /* Now we untokenize everything except inull() markers so we can check * + * for the '*' and '@' special subscripts. The inull()s are removed * + * in getarg() after we know whether we're doing reverse indexing. */ + for (tbrack = *pptr + 1; *tbrack && tbrack != s; tbrack++) { + if (inull(*tbrack) && !*++tbrack) + break; + if (itok(*tbrack)) /* Need to check for Nularg here? */ + *tbrack = ztokens[*tbrack - Pound]; + } + /* If we reached the end of the string (s == NULL) we have an error */ + if (*tbrack) + *tbrack = Outbrack; + else { + zerr("invalid subscript"); + *pptr = tbrack; + return 1; + } + s = *pptr + 1; + if ((s[0] == '*' || s[0] == '@') && s + 1 == tbrack) { + if ((v->isarr || IS_UNSET_VALUE(v)) && s[0] == '@') + v->isarr |= SCANPM_ISVAR_AT; + v->start = 0; + v->end = -1; + s += 2; + } else { + zlong we = 0, dummy; + int startprevlen, startnextlen; + + start = getarg(&s, &inv, v, 0, &we, &startprevlen, &startnextlen, + flags); + + if (inv) { + if (!v->isarr && start != 0) { + char *t, *p; + t = getstrvalue(v); + /* + * Note for the confused (= pws): this is an inverse + * offset so at this stage we need to convert from + * the immediate offset into the value that we have + * into a logical character position. + */ + if (start > 0) { + int nstart = 0; + char *target = t + start - startprevlen; + + p = t; + MB_METACHARINIT(); + while (*p) { + /* + * move up characters, counting how many we + * found + */ + p += MB_METACHARLEN(p); + if (p < target) + nstart++; + else { + if (p == target) + nstart++; + else + p = target; /* pretend we hit exactly */ + break; + } + } + /* if start was too big, keep the difference */ + start = nstart + (target - p) + 1; + } else { + zlong startoff = start + strlen(t); +#ifdef DEBUG + dputs("BUG: can't have negative inverse offsets???"); +#endif + if (startoff < 0) { + /* invalid: keep index but don't dereference */ + start = startoff; + } else { + /* find start in full characters */ + MB_METACHARINIT(); + for (p = t; p < t + startoff;) + p += MB_METACHARLEN(p); + start = - MB_METASTRLEN(p); + } + } + } + if (start > 0 && (isset(KSHARRAYS) || (v->pm->node.flags & PM_HASHED))) + start--; + if (v->isarr != SCANPM_WANTINDEX) { + v->flags |= VALFLAG_INV; + v->isarr = 0; + v->start = start; + v->end = start + 1; + } + if (*s == ',') { + zerr("invalid subscript"); + *tbrack = ']'; + *pptr = tbrack+1; + return 1; + } + if (s == tbrack) + s++; + } else { + int com; + + if ((com = (*s == ','))) { + s++; + end = getarg(&s, &inv, v, 1, &dummy, NULL, NULL, flags); + } else { + end = we ? we : start; + } + if (start != end) + com = 1; + /* + * Somehow the logic sometimes forces us to use the previous + * or next character to what we would expect, which is + * why we had to calculate them in getarg(). + */ + if (start > 0) + start -= startprevlen; + else if (start == 0 && end == 0) + { + /* + * Strictly, this range is entirely off the + * start of the available index range. + * This can't happen with KSH_ARRAYS; we already + * altered the start index in getarg(). + * Are we being strict? + */ + if (isset(KSHZEROSUBSCRIPT)) { + /* + * We're not. + * Treat this as accessing the first element of the + * array. + */ + end = startnextlen; + } else { + /* + * We are. Flag that this range is invalid + * for setting elements. Set the indexes + * to a range that returns empty for other accesses. + */ + v->flags |= VALFLAG_EMPTY; + start = -1; + com = 1; + } + } + if (s == tbrack) { + s++; + if (v->isarr && !com && + (!(v->isarr & SCANPM_MATCHMANY) || + !(v->isarr & (SCANPM_MATCHKEY | SCANPM_MATCHVAL | + SCANPM_KEYMATCH)))) + v->isarr = 0; + v->start = start; + v->end = end; + } else + s = *pptr; + } + } + *tbrack = ']'; + *pptr = s; + return 0; +} + + +/**/ +mod_export Value +getvalue(Value v, char **pptr, int bracks) +{ + return fetchvalue(v, pptr, bracks, 0); +} + +/**/ +mod_export Value +fetchvalue(Value v, char **pptr, int bracks, int flags) +{ + char *s, *t, *ie; + char sav, c; + int ppar = 0; + + s = t = *pptr; + + if (idigit(c = *s)) { + if (bracks >= 0) + ppar = zstrtol(s, &s, 10); + else + ppar = *s++ - '0'; + } + else if ((ie = itype_end(s, IIDENT, 0)) != s) + s = ie; + else if (c == Quest) + *s++ = '?'; + else if (c == Pound) + *s++ = '#'; + else if (c == String) + *s++ = '$'; + else if (c == Qstring) + *s++ = '$'; + else if (c == Star) + *s++ = '*'; + else if (IS_DASH(c)) + *s++ = '-'; + else if (c == '#' || c == '?' || c == '$' || + c == '!' || c == '@' || c == '*') + s++; + else + return NULL; + + if ((sav = *s)) + *s = '\0'; + if (ppar) { + if (v) + memset(v, 0, sizeof(*v)); + else + v = (Value) hcalloc(sizeof *v); + v->pm = argvparam; + v->flags = 0; + v->start = ppar - 1; + v->end = ppar; + if (sav) + *s = sav; + } else { + Param pm; + int isvarat; + + isvarat = (t[0] == '@' && !t[1]); + pm = (Param) paramtab->getnode(paramtab, *t == '0' ? "0" : t); + if (sav) + *s = sav; + *pptr = s; + if (!pm || (pm->node.flags & PM_UNSET)) + return NULL; + if (v) + memset(v, 0, sizeof(*v)); + else + v = (Value) hcalloc(sizeof *v); + if (PM_TYPE(pm->node.flags) & (PM_ARRAY|PM_HASHED)) { + /* Overload v->isarr as the flag bits for hashed arrays. */ + v->isarr = flags | (isvarat ? SCANPM_ISVAR_AT : 0); + /* If no flags were passed, we need something to represent * + * `true' yet differ from an explicit WANTVALS. Use a * + * special flag for this case. */ + if (!v->isarr) + v->isarr = SCANPM_ARRONLY; + } + v->pm = pm; + v->flags = 0; + v->start = 0; + v->end = -1; + if (bracks > 0 && (*s == '[' || *s == Inbrack)) { + if (getindex(&s, v, flags)) { + *pptr = s; + return v; + } + } else if (!(flags & SCANPM_ASSIGNING) && v->isarr && + itype_end(t, IIDENT, 1) != t && isset(KSHARRAYS)) + v->end = 1, v->isarr = 0; + } + if (!bracks && *s) + return NULL; + *pptr = s; +#if 0 + /* + * Check for large subscripts that might be erroneous. + * This code is too gross in several ways: + * - the limit is completely arbitrary + * - the test vetoes operations on existing arrays + * - it's not at all clear a general test on large arrays of + * this kind is any use. + * + * Until someone comes up with workable replacement code it's + * therefore commented out. + */ + if (v->start > MAX_ARRLEN) { + zerr("subscript too %s: %d", "big", v->start + !isset(KSHARRAYS)); + return NULL; + } + if (v->start < -MAX_ARRLEN) { + zerr("subscript too %s: %d", "small", v->start); + return NULL; + } + if (v->end > MAX_ARRLEN+1) { + zerr("subscript too %s: %d", "big", v->end - !!isset(KSHARRAYS)); + return NULL; + } + if (v->end < -MAX_ARRLEN) { + zerr("subscript too %s: %d", "small", v->end); + return NULL; + } +#endif + return v; +} + +/**/ +mod_export char * +getstrvalue(Value v) +{ + char *s, **ss; + char buf[BDIGBUFSIZE]; + int len; + + if (!v) + return hcalloc(1); + + if ((v->flags & VALFLAG_INV) && !(v->pm->node.flags & PM_HASHED)) { + sprintf(buf, "%d", v->start); + s = dupstring(buf); + return s; + } + + switch(PM_TYPE(v->pm->node.flags)) { + case PM_HASHED: + /* (!v->isarr) should be impossible unless emulating ksh */ + if (!v->isarr && EMULATION(EMULATE_KSH)) { + s = dupstring("[0]"); + if (getindex(&s, v, 0) == 0) + s = getstrvalue(v); + return s; + } /* else fall through */ + case PM_ARRAY: + ss = getvaluearr(v); + if (v->isarr) + s = sepjoin(ss, NULL, 1); + else { + if (v->start < 0) + v->start += arrlen(ss); + s = (arrlen_le(ss, v->start) || v->start < 0) ? + (char *) hcalloc(1) : ss[v->start]; + } + return s; + case PM_INTEGER: + convbase(buf, v->pm->gsu.i->getfn(v->pm), v->pm->base); + s = dupstring(buf); + break; + case PM_EFLOAT: + case PM_FFLOAT: + s = convfloat(v->pm->gsu.f->getfn(v->pm), + v->pm->base, v->pm->node.flags, NULL); + break; + case PM_SCALAR: + s = v->pm->gsu.s->getfn(v->pm); + break; + default: + s = ""; + DPUTS(1, "BUG: param node without valid type"); + break; + } + + if (v->flags & VALFLAG_SUBST) { + if (v->pm->node.flags & (PM_LEFT|PM_RIGHT_B|PM_RIGHT_Z)) { + unsigned int fwidth = v->pm->width ? v->pm->width : MB_METASTRLEN(s); + switch (v->pm->node.flags & (PM_LEFT | PM_RIGHT_B | PM_RIGHT_Z)) { + char *t, *tend; + unsigned int t0; + + case PM_LEFT: + case PM_LEFT | PM_RIGHT_Z: + t = s; + if (v->pm->node.flags & PM_RIGHT_Z) + while (*t == '0') + t++; + else + while (iblank(*t)) + t++; + MB_METACHARINIT(); + for (tend = t, t0 = 0; t0 < fwidth && *tend; t0++) + tend += MB_METACHARLEN(tend); + /* + * t0 is the number of characters from t used, + * hence (fwidth - t0) is the number of padding + * characters. fwidth is a misnomer: we use + * character counts, not character widths. + * + * (tend - t) is the number of bytes we need + * to get fwidth characters or the entire string; + * the characters may be multiple bytes. + */ + fwidth -= t0; /* padding chars remaining */ + t0 = tend - t; /* bytes to copy from string */ + s = (char *) hcalloc(t0 + fwidth + 1); + memcpy(s, t, t0); + if (fwidth) + memset(s + t0, ' ', fwidth); + s[t0 + fwidth] = '\0'; + break; + case PM_RIGHT_B: + case PM_RIGHT_Z: + case PM_RIGHT_Z | PM_RIGHT_B: + { + int zero = 1; + /* Calculate length in possibly multibyte chars */ + unsigned int charlen = MB_METASTRLEN(s); + + if (charlen < fwidth) { + char *valprefend = s; + int preflen; + if (v->pm->node.flags & PM_RIGHT_Z) { + /* + * This is a documented feature: when deciding + * whether to pad with zeroes, ignore + * leading blanks already in the value; + * only look for numbers after that. + * Not sure how useful this really is. + * It's certainly confusing to code around. + */ + for (t = s; iblank(*t); t++) + ; + /* + * Allow padding after initial minus + * for numeric variables. + */ + if ((v->pm->node.flags & + (PM_INTEGER|PM_EFLOAT|PM_FFLOAT)) && + *t == '-') + t++; + /* + * Allow padding after initial 0x or + * base# for integer variables. + */ + if (v->pm->node.flags & PM_INTEGER) { + if (isset(CBASES) && + t[0] == '0' && t[1] == 'x') + t += 2; + else if ((valprefend = strchr(t, '#'))) + t = valprefend + 1; + } + valprefend = t; + if (!*t) + zero = 0; + else if (v->pm->node.flags & + (PM_INTEGER|PM_EFLOAT|PM_FFLOAT)) { + /* zero always OK */ + } else if (!idigit(*t)) + zero = 0; + } + /* number of characters needed for padding */ + fwidth -= charlen; + /* bytes from original string */ + t0 = strlen(s); + t = (char *) hcalloc(fwidth + t0 + 1); + /* prefix guaranteed to be single byte chars */ + preflen = valprefend - s; + memset(t + preflen, + (((v->pm->node.flags & PM_RIGHT_B) + || !zero) ? ' ' : '0'), fwidth); + /* + * Copy - or 0x or base# before any padding + * zeroes. + */ + if (preflen) + memcpy(t, s, preflen); + memcpy(t + preflen + fwidth, + valprefend, t0 - preflen); + t[fwidth + t0] = '\0'; + s = t; + } else { + /* Need to skip (charlen - fwidth) chars */ + for (t0 = charlen - fwidth; t0; t0--) + s += MB_METACHARLEN(s); + } + } + break; + } + } + switch (v->pm->node.flags & (PM_LOWER | PM_UPPER)) { + case PM_LOWER: + s = casemodify(s, CASMOD_LOWER); + break; + case PM_UPPER: + s = casemodify(s, CASMOD_UPPER); + break; + } + } + if (v->start == 0 && v->end == -1) + return s; + + len = strlen(s); + if (v->start < 0) { + v->start += len; + if (v->start < 0) + v->start = 0; + } + if (v->end < 0) { + v->end += len; + if (v->end >= 0) { + char *eptr = s + v->end; + if (*eptr) + v->end += MB_METACHARLEN(eptr); + } + } + + s = (v->start > len) ? dupstring("") : + dupstring_wlen(s + v->start, len - v->start); + + if (v->end <= v->start) + s[0] = '\0'; + else if (v->end - v->start <= len - v->start) + s[v->end - v->start] = '\0'; + + return s; +} + +static char *nular[] = {"", NULL}; + +/**/ +mod_export char ** +getarrvalue(Value v) +{ + char **s; + + if (!v) + return arrdup(nular); + else if (IS_UNSET_VALUE(v)) + return arrdup(&nular[1]); + if (v->flags & VALFLAG_INV) { + char buf[DIGBUFSIZE]; + + s = arrdup(nular); + sprintf(buf, "%d", v->start); + s[0] = dupstring(buf); + return s; + } + s = getvaluearr(v); + if (v->start == 0 && v->end == -1) + return s; + if (v->start < 0) + v->start += arrlen(s); + if (v->end < 0) + v->end += arrlen(s) + 1; + + /* Null if 1) array too short, 2) index still negative */ + if (v->end <= v->start) { + s = arrdup_max(nular, 0); + } + else if (v->start < 0) { + s = arrdup_max(nular, 1); + } + else if (arrlen_le(s, v->start)) { + /* Handle $ary[i,i] consistently for any $i > $#ary + * and $ary[i,j] consistently for any $j > $i > $#ary + */ + s = arrdup_max(nular, v->end - (v->start + 1)); + } + else { + /* Copy to a point before the end of the source array: + * arrdup_max will copy at most v->end - v->start elements, + * starting from v->start element. Original code said: + * s[v->end - v->start] = NULL + * which means that there are exactly the same number of + * elements as the value of the above *0-based* index. + */ + s = arrdup_max(s + v->start, v->end - v->start); + } + + return s; +} + +/**/ +mod_export zlong +getintvalue(Value v) +{ + if (!v) + return 0; + if (v->flags & VALFLAG_INV) + return v->start; + if (v->isarr) { + char **arr = getarrvalue(v); + if (arr) { + char *scal = sepjoin(arr, NULL, 1); + return mathevali(scal); + } else + return 0; + } + if (PM_TYPE(v->pm->node.flags) == PM_INTEGER) + return v->pm->gsu.i->getfn(v->pm); + if (v->pm->node.flags & (PM_EFLOAT|PM_FFLOAT)) + return (zlong)v->pm->gsu.f->getfn(v->pm); + return mathevali(getstrvalue(v)); +} + +/**/ +mnumber +getnumvalue(Value v) +{ + mnumber mn; + mn.type = MN_INTEGER; + + + if (!v) { + mn.u.l = 0; + } else if (v->flags & VALFLAG_INV) { + mn.u.l = v->start; + } else if (v->isarr) { + char **arr = getarrvalue(v); + if (arr) { + char *scal = sepjoin(arr, NULL, 1); + return matheval(scal); + } else + mn.u.l = 0; + } else if (PM_TYPE(v->pm->node.flags) == PM_INTEGER) { + mn.u.l = v->pm->gsu.i->getfn(v->pm); + } else if (v->pm->node.flags & (PM_EFLOAT|PM_FFLOAT)) { + mn.type = MN_FLOAT; + mn.u.d = v->pm->gsu.f->getfn(v->pm); + } else + return matheval(getstrvalue(v)); + return mn; +} + +/**/ +void +export_param(Param pm) +{ + char buf[BDIGBUFSIZE], *val; + + if (PM_TYPE(pm->node.flags) & (PM_ARRAY|PM_HASHED)) { +#if 0 /* Requires changes elsewhere in params.c and builtin.c */ + if (EMULATION(EMULATE_KSH) /* isset(KSHARRAYS) */) { + struct value v; + v.isarr = 1; + v.flags = 0; + v.start = 0; + v.end = -1; + val = getstrvalue(&v); + } else +#endif + return; + } else if (PM_TYPE(pm->node.flags) == PM_INTEGER) + convbase(val = buf, pm->gsu.i->getfn(pm), pm->base); + else if (pm->node.flags & (PM_EFLOAT|PM_FFLOAT)) + val = convfloat(pm->gsu.f->getfn(pm), pm->base, + pm->node.flags, NULL); + else + val = pm->gsu.s->getfn(pm); + + addenv(pm, val); +} + +/**/ +mod_export void +setstrvalue(Value v, char *val) +{ + assignstrvalue(v, val, 0); +} + +/**/ +mod_export void +assignstrvalue(Value v, char *val, int flags) +{ + if (unset(EXECOPT)) + return; + if (v->pm->node.flags & PM_READONLY) { + zerr("read-only variable: %s", v->pm->node.nam); + zsfree(val); + return; + } + if ((v->pm->node.flags & PM_RESTRICTED) && isset(RESTRICTED)) { + zerr("%s: restricted", v->pm->node.nam); + zsfree(val); + return; + } + if ((v->pm->node.flags & PM_HASHED) && + (v->isarr & (SCANPM_MATCHMANY|SCANPM_ARRONLY))) { + zerr("%s: attempt to set slice of associative array", v->pm->node.nam); + zsfree(val); + return; + } + if (v->flags & VALFLAG_EMPTY) { + zerr("%s: assignment to invalid subscript range", v->pm->node.nam); + zsfree(val); + return; + } + v->pm->node.flags &= ~PM_UNSET; + switch (PM_TYPE(v->pm->node.flags)) { + case PM_SCALAR: + if (v->start == 0 && v->end == -1) { + v->pm->gsu.s->setfn(v->pm, val); + if ((v->pm->node.flags & (PM_LEFT | PM_RIGHT_B | PM_RIGHT_Z)) && + !v->pm->width) + v->pm->width = strlen(val); + } else { + char *z, *x; + int zlen, vlen, newsize; + + z = v->pm->gsu.s->getfn(v->pm); + zlen = strlen(z); + + if ((v->flags & VALFLAG_INV) && unset(KSHARRAYS)) + v->start--, v->end--; + if (v->start < 0) { + v->start += zlen; + if (v->start < 0) + v->start = 0; + } + if (v->start > zlen) + v->start = zlen; + if (v->end < 0) { + v->end += zlen; + if (v->end < 0) { + v->end = 0; + } else if (v->end >= zlen) { + v->end = zlen; + } else { +#ifdef MULTIBYTE_SUPPORT + if (isset(MULTIBYTE)) { + v->end += MB_METACHARLEN(z + v->end); + } else { + v->end++; + } +#else + v->end++; +#endif + } + } + else if (v->end > zlen) + v->end = zlen; + + vlen = strlen(val); + /* Characters preceding start index + + characters of what is assigned + + characters following end index */ + newsize = v->start + vlen + (zlen - v->end); + + /* Does new size differ? */ + if (newsize != zlen || v->pm->gsu.s->setfn != strsetfn) { + x = (char *) zalloc(newsize + 1); + strncpy(x, z, v->start); + strcpy(x + v->start, val); + strcat(x + v->start, z + v->end); + v->pm->gsu.s->setfn(v->pm, x); + } else { + Param pm = v->pm; + /* Size doesn't change, can limit actions to only + * overwriting bytes in already allocated string */ + strncpy(z + v->start, val, vlen); + /* Implement remainder of strsetfn */ + if (!(pm->node.flags & PM_HASHELEM) && + ((pm->node.flags & PM_NAMEDDIR) || + isset(AUTONAMEDIRS))) { + pm->node.flags |= PM_NAMEDDIR; + adduserdir(pm->node.nam, z, 0, 0); + } + } + zsfree(val); + } + break; + case PM_INTEGER: + if (val) { + zlong ival; + if (flags & ASSPM_ENV_IMPORT) { + char *ptr; + ival = zstrtol_underscore(val, &ptr, 0, 1); + } else + ival = mathevali(val); + v->pm->gsu.i->setfn(v->pm, ival); + if ((v->pm->node.flags & (PM_LEFT | PM_RIGHT_B | PM_RIGHT_Z)) && + !v->pm->width) + v->pm->width = strlen(val); + zsfree(val); + } + if (!v->pm->base && lastbase != -1) + v->pm->base = lastbase; + break; + case PM_EFLOAT: + case PM_FFLOAT: + if (val) { + mnumber mn; + if (flags & ASSPM_ENV_IMPORT) { + char *ptr; + mn.type = MN_FLOAT; + mn.u.d = strtod(val, &ptr); + } else + mn = matheval(val); + v->pm->gsu.f->setfn(v->pm, (mn.type & MN_FLOAT) ? mn.u.d : + (double)mn.u.l); + if ((v->pm->node.flags & (PM_LEFT | PM_RIGHT_B | PM_RIGHT_Z)) && + !v->pm->width) + v->pm->width = strlen(val); + zsfree(val); + } + break; + case PM_ARRAY: + { + char **ss = (char **) zalloc(2 * sizeof(char *)); + + ss[0] = val; + ss[1] = NULL; + setarrvalue(v, ss); + } + break; + case PM_HASHED: + { + if (foundparam == NULL) + { + zerr("%s: attempt to set associative array to scalar", + v->pm->node.nam); + zsfree(val); + return; + } + else + foundparam->gsu.s->setfn(foundparam, val); + } + break; + } + if ((!v->pm->env && !(v->pm->node.flags & PM_EXPORTED) && + !(isset(ALLEXPORT) && !(v->pm->node.flags & PM_HASHELEM))) || + (v->pm->node.flags & PM_ARRAY) || v->pm->ename) + return; + export_param(v->pm); +} + +/**/ +void +setnumvalue(Value v, mnumber val) +{ + char buf[BDIGBUFSIZE], *p; + + if (unset(EXECOPT)) + return; + if (v->pm->node.flags & PM_READONLY) { + zerr("read-only variable: %s", v->pm->node.nam); + return; + } + if ((v->pm->node.flags & PM_RESTRICTED) && isset(RESTRICTED)) { + zerr("%s: restricted", v->pm->node.nam); + return; + } + switch (PM_TYPE(v->pm->node.flags)) { + case PM_SCALAR: + case PM_ARRAY: + if ((val.type & MN_INTEGER) || outputradix) { + if (!(val.type & MN_INTEGER)) + val.u.l = (zlong) val.u.d; + p = convbase_underscore(buf, val.u.l, outputradix, + outputunderscore); + } else + p = convfloat_underscore(val.u.d, outputunderscore); + setstrvalue(v, ztrdup(p)); + break; + case PM_INTEGER: + v->pm->gsu.i->setfn(v->pm, (val.type & MN_INTEGER) ? val.u.l : + (zlong) val.u.d); + setstrvalue(v, NULL); + break; + case PM_EFLOAT: + case PM_FFLOAT: + v->pm->gsu.f->setfn(v->pm, (val.type & MN_INTEGER) ? + (double)val.u.l : val.u.d); + setstrvalue(v, NULL); + break; + } +} + +/**/ +mod_export void +setarrvalue(Value v, char **val) +{ + if (unset(EXECOPT)) + return; + if (v->pm->node.flags & PM_READONLY) { + zerr("read-only variable: %s", v->pm->node.nam); + freearray(val); + return; + } + if ((v->pm->node.flags & PM_RESTRICTED) && isset(RESTRICTED)) { + zerr("%s: restricted", v->pm->node.nam); + freearray(val); + return; + } + if (!(PM_TYPE(v->pm->node.flags) & (PM_ARRAY|PM_HASHED))) { + freearray(val); + zerr("%s: attempt to assign array value to non-array", + v->pm->node.nam); + return; + } + if (v->flags & VALFLAG_EMPTY) { + zerr("%s: assignment to invalid subscript range", v->pm->node.nam); + freearray(val); + return; + } + + if (v->start == 0 && v->end == -1) { + if (PM_TYPE(v->pm->node.flags) == PM_HASHED) + arrhashsetfn(v->pm, val, 0); + else + v->pm->gsu.a->setfn(v->pm, val); + } else if (v->start == -1 && v->end == 0 && + PM_TYPE(v->pm->node.flags) == PM_HASHED) { + arrhashsetfn(v->pm, val, ASSPM_AUGMENT); + } else if ((PM_TYPE(v->pm->node.flags) == PM_HASHED)) { + freearray(val); + zerr("%s: attempt to set slice of associative array", + v->pm->node.nam); + return; + } else { + char **const old = v->pm->gsu.a->getfn(v->pm); + char **new; + char **p, **q, **r; /* index variables */ + const int pre_assignment_length = arrlen(old); + int post_assignment_length; + int i; + + q = old; + + if ((v->flags & VALFLAG_INV) && unset(KSHARRAYS)) { + if (v->start > 0) + v->start--; + v->end--; + } + if (v->start < 0) { + v->start += pre_assignment_length; + if (v->start < 0) + v->start = 0; + } + if (v->end < 0) { + v->end += pre_assignment_length + 1; + if (v->end < 0) + v->end = 0; + } + if (v->end < v->start) + v->end = v->start; + + post_assignment_length = v->start + arrlen(val); + if (v->end < pre_assignment_length) { + /* + * Allocate room for array elements between the end of the slice `v' + * and the original array's end. + */ + post_assignment_length += pre_assignment_length - v->end; + } + + if (pre_assignment_length == post_assignment_length + && v->pm->gsu.a->setfn == arrsetfn + /* ... and isn't something that arrsetfn() treats specially */ + && 0 == (v->pm->node.flags & (PM_SPECIAL|PM_UNIQUE)) + && NULL == v->pm->ename) + { + /* v->start is 0-based */ + p = old + v->start; + for (r = val; *r;) { + /* Free previous string */ + zsfree(*p); + /* Give away ownership of the string */ + *p++ = *r++; + } + } else { + /* arr+=( ... ) + * arr[${#arr}+x,...]=( ... ) */ + if (post_assignment_length > pre_assignment_length && + pre_assignment_length <= v->start && + pre_assignment_length > 0 && + v->pm->gsu.a->setfn == arrsetfn) + { + p = new = (char **) zrealloc(old, sizeof(char *) + * (post_assignment_length + 1)); + + p += pre_assignment_length; /* after old elements */ + + /* Consider 1 < 0, case for a=( 1 ); a[1,..] = + * 1 < 1, case for a=( 1 ); a[2,..] = */ + if (pre_assignment_length < v->start) { + for (i = pre_assignment_length; i < v->start; i++) { + *p++ = ztrdup(""); + } + } + + for (r = val; *r;) { + /* Give away ownership of the string */ + *p++ = *r++; + } + + /* v->end doesn't matter: + * a=( 1 2 ); a[4,100]=( a b ); echo "${(q@)a}" + * 1 2 '' a b */ + *p = NULL; + + v->pm->u.arr = NULL; + v->pm->gsu.a->setfn(v->pm, new); + } else { + p = new = (char **) zalloc(sizeof(char *) + * (post_assignment_length + 1)); + for (i = 0; i < v->start; i++) + *p++ = i < pre_assignment_length ? ztrdup(*q++) : ztrdup(""); + for (r = val; *r;) { + /* Give away ownership of the string */ + *p++ = *r++; + } + if (v->end < pre_assignment_length) + for (q = old + v->end; *q;) + *p++ = ztrdup(*q++); + *p = NULL; + + v->pm->gsu.a->setfn(v->pm, new); + } + + DPUTS2(p - new != post_assignment_length, "setarrvalue: wrong allocation: %d 1= %lu", + post_assignment_length, (unsigned long)(p - new)); + } + + /* Ownership of all strings has been + * given away, can plainly free */ + free(val); + } +} + +/* Retrieve an integer parameter */ + +/**/ +mod_export zlong +getiparam(char *s) +{ + struct value vbuf; + Value v; + + if (!(v = getvalue(&vbuf, &s, 1))) + return 0; + return getintvalue(v); +} + +/* Retrieve a numerical parameter, either integer or floating */ + +/**/ +mnumber +getnparam(char *s) +{ + struct value vbuf; + Value v; + + if (!(v = getvalue(&vbuf, &s, 1))) { + mnumber mn; + mn.type = MN_INTEGER; + mn.u.l = 0; + return mn; + } + return getnumvalue(v); +} + +/* Retrieve a scalar (string) parameter */ + +/**/ +mod_export char * +getsparam(char *s) +{ + struct value vbuf; + Value v; + + if (!(v = getvalue(&vbuf, &s, 0))) + return NULL; + return getstrvalue(v); +} + +/**/ +mod_export char * +getsparam_u(char *s) +{ + if ((s = getsparam(s))) + return unmetafy(s, NULL); + return s; +} + +/* Retrieve an array parameter */ + +/**/ +mod_export char ** +getaparam(char *s) +{ + struct value vbuf; + Value v; + + if (!idigit(*s) && (v = getvalue(&vbuf, &s, 0)) && + PM_TYPE(v->pm->node.flags) == PM_ARRAY) + return v->pm->gsu.a->getfn(v->pm); + return NULL; +} + +/* Retrieve an assoc array parameter as an array */ + +/**/ +mod_export char ** +gethparam(char *s) +{ + struct value vbuf; + Value v; + + if (!idigit(*s) && (v = getvalue(&vbuf, &s, 0)) && + PM_TYPE(v->pm->node.flags) == PM_HASHED) + return paramvalarr(v->pm->gsu.h->getfn(v->pm), SCANPM_WANTVALS); + return NULL; +} + +/* Retrieve the keys of an assoc array parameter as an array */ + +/**/ +mod_export char ** +gethkparam(char *s) +{ + struct value vbuf; + Value v; + + if (!idigit(*s) && (v = getvalue(&vbuf, &s, 0)) && + PM_TYPE(v->pm->node.flags) == PM_HASHED) + return paramvalarr(v->pm->gsu.h->getfn(v->pm), SCANPM_WANTKEYS); + return NULL; +} + +/* + * Function behind WARNCREATEGLOBAL and WARNNESTEDVAR option. + * + * For WARNNESTEDVAR: + * Called when the variable is created. + * Apply heuristics to see if this variable was just created + * globally but in a local context. + * + * For WARNNESTEDVAR: + * Called when the variable already exists and is set. + * Apply heuristics to see if this variable is setting + * a variable that was created in a less nested function + * or globally. + */ + +/**/ +static void +check_warn_pm(Param pm, const char *pmtype, int created, + int may_warn_about_nested_vars) +{ + Funcstack i; + + if (!may_warn_about_nested_vars && !created) + return; + + if (created && isset(WARNCREATEGLOBAL)) { + if (locallevel <= forklevel || pm->level != 0) + return; + } else if (!created && isset(WARNNESTEDVAR)) { + if (pm->level >= locallevel) + return; + } else + return; + + if (pm->node.flags & PM_SPECIAL) + return; + + for (i = funcstack; i; i = i->prev) { + if (i->tp == FS_FUNC) { + char *msg; + DPUTS(!i->name, "funcstack entry with no name"); + msg = created ? + "%s parameter %s created globally in function %s" : + "%s parameter %s set in enclosing scope in function %s"; + zwarn(msg, pmtype, pm->node.nam, i->name); + break; + } + } +} + +/**/ +mod_export Param +assignsparam(char *s, char *val, int flags) +{ + struct value vbuf; + Value v; + char *t = s; + char *ss, *copy, *var; + size_t lvar; + mnumber lhs, rhs; + int sstart, created = 0; + + if (!isident(s)) { + zerr("not an identifier: %s", s); + zsfree(val); + errflag |= ERRFLAG_ERROR; + return NULL; + } + queue_signals(); + if ((ss = strchr(s, '['))) { + *ss = '\0'; + if (!(v = getvalue(&vbuf, &s, 1))) { + createparam(t, PM_ARRAY); + created = 1; + } else { + if (v->pm->node.flags & PM_READONLY) { + zerr("read-only variable: %s", v->pm->node.nam); + *ss = '['; + zsfree(val); + unqueue_signals(); + return NULL; + } + /* + * Parameter defined here is a temporary bogus one. + * Don't warn about anything. + */ + flags &= ~ASSPM_WARN; + } + *ss = '['; + v = NULL; + } else { + if (!(v = getvalue(&vbuf, &s, 1))) { + createparam(t, PM_SCALAR); + created = 1; + } else if ((((v->pm->node.flags & PM_ARRAY) && !(flags & ASSPM_AUGMENT)) || + (v->pm->node.flags & PM_HASHED)) && + !(v->pm->node.flags & (PM_SPECIAL|PM_TIED)) && + unset(KSHARRAYS)) { + unsetparam(t); + createparam(t, PM_SCALAR); + /* not regarded as a new creation */ + v = NULL; + } + } + if (!v && !(v = getvalue(&vbuf, &t, 1))) { + unqueue_signals(); + zsfree(val); + /* errflag |= ERRFLAG_ERROR; */ + return NULL; + } + if (flags & ASSPM_WARN) + check_warn_pm(v->pm, "scalar", created, 1); + if (flags & ASSPM_AUGMENT) { + if (v->start == 0 && v->end == -1) { + switch (PM_TYPE(v->pm->node.flags)) { + case PM_SCALAR: + v->start = INT_MAX; /* just append to scalar value */ + break; + case PM_INTEGER: + case PM_EFLOAT: + case PM_FFLOAT: + rhs = matheval(val); + lhs = getnumvalue(v); + if (lhs.type == MN_FLOAT) { + if ((rhs.type) == MN_FLOAT) + lhs.u.d = lhs.u.d + rhs.u.d; + else + lhs.u.d = lhs.u.d + (double)rhs.u.l; + } else { + if ((rhs.type) == MN_INTEGER) + lhs.u.l = lhs.u.l + rhs.u.l; + else + lhs.u.l = lhs.u.l + (zlong)rhs.u.d; + } + setnumvalue(v, lhs); + unqueue_signals(); + zsfree(val); + return v->pm; /* avoid later setstrvalue() call */ + case PM_ARRAY: + if (unset(KSHARRAYS)) { + v->start = arrlen(v->pm->gsu.a->getfn(v->pm)); + v->end = v->start + 1; + } else { + /* ksh appends scalar to first element */ + v->end = 1; + goto kshappend; + } + break; + } + } else { + switch (PM_TYPE(v->pm->node.flags)) { + case PM_SCALAR: + if (v->end > 0) + v->start = v->end; + else + v->start = v->end = strlen(v->pm->gsu.s->getfn(v->pm)) + + v->end + 1; + break; + case PM_INTEGER: + case PM_EFLOAT: + case PM_FFLOAT: + unqueue_signals(); + zerr("attempt to add to slice of a numeric variable"); + zsfree(val); + return NULL; + case PM_ARRAY: + kshappend: + /* treat slice as the end element */ + v->start = sstart = v->end > 0 ? v->end - 1 : v->end; + v->isarr = 0; + var = getstrvalue(v); + v->start = sstart; + copy = val; + lvar = strlen(var); + val = (char *)zalloc(lvar + strlen(val) + 1); + strcpy(val, var); + strcpy(val + lvar, copy); + zsfree(copy); + break; + } + } + } + + assignstrvalue(v, val, flags); + unqueue_signals(); + return v->pm; +} + +/**/ +mod_export Param +setsparam(char *s, char *val) +{ + return assignsparam(s, val, ASSPM_WARN); +} + +/**/ +mod_export Param +assignaparam(char *s, char **val, int flags) +{ + struct value vbuf; + Value v; + char *t = s; + char *ss; + int created = 0; + int may_warn_about_nested_vars = 1; + + if (!isident(s)) { + zerr("not an identifier: %s", s); + freearray(val); + errflag |= ERRFLAG_ERROR; + return NULL; + } + queue_signals(); + if ((ss = strchr(s, '['))) { + *ss = '\0'; + if (!(v = getvalue(&vbuf, &s, 1))) { + createparam(t, PM_ARRAY); + created = 1; + } else { + may_warn_about_nested_vars = 0; + } + *ss = '['; + if (v && PM_TYPE(v->pm->node.flags) == PM_HASHED) { + unqueue_signals(); + zerr("%s: attempt to set slice of associative array", + v->pm->node.nam); + freearray(val); + errflag |= ERRFLAG_ERROR; + return NULL; + } + v = NULL; + } else { + if (!(v = fetchvalue(&vbuf, &s, 1, SCANPM_ASSIGNING))) { + createparam(t, PM_ARRAY); + created = 1; + } else if (!(PM_TYPE(v->pm->node.flags) & (PM_ARRAY|PM_HASHED)) && + !(v->pm->node.flags & (PM_SPECIAL|PM_TIED))) { + int uniq = v->pm->node.flags & PM_UNIQUE; + if (flags & ASSPM_AUGMENT) { + /* insert old value at the beginning of the val array */ + char **new; + int lv = arrlen(val); + + new = (char **) zalloc(sizeof(char *) * (lv + 2)); + *new = ztrdup(getstrvalue(v)); + memcpy(new+1, val, sizeof(char *) * (lv + 1)); + free(val); + val = new; + } + unsetparam(t); + createparam(t, PM_ARRAY | uniq); + v = NULL; + } + } + if (!v) + if (!(v = fetchvalue(&vbuf, &t, 1, SCANPM_ASSIGNING))) { + unqueue_signals(); + freearray(val); + /* errflag |= ERRFLAG_ERROR; */ + return NULL; + } + + if (flags & ASSPM_WARN) + check_warn_pm(v->pm, "array", created, may_warn_about_nested_vars); + + /* + * At this point, we may have array entries consisting of + * - a Marker element --- normally allocated array entry but + * with just Marker char and null + * - an array index element --- as normal for associative array, + * but non-standard for normal array which we handle now. + * - a value for the indexed element. + * This only applies if the flag ASSPM_KEY_VALUE is passed in, + * indicating prefork() detected this syntax. + * + * For associative arrays we just junk the Marker elements. + */ + if (flags & ASSPM_KEY_VALUE) { + char **aptr; + if (PM_TYPE(v->pm->node.flags) & PM_ARRAY) { + /* + * This is an ordinary array with key / value pairs. + */ + int maxlen, origlen, nextind; + char **fullval, **origptr; + zlong *subscripts = (zlong *)zhalloc(arrlen(val) * sizeof(zlong)); + zlong *iptr = subscripts; + if (flags & ASSPM_AUGMENT) { + origptr = v->pm->gsu.a->getfn(v->pm); + maxlen = origlen = arrlen(origptr); + } else { + maxlen = origlen = 0; + origptr = NULL; + } + nextind = 0; + for (aptr = val; *aptr; ) { + if (**aptr == Marker) { + *iptr = mathevali(*++aptr); + if (*iptr < 0 || + (!isset(KSHARRAYS) && *iptr == 0)) { + unqueue_signals(); + zerr("bad subscript for direct array assignment: %s", *aptr); + freearray(val); + return NULL; + } + if (!isset(KSHARRAYS)) + --*iptr; + nextind = *iptr + 1; + ++iptr; + aptr += 2; + } else { + ++nextind; + ++aptr; + } + if (nextind > maxlen) + maxlen = nextind; + } + fullval = zshcalloc((maxlen+1) * sizeof(char *)); + if (!fullval) { + zerr("array too large"); + freearray(val); + return NULL; + } + fullval[maxlen] = NULL; + if (flags & ASSPM_AUGMENT) { + char **srcptr = origptr; + for (aptr = fullval; aptr <= fullval + origlen; aptr++) { + *aptr = ztrdup(*srcptr); + srcptr++; + } + } + iptr = subscripts; + nextind = 0; + for (aptr = val; *aptr; ++aptr) { + char *old; + if (**aptr == Marker) { + int augment = ((*aptr)[1] == '+'); + zsfree(*aptr); + zsfree(*++aptr); /* Index, no longer needed */ + old = fullval[*iptr]; + if (augment && old) { + fullval[*iptr] = bicat(old, *++aptr); + zsfree(*aptr); + } else { + fullval[*iptr] = *++aptr; + } + nextind = *iptr + 1; + ++iptr; + } else { + old = fullval[nextind]; + fullval[nextind] = *aptr; + ++nextind; + } + if (old) + zsfree(old); + /* aptr now on value in both cases */ + } + if (*aptr) { /* Shouldn't be possible */ + DPUTS(1, "Extra element in key / value array"); + zsfree(*aptr); + } + free(val); + for (aptr = fullval; aptr < fullval + maxlen; aptr++) { + /* + * Remember we don't have sparse arrays but and they're null + * terminated --- so any value we don't set has to be an + * empty string. + */ + if (!*aptr) + *aptr = ztrdup(""); + } + setarrvalue(v, fullval); + unqueue_signals(); + return v->pm; + } else if (PM_TYPE(v->pm->node.flags & PM_HASHED)) { + /* + * We strictly enforce [key]=value syntax for associative + * arrays. Marker can only indicate a Marker / key / value + * triad; it cannot be there by accident. + * + * It's too inefficient to strip Markers here, and they + * can't be there in the other form --- so just ignore + * them willy nilly lower down. + */ + for (aptr = val; *aptr; aptr += 3) { + if (**aptr != Marker) { + unqueue_signals(); + freearray(val); + zerr("bad [key]=value syntax for associative array"); + return NULL; + } + } + } else { + unqueue_signals(); + freearray(val); + zerr("invalid use of [key]=value assignment syntax"); + return NULL; + } + } + + if (flags & ASSPM_AUGMENT) { + if (v->start == 0 && v->end == -1) { + if (PM_TYPE(v->pm->node.flags) & PM_ARRAY) { + v->start = arrlen(v->pm->gsu.a->getfn(v->pm)); + v->end = v->start + 1; + } else if (PM_TYPE(v->pm->node.flags) & PM_HASHED) + v->start = -1, v->end = 0; + } else { + if (v->end > 0) + v->start = v->end--; + else if (PM_TYPE(v->pm->node.flags) & PM_ARRAY) { + v->end = arrlen(v->pm->gsu.a->getfn(v->pm)) + v->end; + v->start = v->end + 1; + } + } + } + + setarrvalue(v, val); + unqueue_signals(); + return v->pm; +} + + +/**/ +mod_export Param +setaparam(char *s, char **aval) +{ + return assignaparam(s, aval, ASSPM_WARN); +} + +/**/ +mod_export Param +sethparam(char *s, char **val) +{ + struct value vbuf; + Value v; + char *t = s; + int checkcreate = 0; + + if (!isident(s)) { + zerr("not an identifier: %s", s); + freearray(val); + errflag |= ERRFLAG_ERROR; + return NULL; + } + if (strchr(s, '[')) { + freearray(val); + zerr("nested associative arrays not yet supported"); + errflag |= ERRFLAG_ERROR; + return NULL; + } + if (unset(EXECOPT)) + return NULL; + queue_signals(); + if (!(v = fetchvalue(&vbuf, &s, 1, SCANPM_ASSIGNING))) { + createparam(t, PM_HASHED); + checkcreate = 1; + } else if (!(PM_TYPE(v->pm->node.flags) & PM_HASHED)) { + if (!(v->pm->node.flags & PM_SPECIAL)) { + unsetparam(t); + /* no WARNCREATEGLOBAL check here as parameter already existed */ + createparam(t, PM_HASHED); + v = NULL; + } else { + zerr("%s: can't change type of a special parameter", t); + unqueue_signals(); + return NULL; + } + } + if (!v) + if (!(v = fetchvalue(&vbuf, &t, 1, SCANPM_ASSIGNING))) { + unqueue_signals(); + /* errflag |= ERRFLAG_ERROR; */ + return NULL; + } + check_warn_pm(v->pm, "associative array", checkcreate, 1); + setarrvalue(v, val); + unqueue_signals(); + return v->pm; +} + + +/* + * Set a generic shell number, floating point or integer. + * Option to warn on setting. + */ + +/**/ +mod_export Param +assignnparam(char *s, mnumber val, int flags) +{ + struct value vbuf; + Value v; + char *t = s, *ss; + Param pm; + int was_unset = 0; + + if (!isident(s)) { + zerr("not an identifier: %s", s); + errflag |= ERRFLAG_ERROR; + return NULL; + } + if (unset(EXECOPT)) + return NULL; + queue_signals(); + ss = strchr(s, '['); + v = getvalue(&vbuf, &s, 1); + if (v && (v->pm->node.flags & (PM_ARRAY|PM_HASHED)) && + !(v->pm->node.flags & (PM_SPECIAL|PM_TIED)) && + /* + * not sure what KSHARRAYS has got to do with this... + * copied this from assignsparam(). + */ + unset(KSHARRAYS) && !ss) { + unsetparam_pm(v->pm, 0, 1); + was_unset = 1; + s = t; + v = NULL; + } + if (!v) { + /* s has been updated by getvalue, so check again */ + ss = strchr(s, '['); + if (ss) + *ss = '\0'; + pm = createparam(t, ss ? PM_ARRAY : + isset(POSIXIDENTIFIERS) ? PM_SCALAR : + (val.type & MN_INTEGER) ? PM_INTEGER : PM_FFLOAT); + if (!pm) + pm = (Param) paramtab->getnode(paramtab, t); + DPUTS(!pm, "BUG: parameter not created"); + if (ss) { + *ss = '['; + } else if (val.type & MN_INTEGER) { + pm->base = outputradix; + } + if (!(v = getvalue(&vbuf, &t, 1))) { + DPUTS(!v, "BUG: value not found for new parameter"); + /* errflag |= ERRFLAG_ERROR; */ + unqueue_signals(); + return NULL; + } + if (flags & ASSPM_WARN) + check_warn_pm(v->pm, "numeric", !was_unset, 1); + } else { + if (flags & ASSPM_WARN) + check_warn_pm(v->pm, "numeric", 0, 1); + } + setnumvalue(v, val); + unqueue_signals(); + return v->pm; +} + +/* + * Set a generic shell number, floating point or integer. + * Warn on setting based on option. + */ + +/**/ +mod_export Param +setnparam(char *s, mnumber val) +{ + return assignnparam(s, val, ASSPM_WARN); +} + +/* Simplified interface to assignnparam */ + +/**/ +mod_export Param +assigniparam(char *s, zlong val, int flags) +{ + mnumber mnval; + mnval.type = MN_INTEGER; + mnval.u.l = val; + return assignnparam(s, mnval, flags); +} + +/* Simplified interface to setnparam */ + +/**/ +mod_export Param +setiparam(char *s, zlong val) +{ + mnumber mnval; + mnval.type = MN_INTEGER; + mnval.u.l = val; + return assignnparam(s, mnval, ASSPM_WARN); +} + +/* + * Set an integer parameter without forcing creation of an integer type. + * This is useful if the integer is going to be set to a parmaeter which + * would usually be scalar but may not exist. + */ + +/**/ +mod_export Param +setiparam_no_convert(char *s, zlong val) +{ + /* + * If the target is already an integer, thisgets converted + * back. Low technology rules. + */ + char buf[BDIGBUFSIZE]; + convbase(buf, val, 10); + return assignsparam(s, ztrdup(buf), ASSPM_WARN); +} + +/* Unset a parameter */ + +/**/ +mod_export void +unsetparam(char *s) +{ + Param pm; + + queue_signals(); + if ((pm = (Param) (paramtab == realparamtab ? + /* getnode2() to avoid autoloading */ + paramtab->getnode2(paramtab, s) : + paramtab->getnode(paramtab, s)))) + unsetparam_pm(pm, 0, 1); + unqueue_signals(); +} + +/* Unset a parameter + * + * altflag: if true, don't remove pm->ename from the environment + * exp: See stdunsetfn() + */ + +/**/ +mod_export int +unsetparam_pm(Param pm, int altflag, int exp) +{ + Param oldpm, altpm; + char *altremove; + + if ((pm->node.flags & PM_READONLY) && pm->level <= locallevel) { + zerr("read-only variable: %s", pm->node.nam); + return 1; + } + if ((pm->node.flags & PM_RESTRICTED) && isset(RESTRICTED)) { + zerr("%s: restricted", pm->node.nam); + return 1; + } + + if (pm->ename && !altflag) + altremove = ztrdup(pm->ename); + else + altremove = NULL; + + if (!(pm->node.flags & PM_UNSET)) + pm->gsu.s->unsetfn(pm, exp); + if (pm->env) + delenv(pm); + + /* remove it under its alternate name if necessary */ + if (altremove) { + altpm = (Param) paramtab->getnode(paramtab, altremove); + /* tied parameters are at the same local level as each other */ + oldpm = NULL; + while (altpm && altpm->level > pm->level) { + /* param under alternate name hidden by a local */ + oldpm = altpm; + altpm = altpm->old; + } + if (altpm) { + if (oldpm && !altpm->level) { + oldpm->old = NULL; + /* fudge things so removenode isn't called */ + altpm->level = 1; + } + unsetparam_pm(altpm, 1, exp); + } + + zsfree(altremove); + } + + /* + * If this was a local variable, we need to keep the old + * struct so that it is resurrected at the right level. + * This is partly because when an array/scalar value is set + * and the parameter used to be the other sort, unsetparam() + * is called. Beyond that, there is an ambiguity: should + * foo() { local bar; unset bar; } make the global bar + * available or not? The following makes the answer "no". + * + * Some specials, such as those used in zle, still need removing + * from the parameter table; they have the PM_REMOVABLE flag. + */ + if ((pm->level && locallevel >= pm->level) || + (pm->node.flags & (PM_SPECIAL|PM_REMOVABLE)) == PM_SPECIAL) + return 0; + + /* remove parameter node from table */ + paramtab->removenode(paramtab, pm->node.nam); + + if (pm->old) { + oldpm = pm->old; + paramtab->addnode(paramtab, oldpm->node.nam, oldpm); + if ((PM_TYPE(oldpm->node.flags) == PM_SCALAR) && + !(pm->node.flags & PM_HASHELEM) && + (oldpm->node.flags & PM_NAMEDDIR) && + oldpm->gsu.s == &stdscalar_gsu) + adduserdir(oldpm->node.nam, oldpm->u.str, 0, 0); + if (oldpm->node.flags & PM_EXPORTED) { + /* + * Re-export the old value which we removed in typeset_single(). + * I don't think we need to test for ALL_EXPORT here, since if + * it was used to export the parameter originally the parameter + * should still have the PM_EXPORTED flag. + */ + export_param(oldpm); + } + } + + paramtab->freenode(&pm->node); /* free parameter node */ + + return 0; +} + +/* Standard function to unset a parameter. This is mostly delegated to * + * the specific set function. + * + * This could usefully be made type-specific, but then we need + * to be more careful when calling the unset method directly. + * + * The "exp"licit parameter should be nonzero for assignments and the + * unset command, and zero for implicit unset (e.g., end of scope). + * Currently this is used only by some modules. + */ + +/**/ +mod_export void +stdunsetfn(Param pm, UNUSED(int exp)) +{ + switch (PM_TYPE(pm->node.flags)) { + case PM_SCALAR: + if (pm->gsu.s->setfn) + pm->gsu.s->setfn(pm, NULL); + break; + + case PM_ARRAY: + if (pm->gsu.a->setfn) + pm->gsu.a->setfn(pm, NULL); + break; + + case PM_HASHED: + if (pm->gsu.h->setfn) + pm->gsu.h->setfn(pm, NULL); + break; + + default: + if (!(pm->node.flags & PM_SPECIAL)) + pm->u.str = NULL; + break; + } + if ((pm->node.flags & (PM_SPECIAL|PM_TIED)) == PM_TIED) { + if (pm->ename) { + zsfree(pm->ename); + pm->ename = NULL; + } + pm->node.flags &= ~PM_TIED; + } + pm->node.flags |= PM_UNSET; +} + +/* Function to get value of an integer parameter */ + +/**/ +mod_export zlong +intgetfn(Param pm) +{ + return pm->u.val; +} + +/* Function to set value of an integer parameter */ + +/**/ +static void +intsetfn(Param pm, zlong x) +{ + pm->u.val = x; +} + +/* Function to get value of a floating point parameter */ + +/**/ +static double +floatgetfn(Param pm) +{ + return pm->u.dval; +} + +/* Function to set value of an integer parameter */ + +/**/ +static void +floatsetfn(Param pm, double x) +{ + pm->u.dval = x; +} + +/* Function to get value of a scalar (string) parameter */ + +/**/ +mod_export char * +strgetfn(Param pm) +{ + return pm->u.str ? pm->u.str : (char *) hcalloc(1); +} + +/* Function to set value of a scalar (string) parameter */ + +/**/ +mod_export void +strsetfn(Param pm, char *x) +{ + zsfree(pm->u.str); + pm->u.str = x; + if (!(pm->node.flags & PM_HASHELEM) && + ((pm->node.flags & PM_NAMEDDIR) || isset(AUTONAMEDIRS))) { + pm->node.flags |= PM_NAMEDDIR; + adduserdir(pm->node.nam, x, 0, 0); + } + /* If you update this function, you may need to update the + * `Implement remainder of strsetfn' block in assignstrvalue(). */ +} + +/* Function to get value of an array parameter */ + +static char *nullarray = NULL; + +/**/ +char ** +arrgetfn(Param pm) +{ + return pm->u.arr ? pm->u.arr : &nullarray; +} + +/* Function to set value of an array parameter */ + +/**/ +mod_export void +arrsetfn(Param pm, char **x) +{ + if (pm->u.arr && pm->u.arr != x) + freearray(pm->u.arr); + if (pm->node.flags & PM_UNIQUE) + uniqarray(x); + pm->u.arr = x; + /* Arrays tied to colon-arrays may need to fix the environment */ + if (pm->ename && x) + arrfixenv(pm->ename, x); + /* If you extend this function, update the list of conditions in + * setarrvalue(). */ +} + +/* Function to get value of an association parameter */ + +/**/ +mod_export HashTable +hashgetfn(Param pm) +{ + return pm->u.hash; +} + +/* Function to set value of an association parameter */ + +/**/ +mod_export void +hashsetfn(Param pm, HashTable x) +{ + if (pm->u.hash && pm->u.hash != x) + deleteparamtable(pm->u.hash); + pm->u.hash = x; +} + +/* Function to dispose of setting of an unsettable hash */ + +/**/ +mod_export void +nullsethashfn(UNUSED(Param pm), HashTable x) +{ + deleteparamtable(x); +} + +/* Function to set value of an association parameter using key/value pairs */ + +/**/ +static void +arrhashsetfn(Param pm, char **val, int flags) +{ + /* Best not to shortcut this by using the existing hash table, * + * since that could cause trouble for special hashes. This way, * + * it's up to pm->gsu.h->setfn() what to do. */ + int alen = 0; + HashTable opmtab = paramtab, ht = 0; + char **aptr; + Value v = (Value) hcalloc(sizeof *v); + v->end = -1; + + for (aptr = val; *aptr; ++aptr) { + if (**aptr != Marker) + ++alen; + } + + if (alen % 2) { + freearray(val); + zerr("bad set of key/value pairs for associative array"); + return; + } + if (flags & ASSPM_AUGMENT) { + ht = paramtab = pm->gsu.h->getfn(pm); + } + if (alen && (!(flags & ASSPM_AUGMENT) || !paramtab)) { + ht = paramtab = newparamtable(17, pm->node.nam); + } + for (aptr = val; *aptr; ) { + int eltflags = 0; + if (**aptr == Marker) { + /* Either all elements have Marker or none. Checked in caller. */ + if ((*aptr)[1] == '+') { + /* Actually, assignstrvalue currently doesn't handle this... */ + eltflags = ASSPM_AUGMENT; + /* ...so we'll use the trick from setsparam(). */ + v->start = INT_MAX; + } else { + v->start = 0; + } + v->end = -1; + zsfree(*aptr++); + } + /* The parameter name is ztrdup'd... */ + v->pm = createparam(*aptr, PM_SCALAR|PM_UNSET); + /* + * createparam() doesn't return anything if the parameter + * already existed. + */ + if (!v->pm) + v->pm = (Param) paramtab->getnode(paramtab, *aptr); + zsfree(*aptr++); + /* ...but we can use the value without copying. */ + assignstrvalue(v, *aptr++, eltflags); + } + paramtab = opmtab; + pm->gsu.h->setfn(pm, ht); + free(val); /* not freearray() */ +} + +/* + * These functions are used as the set function for special parameters that + * cannot be set by the user. The set is incomplete as the only such + * parameters are scalar and integer. + */ + +/**/ +mod_export void +nullstrsetfn(UNUSED(Param pm), char *x) +{ + zsfree(x); +} + +/**/ +mod_export void +nullintsetfn(UNUSED(Param pm), UNUSED(zlong x)) +{} + +/**/ +mod_export void +nullunsetfn(UNUSED(Param pm), UNUSED(int exp)) +{} + + +/* Function to get value of generic special integer * + * parameter. data is pointer to global variable * + * containing the integer value. */ + +/**/ +mod_export zlong +intvargetfn(Param pm) +{ + return *pm->u.valptr; +} + +/* Function to set value of generic special integer * + * parameter. data is pointer to global variable * + * where the value is to be stored. */ + +/**/ +mod_export void +intvarsetfn(Param pm, zlong x) +{ + *pm->u.valptr = x; +} + +/* Function to set value of any ZLE-related integer * + * parameter. data is pointer to global variable * + * where the value is to be stored. */ + +/**/ +void +zlevarsetfn(Param pm, zlong x) +{ + zlong *p = pm->u.valptr; + + *p = x; + if (p == &zterm_lines || p == &zterm_columns) + adjustwinsize(2 + (p == &zterm_columns)); +} + + +/* Implements gsu_integer.unsetfn for ZLE_RPROMPT_INDENT; see stdunsetfn() */ + +static void +rprompt_indent_unsetfn(Param pm, int exp) +{ + stdunsetfn(pm, exp); + rprompt_indent = 1; /* Keep this in sync with init_term() */ +} + +/* Function to set value of generic special scalar * + * parameter. data is pointer to a character pointer * + * representing the scalar (string). */ + +/**/ +mod_export void +strvarsetfn(Param pm, char *x) +{ + char **q = ((char **)pm->u.data); + + zsfree(*q); + *q = x; +} + +/* Function to get value of generic special scalar * + * parameter. data is pointer to a character pointer * + * representing the scalar (string). */ + +/**/ +mod_export char * +strvargetfn(Param pm) +{ + char *s = *((char **)pm->u.data); + + if (!s) + return hcalloc(1); + return s; +} + +/* Function to get value of generic special array * + * parameter. data is a pointer to the pointer to * + * a pointer (a pointer to a variable length array * + * of pointers). */ + +/**/ +mod_export char ** +arrvargetfn(Param pm) +{ + char **arrptr = *((char ***)pm->u.data); + + return arrptr ? arrptr : &nullarray; +} + +/* Function to set value of generic special array parameter. * + * data is pointer to a variable length array of pointers which * + * represents this array of scalars (strings). If pm->ename is * + * non NULL, then it is a colon separated environment variable * + * version of this array which will need to be updated. */ + +/**/ +mod_export void +arrvarsetfn(Param pm, char **x) +{ + char ***dptr = (char ***)pm->u.data; + + if (*dptr != x) + freearray(*dptr); + if (pm->node.flags & PM_UNIQUE) + uniqarray(x); + /* + * Special tied arrays point to variables accessible in other + * ways which need to be set to NULL. We can't do this + * with user tied variables since we can leak memory. + */ + if ((pm->node.flags & PM_SPECIAL) && !x) + *dptr = mkarray(NULL); + else + *dptr = x; + if (pm->ename) { + if (x) + arrfixenv(pm->ename, x); + else if (*dptr == path) + pathchecked = path; + } +} + +/**/ +char * +colonarrgetfn(Param pm) +{ + char ***dptr = (char ***)pm->u.data; + return *dptr ? zjoin(*dptr, ':', 1) : ""; +} + +/**/ +void +colonarrsetfn(Param pm, char *x) +{ + char ***dptr = (char ***)pm->u.data; + /* + * We have to make sure this is never NULL, since that + * can cause problems. + */ + if (*dptr) + freearray(*dptr); + if (x) + *dptr = colonsplit(x, pm->node.flags & PM_UNIQUE); + else + *dptr = mkarray(NULL); + arrfixenv(pm->node.nam, *dptr); + zsfree(x); +} + +/**/ +char * +tiedarrgetfn(Param pm) +{ + struct tieddata *dptr = (struct tieddata *)pm->u.data; + return *dptr->arrptr ? zjoin(*dptr->arrptr, STOUC(dptr->joinchar), 1) : ""; +} + +/**/ +void +tiedarrsetfn(Param pm, char *x) +{ + struct tieddata *dptr = (struct tieddata *)pm->u.data; + + if (*dptr->arrptr) + freearray(*dptr->arrptr); + if (x) { + char sepbuf[3]; + if (imeta(dptr->joinchar)) + { + sepbuf[0] = Meta; + sepbuf[1] = dptr->joinchar ^ 32; + sepbuf[2] = '\0'; + } + else + { + sepbuf[0] = dptr->joinchar; + sepbuf[1] = '\0'; + } + *dptr->arrptr = sepsplit(x, sepbuf, 0, 0); + if (pm->node.flags & PM_UNIQUE) + uniqarray(*dptr->arrptr); + zsfree(x); + } else + *dptr->arrptr = NULL; + if (pm->ename) + arrfixenv(pm->node.nam, *dptr->arrptr); +} + +/**/ +void +tiedarrunsetfn(Param pm, UNUSED(int exp)) +{ + /* + * Special unset function because we allocated a struct tieddata + * in typeset_single to hold the special data which we now + * need to delete. + */ + pm->gsu.s->setfn(pm, NULL); + zfree(pm->u.data, sizeof(struct tieddata)); + /* paranoia -- shouldn't need these, but in case we reuse the struct... */ + pm->u.data = NULL; + zsfree(pm->ename); + pm->ename = NULL; + pm->node.flags &= ~PM_TIED; + pm->node.flags |= PM_UNSET; +} + +/**/ +static void +simple_arrayuniq(char **x, int freeok) +{ + char **t, **p = x; + char *hole = ""; + + /* Find duplicates and replace them with holes */ + while (*++p) + for (t = x; t < p; t++) + if (*t != hole && !strcmp(*p, *t)) { + if (freeok) + zsfree(*p); + *p = hole; + break; + } + /* Swap non-holes into holes in optimal jumps */ + for (p = t = x; *t != NULL; t++) { + if (*t == hole) { + while (*p == hole) + ++p; + if ((*t = *p) != NULL) + *p++ = hole; + } else if (p == t) + p++; + } + /* Erase all the remaining holes, just in case */ + while (++t < p) + *t = NULL; +} + +/**/ +static void +arrayuniq_freenode(HashNode hn) +{ + (void)hn; +} + +/**/ +HashTable +newuniqtable(zlong size) +{ + HashTable ht = newhashtable((int)size, "arrayuniq", NULL); + /* ??? error checking */ + + ht->hash = hasher; + ht->emptytable = emptyhashtable; + ht->filltable = NULL; + ht->cmpnodes = strcmp; + ht->addnode = addhashnode; + ht->getnode = gethashnode2; + ht->getnode2 = gethashnode2; + ht->removenode = removehashnode; + ht->disablenode = disablehashnode; + ht->enablenode = enablehashnode; + ht->freenode = arrayuniq_freenode; + ht->printnode = NULL; + + return ht; +} + +/**/ +static void +arrayuniq(char **x, int freeok) +{ + char **it, **write_it; + zlong array_size = arrlen(x); + HashTable ht; + + if (array_size == 0) + return; + if (array_size < 10 || !(ht = newuniqtable(array_size + 1))) { + /* fallback to simpler routine */ + simple_arrayuniq(x, freeok); + return; + } + + for (it = x, write_it = x; *it;) { + if (! gethashnode2(ht, *it)) { + HashNode new_node = zhalloc(sizeof(struct hashnode)); + if (!new_node) { + /* Oops, out of heap memory, no way to recover */ + zerr("out of memory in arrayuniq"); + break; + } + (void) addhashnode2(ht, *it, new_node); + *write_it = *it; + if (it != write_it) + *it = NULL; + ++write_it; + } + else { + if (freeok) + zsfree(*it); + *it = NULL; + } + ++it; + } + + deletehashtable(ht); +} + +/**/ +void +uniqarray(char **x) +{ + if (!x || !*x) + return; + arrayuniq(x, !zheapptr(*x)); +} + +/**/ +void +zhuniqarray(char **x) +{ + if (!x || !*x) + return; + arrayuniq(x, 0); +} + +/* Function to get value of special parameter `#' and `ARGC' */ + +/**/ +zlong +poundgetfn(UNUSED(Param pm)) +{ + return arrlen(pparams); +} + +/* Function to get value for special parameter `RANDOM' */ + +/**/ +zlong +randomgetfn(UNUSED(Param pm)) +{ + return rand() & 0x7fff; +} + +/* Function to set value of special parameter `RANDOM' */ + +/**/ +void +randomsetfn(UNUSED(Param pm), zlong v) +{ + srand((unsigned int)v); +} + +/* Function to get value for special parameter `SECONDS' */ + +/**/ +zlong +intsecondsgetfn(UNUSED(Param pm)) +{ + struct timeval now; + struct timezone dummy_tz; + + gettimeofday(&now, &dummy_tz); + + return (zlong)(now.tv_sec - shtimer.tv_sec - + (now.tv_usec < shtimer.tv_usec ? 1 : 0)); +} + +/* Function to set value of special parameter `SECONDS' */ + +/**/ +void +intsecondssetfn(UNUSED(Param pm), zlong x) +{ + struct timeval now; + struct timezone dummy_tz; + zlong diff; + + gettimeofday(&now, &dummy_tz); + diff = (zlong)now.tv_sec - x; + shtimer.tv_sec = diff; + if ((zlong)shtimer.tv_sec != diff) + zwarn("SECONDS truncated on assignment"); + shtimer.tv_usec = now.tv_usec; +} + +/**/ +double +floatsecondsgetfn(UNUSED(Param pm)) +{ + struct timeval now; + struct timezone dummy_tz; + + gettimeofday(&now, &dummy_tz); + + return (double)(now.tv_sec - shtimer.tv_sec) + + (double)(now.tv_usec - shtimer.tv_usec) / 1000000.0; +} + +/**/ +void +floatsecondssetfn(UNUSED(Param pm), double x) +{ + struct timeval now; + struct timezone dummy_tz; + + gettimeofday(&now, &dummy_tz); + shtimer.tv_sec = now.tv_sec - (zlong)x; + shtimer.tv_usec = now.tv_usec - (zlong)((x - (zlong)x) * 1000000.0); +} + +/**/ +double +getrawseconds(void) +{ + return (double)shtimer.tv_sec + (double)shtimer.tv_usec / 1000000.0; +} + +/**/ +void +setrawseconds(double x) +{ + shtimer.tv_sec = (zlong)x; + shtimer.tv_usec = (zlong)((x - (zlong)x) * 1000000.0); +} + +/**/ +int +setsecondstype(Param pm, int on, int off) +{ + int newflags = (pm->node.flags | on) & ~off; + int tp = PM_TYPE(newflags); + /* Only one of the numeric types is allowed. */ + if (tp == PM_EFLOAT || tp == PM_FFLOAT) + { + pm->gsu.f = &floatseconds_gsu; + } + else if (tp == PM_INTEGER) + { + pm->gsu.i = &intseconds_gsu; + } + else + return 1; + pm->node.flags = newflags; + return 0; +} + +/* Function to get value for special parameter `USERNAME' */ + +/**/ +char * +usernamegetfn(UNUSED(Param pm)) +{ + return get_username(); +} + +/* Function to set value of special parameter `USERNAME' */ + +/**/ +void +usernamesetfn(UNUSED(Param pm), char *x) +{ +#if defined(HAVE_SETUID) && defined(HAVE_GETPWNAM) + struct passwd *pswd; + + if (x && (pswd = getpwnam(x)) && (pswd->pw_uid != cached_uid)) { +# ifdef USE_INITGROUPS + initgroups(x, pswd->pw_gid); +# endif + if (setgid(pswd->pw_gid)) + zwarn("failed to change group ID: %e", errno); + else if (setuid(pswd->pw_uid)) + zwarn("failed to change user ID: %e", errno); + else { + zsfree(cached_username); + cached_username = ztrdup(pswd->pw_name); + cached_uid = pswd->pw_uid; + } + } +#endif /* HAVE_SETUID && HAVE_GETPWNAM */ + zsfree(x); +} + +/* Function to get value for special parameter `UID' */ + +/**/ +zlong +uidgetfn(UNUSED(Param pm)) +{ + return getuid(); +} + +/* Function to set value of special parameter `UID' */ + +/**/ +void +uidsetfn(UNUSED(Param pm), zlong x) +{ +#ifdef HAVE_SETUID + if (setuid((uid_t)x)) + zerr("failed to change user ID: %e", errno); +#endif +} + +/* Function to get value for special parameter `EUID' */ + +/**/ +zlong +euidgetfn(UNUSED(Param pm)) +{ + return geteuid(); +} + +/* Function to set value of special parameter `EUID' */ + +/**/ +void +euidsetfn(UNUSED(Param pm), zlong x) +{ +#ifdef HAVE_SETEUID + if (seteuid((uid_t)x)) + zerr("failed to change effective user ID: %e", errno); +#endif +} + +/* Function to get value for special parameter `GID' */ + +/**/ +zlong +gidgetfn(UNUSED(Param pm)) +{ + return getgid(); +} + +/* Function to set value of special parameter `GID' */ + +/**/ +void +gidsetfn(UNUSED(Param pm), zlong x) +{ +#ifdef HAVE_SETUID + if (setgid((gid_t)x)) + zerr("failed to change group ID: %e", errno); +#endif +} + +/* Function to get value for special parameter `EGID' */ + +/**/ +zlong +egidgetfn(UNUSED(Param pm)) +{ + return getegid(); +} + +/* Function to set value of special parameter `EGID' */ + +/**/ +void +egidsetfn(UNUSED(Param pm), zlong x) +{ +#ifdef HAVE_SETEUID + if (setegid((gid_t)x)) + zerr("failed to change effective group ID: %e", errno); +#endif +} + +/**/ +zlong +ttyidlegetfn(UNUSED(Param pm)) +{ + struct stat ttystat; + + if (SHTTY == -1 || fstat(SHTTY, &ttystat)) + return -1; + return time(NULL) - ttystat.st_atime; +} + +/* Function to get value for special parameter `IFS' */ + +/**/ +char * +ifsgetfn(UNUSED(Param pm)) +{ + return ifs; +} + +/* Function to set value of special parameter `IFS' */ + +/**/ +void +ifssetfn(UNUSED(Param pm), char *x) +{ + zsfree(ifs); + ifs = x; + inittyptab(); +} + +/* Functions to set value of special parameters `LANG' and `LC_*' */ + +#ifdef USE_LOCALE +static struct localename { + char *name; + int category; +} lc_names[] = { +#ifdef LC_COLLATE + {"LC_COLLATE", LC_COLLATE}, +#endif +#ifdef LC_CTYPE + {"LC_CTYPE", LC_CTYPE}, +#endif +#ifdef LC_MESSAGES + {"LC_MESSAGES", LC_MESSAGES}, +#endif +#ifdef LC_NUMERIC + {"LC_NUMERIC", LC_NUMERIC}, +#endif +#ifdef LC_TIME + {"LC_TIME", LC_TIME}, +#endif + {NULL, 0} +}; + +/**/ +static void +setlang(char *x) +{ + struct localename *ln; + char *x2; + + if ((x2 = getsparam_u("LC_ALL")) && *x2) + return; + + /* + * Set the global locale to the value passed, but override + * this with any non-empty definitions for specific + * categories. + * + * We only use non-empty definitions because empty values aren't + * valid as locales; when passed to setlocale() they mean "use the + * environment variable", but if that's what we're setting the value + * from this is meaningless. So just all $LANG to show through in + * that case. + */ + setlocale(LC_ALL, x ? unmeta(x) : ""); + queue_signals(); + for (ln = lc_names; ln->name; ln++) + if ((x = getsparam_u(ln->name)) && *x) + setlocale(ln->category, x); + unqueue_signals(); +} + +/**/ +void +lc_allsetfn(Param pm, char *x) +{ + strsetfn(pm, x); + /* + * Treat an empty LC_ALL the same as an unset one, + * namely by using LANG as the default locale but overriding + * that with any LC_* that are set. + */ + if (!x || !*x) { + x = getsparam_u("LANG"); + if (x && *x) { + queue_signals(); + setlang(x); + unqueue_signals(); + } + } + else + setlocale(LC_ALL, unmeta(x)); +} + +/**/ +void +langsetfn(Param pm, char *x) +{ + strsetfn(pm, x); + setlang(unmeta(x)); +} + +/**/ +void +lcsetfn(Param pm, char *x) +{ + char *x2; + struct localename *ln; + + strsetfn(pm, x); + if ((x2 = getsparam("LC_ALL")) && *x2) + return; + queue_signals(); + /* Treat empty LC_* the same as unset. */ + if (!x || !*x) + x = getsparam("LANG"); + + /* + * If we've got no non-empty string at this + * point (after checking $LANG, too), + * we shouldn't bother setting anything. + */ + if (x && *x) { + for (ln = lc_names; ln->name; ln++) + if (!strcmp(ln->name, pm->node.nam)) + setlocale(ln->category, unmeta(x)); + } + unqueue_signals(); +} +#endif /* USE_LOCALE */ + +/* Function to set value for special parameter `0' */ + +/**/ +static void +argzerosetfn(UNUSED(Param pm), char *x) +{ + if (x) { + if (isset(POSIXARGZERO)) + zerr("read-only variable: 0"); + else { + zsfree(argzero); + argzero = ztrdup(x); + } + zsfree(x); + } +} + +/* Function to get value for special parameter `0' */ + +/**/ +static char * +argzerogetfn(UNUSED(Param pm)) +{ + if (isset(POSIXARGZERO)) + return posixzero; + return argzero; +} + +/* Function to get value for special parameter `HISTSIZE' */ + +/**/ +zlong +histsizegetfn(UNUSED(Param pm)) +{ + return histsiz; +} + +/* Function to set value of special parameter `HISTSIZE' */ + +/**/ +void +histsizesetfn(UNUSED(Param pm), zlong v) +{ + if ((histsiz = v) < 1) + histsiz = 1; + resizehistents(); +} + +/* Function to get value for special parameter `SAVEHIST' */ + +/**/ +zlong +savehistsizegetfn(UNUSED(Param pm)) +{ + return savehistsiz; +} + +/* Function to set value of special parameter `SAVEHIST' */ + +/**/ +void +savehistsizesetfn(UNUSED(Param pm), zlong v) +{ + if ((savehistsiz = v) < 0) + savehistsiz = 0; +} + +/* Function to set value for special parameter `ERRNO' */ + +/**/ +void +errnosetfn(UNUSED(Param pm), zlong x) +{ + errno = (int)x; + if ((zlong)errno != x) + zwarn("errno truncated on assignment"); +} + +/* Function to get value for special parameter `ERRNO' */ + +/**/ +zlong +errnogetfn(UNUSED(Param pm)) +{ + return errno; +} + +/* Function to get value for special parameter `KEYBOARD_HACK' */ + +/**/ +char * +keyboardhackgetfn(UNUSED(Param pm)) +{ + static char buf[2]; + + buf[0] = keyboardhackchar; + buf[1] = '\0'; + return buf; +} + + +/* Function to set value of special parameter `KEYBOARD_HACK' */ + +/**/ +void +keyboardhacksetfn(UNUSED(Param pm), char *x) +{ + if (x) { + int len, i; + + unmetafy(x, &len); + if (len > 1) { + len = 1; + zwarn("Only one KEYBOARD_HACK character can be defined"); /* could be changed if needed */ + } + for (i = 0; i < len; i++) { + if (!isascii(STOUC(x[i]))) { + zwarn("KEYBOARD_HACK can only contain ASCII characters"); + return; + } + } + keyboardhackchar = len ? STOUC(x[0]) : '\0'; + free(x); + } else + keyboardhackchar = '\0'; +} + +/* Function to get value for special parameter `histchar' */ + +/**/ +char * +histcharsgetfn(UNUSED(Param pm)) +{ + static char buf[4]; + + buf[0] = bangchar; + buf[1] = hatchar; + buf[2] = hashchar; + buf[3] = '\0'; + return buf; +} + +/* Function to set value of special parameter `histchar' */ + +/**/ +void +histcharssetfn(UNUSED(Param pm), char *x) +{ + if (x) { + int len, i; + + unmetafy(x, &len); + if (len > 3) + len = 3; + for (i = 0; i < len; i++) { + if (!isascii(STOUC(x[i]))) { + zwarn("HISTCHARS can only contain ASCII characters"); + return; + } + } + bangchar = len ? STOUC(x[0]) : '\0'; + hatchar = len > 1 ? STOUC(x[1]) : '\0'; + hashchar = len > 2 ? STOUC(x[2]) : '\0'; + free(x); + } else { + bangchar = '!'; + hashchar = '#'; + hatchar = '^'; + } + inittyptab(); +} + +/* Function to get value for special parameter `HOME' */ + +/**/ +char * +homegetfn(UNUSED(Param pm)) +{ + return home; +} + +/* Function to set value of special parameter `HOME' */ + +/**/ +void +homesetfn(UNUSED(Param pm), char *x) +{ + zsfree(home); + if (x && isset(CHASELINKS) && (home = xsymlink(x, 0))) + zsfree(x); + else + home = x ? x : ztrdup(""); + finddir(NULL); +} + +/* Function to get value for special parameter `WORDCHARS' */ + +/**/ +char * +wordcharsgetfn(UNUSED(Param pm)) +{ + return wordchars; +} + +/* Function to set value of special parameter `WORDCHARS' */ + +/**/ +void +wordcharssetfn(UNUSED(Param pm), char *x) +{ + zsfree(wordchars); + wordchars = x; + inittyptab(); +} + +/* Function to get value for special parameter `_' */ + +/**/ +char * +underscoregetfn(UNUSED(Param pm)) +{ + char *u = dupstring(zunderscore); + + untokenize(u); + return u; +} + +/* Function used when we need to reinitialise the terminal */ + +static void +term_reinit_from_pm(void) +{ + /* If non-interactive, delay setting up term till we need it. */ + if (unset(INTERACTIVE) || !*term) + termflags |= TERM_UNKNOWN; + else + init_term(); +} + +/* Function to get value for special parameter `TERM' */ + +/**/ +char * +termgetfn(UNUSED(Param pm)) +{ + return term; +} + +/* Function to set value of special parameter `TERM' */ + +/**/ +void +termsetfn(UNUSED(Param pm), char *x) +{ + zsfree(term); + term = x ? x : ztrdup(""); + term_reinit_from_pm(); +} + +/* Function to get value of special parameter `TERMINFO' */ + +/**/ +char * +terminfogetfn(UNUSED(Param pm)) +{ + return zsh_terminfo ? zsh_terminfo : dupstring(""); +} + +/* Function to set value of special parameter `TERMINFO' */ + +/**/ +void +terminfosetfn(Param pm, char *x) +{ + zsfree(zsh_terminfo); + zsh_terminfo = x; + + /* + * terminfo relies on the value being exported before + * we reinitialise the terminal. This is a bit inefficient. + */ + if ((pm->node.flags & PM_EXPORTED) && x) + addenv(pm, x); + + term_reinit_from_pm(); +} + +/* Function to get value of special parameter `TERMINFO_DIRS' */ + +/**/ +char * +terminfodirsgetfn(UNUSED(Param pm)) +{ + return zsh_terminfodirs ? zsh_terminfodirs : dupstring(""); +} + +/* Function to set value of special parameter `TERMINFO_DIRS' */ + +/**/ +void +terminfodirssetfn(Param pm, char *x) +{ + zsfree(zsh_terminfodirs); + zsh_terminfodirs = x; + + /* + * terminfo relies on the value being exported before + * we reinitialise the terminal. This is a bit inefficient. + */ + if ((pm->node.flags & PM_EXPORTED) && x) + addenv(pm, x); + + term_reinit_from_pm(); +} +/* Function to get value for special parameter `pipestatus' */ + +/**/ +static char ** +pipestatgetfn(UNUSED(Param pm)) +{ + char **x = (char **) zhalloc((numpipestats + 1) * sizeof(char *)); + char buf[DIGBUFSIZE], **p; + int *q, i; + + for (p = x, q = pipestats, i = numpipestats; i--; p++, q++) { + sprintf(buf, "%d", *q); + *p = dupstring(buf); + } + *p = NULL; + + return x; +} + +/* Function to get value for special parameter `pipestatus' */ + +/**/ +static void +pipestatsetfn(UNUSED(Param pm), char **x) +{ + if (x) { + int i; + + for (i = 0; *x && i < MAX_PIPESTATS; i++, x++) + pipestats[i] = atoi(*x); + numpipestats = i; + } + else + numpipestats = 0; +} + +/**/ +void +arrfixenv(char *s, char **t) +{ + Param pm; + int joinchar; + + if (t == path) + cmdnamtab->emptytable(cmdnamtab); + + pm = (Param) paramtab->getnode(paramtab, s); + + /* + * Only one level of a parameter can be exported. Unless + * ALLEXPORT is set, this must be global. + */ + + if (pm->node.flags & PM_HASHELEM) + return; + + if (isset(ALLEXPORT)) + pm->node.flags |= PM_EXPORTED; + + /* + * Do not "fix" parameters that were not exported + */ + + if (!(pm->node.flags & PM_EXPORTED)) + return; + + if (pm->node.flags & PM_TIED) + joinchar = STOUC(((struct tieddata *)pm->u.data)->joinchar); + else + joinchar = ':'; + + addenv(pm, t ? zjoin(t, joinchar, 1) : ""); +} + + +/**/ +int +zputenv(char *str) +{ + DPUTS(!str, "Attempt to put null string into environment."); +#ifdef USE_SET_UNSET_ENV + /* + * If we are using unsetenv() to remove values from the + * environment, which is the safe thing to do, we + * need to use setenv() to put them there in the first place. + * Unfortunately this is a slightly different interface + * from what zputenv() assumes. + */ + char *ptr; + int ret; + + for (ptr = str; *ptr && STOUC(*ptr) < 128 && *ptr != '='; ptr++) + ; + if (STOUC(*ptr) >= 128) { + /* + * Environment variables not in the portable character + * set are non-standard and we don't really know of + * a use for them. + * + * We'll disable until someone complains. + */ + return 1; + } else if (*ptr) { + *ptr = '\0'; + ret = setenv(str, ptr+1, 1); + *ptr = '='; + } else { + /* safety first */ + DPUTS(1, "bad environment string"); + ret = setenv(str, ptr, 1); + } + return ret; +#else +#ifdef HAVE_PUTENV + return putenv(str); +#else + char **ep; + int num_env; + + + /* First check if there is already an environment * + * variable matching string `name'. */ + if (findenv(str, &num_env)) { + environ[num_env] = str; + } else { + /* Else we have to make room and add it */ + num_env = arrlen(environ); + environ = (char **) zrealloc(environ, (sizeof(char *)) * (num_env + 2)); + + /* Now add it at the end */ + ep = environ + num_env; + *ep = str; + *(ep + 1) = NULL; + } + return 0; +#endif +#endif +} + +/**/ +#ifndef USE_SET_UNSET_ENV +/**/ +static int +findenv(char *name, int *pos) +{ + char **ep, *eq; + int nlen; + + + eq = strchr(name, '='); + nlen = eq ? eq - name : (int)strlen(name); + for (ep = environ; *ep; ep++) + if (!strncmp (*ep, name, nlen) && *((*ep)+nlen) == '=') { + if (pos) + *pos = ep - environ; + return 1; + } + + return 0; +} +/**/ +#endif + +/* Given *name = "foo", it searches the environment for string * + * "foo=bar", and returns a pointer to the beginning of "bar" */ + +/**/ +mod_export char * +zgetenv(char *name) +{ +#ifdef HAVE_GETENV + return getenv(name); +#else + char **ep, *s, *t; + + for (ep = environ; *ep; ep++) { + for (s = *ep, t = name; *s && *s == *t; s++, t++); + if (*s == '=' && !*t) + return s + 1; + } + return NULL; +#endif +} + +/**/ +static void +copyenvstr(char *s, char *value, int flags) +{ + while (*s++) { + if ((*s = *value++) == Meta) + *s = *value++ ^ 32; + if (flags & PM_LOWER) + *s = tulower(*s); + else if (flags & PM_UPPER) + *s = tuupper(*s); + } +} + +/**/ +void +addenv(Param pm, char *value) +{ + char *newenv = 0; +#ifndef USE_SET_UNSET_ENV + char *oldenv = 0, *env = 0; + int pos; + + /* + * First check if there is already an environment + * variable matching string `name'. + */ + if (findenv(pm->node.nam, &pos)) + oldenv = environ[pos]; +#endif + + newenv = mkenvstr(pm->node.nam, value, pm->node.flags); + if (zputenv(newenv)) { + zsfree(newenv); + pm->env = NULL; + return; + } +#ifdef USE_SET_UNSET_ENV + /* + * If we are using setenv/unsetenv to manage the environment, + * we simply store the string we created in pm->env since + * memory management of the environment is handled entirely + * by the system. + * + * TODO: is this good enough to fix problem cases from + * the other branch? If so, we don't actually need to + * store pm->env at all, just a flag that the value was set. + */ + if (pm->env) + zsfree(pm->env); + pm->env = newenv; + pm->node.flags |= PM_EXPORTED; +#else + /* + * Under Cygwin we must use putenv() to maintain consistency. + * Unfortunately, current version (1.1.2) copies argument and may + * silently reuse existing environment string. This tries to + * check for both cases + */ + if (findenv(pm->node.nam, &pos)) { + env = environ[pos]; + if (env != oldenv) + zsfree(oldenv); + if (env != newenv) + zsfree(newenv); + pm->node.flags |= PM_EXPORTED; + pm->env = env; + return; + } + + DPUTS(1, "addenv should never reach the end"); + pm->env = NULL; +#endif +} + + +/* Given strings *name = "foo", *value = "bar", * + * return a new string *str = "foo=bar". */ + +/**/ +static char * +mkenvstr(char *name, char *value, int flags) +{ + char *str, *s = value; + int len_name, len_value = 0; + + len_name = strlen(name); + if (s) + while (*s && (*s++ != Meta || *s++ != 32)) + len_value++; + s = str = (char *) zalloc(len_name + len_value + 2); + strcpy(s, name); + s += len_name; + *s = '='; + if (value) + copyenvstr(s, value, flags); + else + *++s = '\0'; + return str; +} + +/* Given *name = "foo", *value = "bar", add the * + * string "foo=bar" to the environment. Return a * + * pointer to the location of this new environment * + * string. */ + + +#ifndef USE_SET_UNSET_ENV +/**/ +void +delenvvalue(char *x) +{ + char **ep; + + for (ep = environ; *ep; ep++) { + if (*ep == x) + break; + } + if (*ep) { + for (; (ep[0] = ep[1]); ep++); + } + zsfree(x); +} +#endif + + +/* Delete a pointer from the list of pointers to environment * + * variables by shifting all the other pointers up one slot. */ + +/**/ +void +delenv(Param pm) +{ +#ifdef USE_SET_UNSET_ENV + unsetenv(pm->node.nam); + zsfree(pm->env); +#else + delenvvalue(pm->env); +#endif + pm->env = NULL; + /* + * Note we don't remove PM_EXPORT from the flags. This + * may be asking for trouble but we need to know later + * if we restore this parameter to its old value. + */ +} + +/* + * Guts of convbase: this version can return the number of digits + * sans any base discriminator. + */ + +/**/ +void +convbase_ptr(char *s, zlong v, int base, int *ndigits) +{ + int digs = 0; + zulong x; + + if (v < 0) + *s++ = '-', v = -v; + if (base >= -1 && base <= 1) + base = -10; + + if (base > 0) { + if (isset(CBASES) && base == 16) + sprintf(s, "0x"); + else if (isset(CBASES) && base == 8 && isset(OCTALZEROES)) + sprintf(s, "0"); + else if (base != 10) + sprintf(s, "%d#", base); + else + *s = 0; + s += strlen(s); + } else + base = -base; + for (x = v; x; digs++) + x /= base; + if (!digs) + digs = 1; + if (ndigits) + *ndigits = digs; + s[digs--] = '\0'; + x = v; + while (digs >= 0) { + int dig = x % base; + + s[digs--] = (dig < 10) ? '0' + dig : dig - 10 + 'A'; + x /= base; + } +} + +/* + * Basic conversion of integer to a string given a base. + * If 0 base is 10. + * If negative no base discriminator is output. + */ + +/**/ +mod_export void +convbase(char *s, zlong v, int base) +{ + convbase_ptr(s, v, base, NULL); +} + +/* + * Add underscores to converted integer for readability with given spacing. + * s is as for convbase: at least BDIGBUFSIZE. + * If underscores were added, returned value with underscores comes from + * heap, else the returned value is s. + */ + +/**/ +char * +convbase_underscore(char *s, zlong v, int base, int underscore) +{ + char *retptr, *sptr, *dptr; + int ndigits, nunderscore, mod, len; + + convbase_ptr(s, v, base, &ndigits); + + if (underscore <= 0) + return s; + + nunderscore = (ndigits - 1) / underscore; + if (!nunderscore) + return s; + len = strlen(s); + retptr = zhalloc(len + nunderscore + 1); + mod = 0; + memcpy(retptr, s, len - ndigits); + sptr = s + len; + dptr = retptr + len + nunderscore; + /* copy the null */ + *dptr-- = *sptr--; + for (;;) { + *dptr = *sptr; + if (!--ndigits) + break; + dptr--; + sptr--; + if (++mod == underscore) { + mod = 0; + *dptr-- = '_'; + } + } + + return retptr; +} + +/* + * Convert a floating point value for output. + * Unlike convbase(), this has its own internal storage and returns + * a value from the heap. + */ + +/**/ +char * +convfloat(double dval, int digits, int flags, FILE *fout) +{ + char fmt[] = "%.*e"; + char *prev_locale, *ret; + + /* + * The difficulty with the buffer size is that a %f conversion + * prints all digits before the decimal point: with 64 bit doubles, + * that's around 310. We can't check without doing some quite + * serious floating point operations we'd like to avoid. + * Then we are liable to get all the digits + * we asked for after the decimal point, or we should at least + * bargain for it. So we just allocate 512 + digits. This + * should work until somebody decides on 128-bit doubles. + */ + if (!(flags & (PM_EFLOAT|PM_FFLOAT))) { + /* + * Conversion from a floating point expression without using + * a variable. The best bet in this case just seems to be + * to use the general %g format with something like the maximum + * double precision. + */ + fmt[3] = 'g'; + if (!digits) + digits = 17; + } else { + if (flags & PM_FFLOAT) + fmt[3] = 'f'; + if (digits <= 0) + digits = 10; + if (flags & PM_EFLOAT) { + /* + * Here, we are given the number of significant figures, but + * %e wants the number of decimal places (unlike %g) + */ + digits--; + } + } +#ifdef USE_LOCALE + prev_locale = dupstring(setlocale(LC_NUMERIC, NULL)); + setlocale(LC_NUMERIC, "POSIX"); +#endif + if (fout) { + fprintf(fout, fmt, digits, dval); + ret = NULL; + } else { + VARARR(char, buf, 512 + digits); + if (isinf(dval)) + ret = dupstring((dval < 0.0) ? "-Inf" : "Inf"); + else if (isnan(dval)) + ret = dupstring("NaN"); + else { + sprintf(buf, fmt, digits, dval); + if (!strchr(buf, 'e') && !strchr(buf, '.')) + strcat(buf, "."); + ret = dupstring(buf); + } + } +#ifdef USE_LOCALE + if (prev_locale) setlocale(LC_NUMERIC, prev_locale); +#endif + return ret; +} + +/* + * convert float to string with basic options but inserting underscores + * for readability. + */ + +/**/ +char *convfloat_underscore(double dval, int underscore) +{ + int ndigits_int = 0, ndigits_frac = 0, nunderscore, len; + char *s, *retptr, *sptr, *dptr; + + s = convfloat(dval, 0, 0, NULL); + if (underscore <= 0) + return s; + + /* + * Count the number of digits before and after the decimal point, if any. + */ + sptr = s; + if (*sptr == '-') + sptr++; + while (idigit(*sptr)) { + ndigits_int++; + sptr++; + } + if (*sptr == '.') { + sptr++; + while (idigit(*sptr)) { + ndigits_frac++; + sptr++; + } + } + + /* + * Work out how many underscores to insert --- remember we + * put them in integer and fractional parts separately. + */ + nunderscore = (ndigits_int-1) / underscore + (ndigits_frac-1) / underscore; + if (!nunderscore) + return s; + len = strlen(s); + dptr = retptr = zhalloc(len + nunderscore + 1); + + /* + * Insert underscores in integer part. + * Grouping starts from the point in both directions. + */ + sptr = s; + if (*sptr == '-') + *dptr++ = *sptr++; + while (ndigits_int) { + *dptr++ = *sptr++; + if (--ndigits_int && !(ndigits_int % underscore)) + *dptr++ = '_'; + } + if (ndigits_frac) { + /* + * Insert underscores in the fractional part. + */ + int mod = 0; + /* decimal point, we already checked */ + *dptr++ = *sptr++; + while (ndigits_frac) { + *dptr++ = *sptr++; + mod++; + if (--ndigits_frac && mod == underscore) { + *dptr++ = '_'; + mod = 0; + } + } + } + /* Copy exponent and anything else up to null */ + while ((*dptr++ = *sptr++)) + ; + return retptr; +} + +/* Start a parameter scope */ + +/**/ +mod_export void +startparamscope(void) +{ + locallevel++; +} + +/* End a parameter scope: delete the parameters local to the scope. */ + +/**/ +mod_export void +endparamscope(void) +{ + queue_signals(); + locallevel--; + /* This pops anything from a higher locallevel */ + saveandpophiststack(0, HFILE_USE_OPTIONS); + scanhashtable(paramtab, 0, 0, 0, scanendscope, 0); + unqueue_signals(); +} + +/**/ +static void +scanendscope(HashNode hn, UNUSED(int flags)) +{ + Param pm = (Param)hn; + if (pm->level > locallevel) { + if ((pm->node.flags & (PM_SPECIAL|PM_REMOVABLE)) == PM_SPECIAL) { + /* + * Removable specials are normal in that they can be removed + * to reveal an ordinary parameter beneath. Here we handle + * non-removable specials, which were made local by stealth + * (see newspecial code in typeset_single()). In fact the + * visible pm is always the same struct; the pm->old is + * just a place holder for old data and flags. + */ + Param tpm = pm->old; + + if (!strcmp(pm->node.nam, "SECONDS")) + { + setsecondstype(pm, PM_TYPE(tpm->node.flags), PM_TYPE(pm->node.flags)); + /* + * We restore SECONDS by restoring its raw internal value + * that we cached off into tpm->u.dval. + */ + setrawseconds(tpm->u.dval); + tpm->node.flags |= PM_NORESTORE; + } + DPUTS(!tpm || PM_TYPE(pm->node.flags) != PM_TYPE(tpm->node.flags) || + !(tpm->node.flags & PM_SPECIAL), + "BUG: in restoring scope of special parameter"); + pm->old = tpm->old; + pm->node.flags = (tpm->node.flags & ~PM_NORESTORE); + pm->level = tpm->level; + pm->base = tpm->base; + pm->width = tpm->width; + if (pm->env) + delenv(pm); + + if (!(tpm->node.flags & (PM_NORESTORE|PM_READONLY))) + switch (PM_TYPE(pm->node.flags)) { + case PM_SCALAR: + pm->gsu.s->setfn(pm, tpm->u.str); + break; + case PM_INTEGER: + pm->gsu.i->setfn(pm, tpm->u.val); + break; + case PM_EFLOAT: + case PM_FFLOAT: + pm->gsu.f->setfn(pm, tpm->u.dval); + break; + case PM_ARRAY: + pm->gsu.a->setfn(pm, tpm->u.arr); + break; + case PM_HASHED: + pm->gsu.h->setfn(pm, tpm->u.hash); + break; + } + zfree(tpm, sizeof(*tpm)); + + if (pm->node.flags & PM_EXPORTED) + export_param(pm); + } else + unsetparam_pm(pm, 0, 0); + } +} + + +/**********************************/ +/* Parameter Hash Table Functions */ +/**********************************/ + +/**/ +void +freeparamnode(HashNode hn) +{ + Param pm = (Param) hn; + + /* The second argument of unsetfn() is used by modules to + * differentiate "exp"licit unset from implicit unset, as when + * a parameter is going out of scope. It's not clear which + * of these applies here, but passing 1 has always worked. + */ + if (delunset) + pm->gsu.s->unsetfn(pm, 1); + zsfree(pm->node.nam); + /* If this variable was tied by the user, ename was ztrdup'd */ + if (pm->node.flags & PM_TIED) + zsfree(pm->ename); + zfree(pm, sizeof(struct param)); +} + +/* Print a parameter */ + +enum paramtypes_flags { + PMTF_USE_BASE = (1<<0), + PMTF_USE_WIDTH = (1<<1), + PMTF_TEST_LEVEL = (1<<2) +}; + +struct paramtypes { + int binflag; /* The relevant PM_FLAG(S) */ + const char *string; /* String for verbose output */ + int typeflag; /* Flag for typeset -? */ + int flags; /* The enum above */ +}; + +static const struct paramtypes pmtypes[] = { + { PM_AUTOLOAD, "undefined", 0, 0}, + { PM_INTEGER, "integer", 'i', PMTF_USE_BASE}, + { PM_EFLOAT, "float", 'E', 0}, + { PM_FFLOAT, "float", 'F', 0}, + { PM_ARRAY, "array", 'a', 0}, + { PM_HASHED, "association", 'A', 0}, + { 0, "local", 0, PMTF_TEST_LEVEL}, + { PM_LEFT, "left justified", 'L', PMTF_USE_WIDTH}, + { PM_RIGHT_B, "right justified", 'R', PMTF_USE_WIDTH}, + { PM_RIGHT_Z, "zero filled", 'Z', PMTF_USE_WIDTH}, + { PM_LOWER, "lowercase", 'l', 0}, + { PM_UPPER, "uppercase", 'u', 0}, + { PM_READONLY, "readonly", 'r', 0}, + { PM_TAGGED, "tagged", 't', 0}, + { PM_EXPORTED, "exported", 'x', 0} +}; + +#define PMTYPES_SIZE ((int)(sizeof(pmtypes)/sizeof(struct paramtypes))) + +static void +printparamvalue(Param p, int printflags) +{ + char *t, **u; + + if (!(printflags & PRINT_KV_PAIR)) + putchar('='); + + /* How the value is displayed depends * + * on the type of the parameter */ + switch (PM_TYPE(p->node.flags)) { + case PM_SCALAR: + /* string: simple output */ + if (p->gsu.s->getfn && (t = p->gsu.s->getfn(p))) + quotedzputs(t, stdout); + break; + case PM_INTEGER: + /* integer */ +#ifdef ZSH_64_BIT_TYPE + fputs(output64(p->gsu.i->getfn(p)), stdout); +#else + printf("%ld", p->gsu.i->getfn(p)); +#endif + break; + case PM_EFLOAT: + case PM_FFLOAT: + /* float */ + convfloat(p->gsu.f->getfn(p), p->base, p->node.flags, stdout); + break; + case PM_ARRAY: + /* array */ + if (!(printflags & PRINT_KV_PAIR)) { + putchar('('); + if (!(printflags & PRINT_LINE)) + putchar(' '); + } + u = p->gsu.a->getfn(p); + if(*u) { + if (printflags & PRINT_LINE) { + if (printflags & PRINT_KV_PAIR) + printf(" "); + else + printf("\n "); + } + quotedzputs(*u++, stdout); + while (*u) { + if (printflags & PRINT_LINE) + printf("\n "); + else + putchar(' '); + quotedzputs(*u++, stdout); + } + if ((printflags & (PRINT_LINE|PRINT_KV_PAIR)) == PRINT_LINE) + putchar('\n'); + } + if (!(printflags & PRINT_KV_PAIR)) { + if (!(printflags & PRINT_LINE)) + putchar(' '); + putchar(')'); + } + break; + case PM_HASHED: + /* association */ + { + HashTable ht; + int found = 0; + if (!(printflags & PRINT_KV_PAIR)) { + putchar('('); + if (!(printflags & PRINT_LINE)) + putchar(' '); + } + ht = p->gsu.h->getfn(p); + if (ht) + found = scanhashtable(ht, 1, 0, PM_UNSET, + ht->printnode, PRINT_KV_PAIR | + (printflags & PRINT_LINE)); + if (!(printflags & PRINT_KV_PAIR)) { + if (found && (printflags & PRINT_LINE)) + putchar('\n'); + putchar(')'); + } + } + break; + } + if ((printflags & (PRINT_KV_PAIR|PRINT_LINE)) == PRINT_KV_PAIR) + putchar(' '); + else if (!(printflags & PRINT_KV_PAIR)) + putchar('\n'); +} + +/**/ +mod_export void +printparamnode(HashNode hn, int printflags) +{ + Param p = (Param) hn; + + if (p->node.flags & PM_UNSET) { + if (isset(POSIXBUILTINS) && (p->node.flags & PM_READONLY) && + (printflags & PRINT_TYPESET)) + { + /* + * Special POSIX rules: show the parameter as readonly + * even though it's unset, but with no value. + */ + printflags |= PRINT_NAMEONLY; + } + else if (p->node.flags & PM_EXPORTED) + printflags |= PRINT_NAMEONLY; + else + return; + } + if (p->node.flags & PM_AUTOLOAD) + printflags |= PRINT_NAMEONLY; + + if (printflags & PRINT_TYPESET) { + if ((p->node.flags & (PM_READONLY|PM_SPECIAL)) == + (PM_READONLY|PM_SPECIAL) || + (p->node.flags & PM_AUTOLOAD)) { + /* + * It's not possible to restore the state of + * these, so don't output. + */ + return; + } + if (locallevel && p->level >= locallevel) { + printf("typeset "); /* printf("local "); */ + } else if ((p->node.flags & PM_EXPORTED) && + !(p->node.flags & (PM_ARRAY|PM_HASHED))) { + printf("export "); + } else if (locallevel) { + printf("typeset -g "); + } else + printf("typeset "); + } + + /* Print the attributes of the parameter */ + if (printflags & (PRINT_TYPE|PRINT_TYPESET)) { + int doneminus = 0, i; + const struct paramtypes *pmptr; + + for (pmptr = pmtypes, i = 0; i < PMTYPES_SIZE; i++, pmptr++) { + int doprint = 0; + if (pmptr->flags & PMTF_TEST_LEVEL) { + if (p->level) + doprint = 1; + } else if ((pmptr->binflag != PM_EXPORTED || p->level || + (p->node.flags & (PM_LOCAL|PM_ARRAY|PM_HASHED))) && + (p->node.flags & pmptr->binflag)) + doprint = 1; + + if (doprint) { + if (printflags & PRINT_TYPESET) { + if (pmptr->typeflag) { + if (!doneminus) { + putchar('-'); + doneminus = 1; + } + putchar(pmptr->typeflag); + } + } else + printf("%s ", pmptr->string); + if ((pmptr->flags & PMTF_USE_BASE) && p->base) { + printf("%d ", p->base); + doneminus = 0; + } + if ((pmptr->flags & PMTF_USE_WIDTH) && p->width) { + printf("%d ", p->width); + doneminus = 0; + } + } + } + if (doneminus) + putchar(' '); + } + + if ((printflags & PRINT_NAMEONLY) || + ((p->node.flags & PM_HIDEVAL) && !(printflags & PRINT_INCLUDEVALUE))) { + zputs(p->node.nam, stdout); + putchar('\n'); + } else { + if (printflags & PRINT_KV_PAIR) { + if (printflags & PRINT_LINE) + printf("\n "); + putchar('['); + } + quotedzputs(p->node.nam, stdout); + if (printflags & PRINT_KV_PAIR) + printf("]="); + + printparamvalue(p, printflags); + } +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/parse.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/parse.c new file mode 100644 index 00000000..83383f10 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/parse.c @@ -0,0 +1,3977 @@ +/* + * parse.c - parser + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "parse.pro" + +/* != 0 if we are about to read a command word */ + +/**/ +mod_export int incmdpos; + +/**/ +int aliasspaceflag; + +/* != 0 if we are in the middle of a [[ ... ]] */ + +/**/ +mod_export int incond; + +/* != 0 if we are after a redirection (for ctxtlex only) */ + +/**/ +mod_export int inredir; + +/* + * 1 if we are about to read a case pattern + * -1 if we are not quite sure + * 0 otherwise + */ + +/**/ +int incasepat; + +/* != 0 if we just read a newline */ + +/**/ +int isnewlin; + +/* != 0 if we are after a for keyword */ + +/**/ +int infor; + +/* != 0 if we are after a repeat keyword; if it's nonzero it's a 1-based index + * of the current token from the last-seen command position */ + +/**/ +int inrepeat_; /* trailing underscore because of name clash with Zle/zle_vi.c */ + +/* != 0 if parsing arguments of typeset etc. */ + +/**/ +mod_export int intypeset; + +/* list of here-documents */ + +/**/ +struct heredocs *hdocs; + + +#define YYERROR(O) { tok = LEXERR; ecused = (O); return 0; } +#define YYERRORV(O) { tok = LEXERR; ecused = (O); return; } +#define COND_ERROR(X,Y) \ + do { \ + zwarn(X,Y); \ + herrflush(); \ + if (noerrs != 2) \ + errflag |= ERRFLAG_ERROR; \ + YYERROR(ecused) \ + } while(0) + + +/* + * Word code. + * + * The parser now produces word code, reducing memory consumption compared + * to the nested structs we had before. + * + * Word code layout: + * + * WC_END + * - end of program code + * + * WC_LIST + * - data contains type (sync, ...) + * - followed by code for this list + * - if not (type & Z_END), followed by next WC_LIST + * + * WC_SUBLIST + * - data contains type (&&, ||, END) and flags (coprog, not) + * - followed by code for sublist + * - if not (type == END), followed by next WC_SUBLIST + * + * WC_PIPE + * - data contains type (end, mid) and LINENO + * - if not (type == END), followed by offset to next WC_PIPE + * - followed by command + * - if not (type == END), followed by next WC_PIPE + * + * WC_REDIR + * - must precede command-code (or WC_ASSIGN) + * - data contains type (<, >, ...) + * - followed by fd1 and name from struct redir + * - for the extended form {var}>... where the fd is assigned + * to var, there is an extra item to contain var + * + * WC_ASSIGN + * - data contains type (scalar, array) and number of array-elements + * - followed by name and value + * Note variant for WC_TYPESET assignments: WC_ASSIGN_INC indicates + * a name with no equals, not an =+ which isn't valid here. + * + * WC_SIMPLE + * - data contains the number of arguments (plus command) + * - followed by strings + * + * WC_TYPESET + * Variant of WC_SIMPLE used when TYPESET reserved word found. + * - data contains the number of string arguments (plus command) + * - followed by strings + * - followed by number of assignments + * - followed by assignments if non-zero number. + * + * WC_SUBSH + * - data unused + * - followed by list + * + * WC_CURSH + * - data unused + * - followed by list + * + * WC_TIMED + * - data contains type (followed by pipe or not) + * - if (type == PIPE), followed by pipe + * + * WC_FUNCDEF + * - data contains offset to after body + * - followed by number of names + * - followed by names + * - followed by offset to first string + * - followed by length of string table + * - followed by number of patterns for body + * - followed by codes for body + * - followed by strings for body + * + * WC_FOR + * - data contains type (list, ...) and offset to after body + * - if (type == COND), followed by init, cond, advance expressions + * - else if (type == PPARAM), followed by param name + * - else if (type == LIST), followed by param name, num strings, strings + * - followed by body + * + * WC_SELECT + * - data contains type (list, ...) and offset to after body + * - if (type == PPARAM), followed by param name + * - else if (type == LIST), followed by param name, num strings, strings + * - followed by body + * + * WC_WHILE + * - data contains type (while, until) and offset to after body + * - followed by condition + * - followed by body + * + * WC_REPEAT + * - data contains offset to after body + * - followed by number-string + * - followed by body + * + * WC_CASE + * - first CASE is always of type HEAD, data contains offset to esac + * - after that CASEs of type OR (;;), AND (;&) and TESTAND (;|), + * data is offset to next case + * - each OR/AND/TESTAND case is followed by pattern, pattern-number, list + * + * WC_IF + * - first IF is of type HEAD, data contains offset to fi + * - after that IFs of type IF, ELIF, ELSE, data is offset to next + * - each non-HEAD is followed by condition (only IF, ELIF) and body + * + * WC_COND + * - data contains type + * - if (type == AND/OR), data contains offset to after this one, + * followed by two CONDs + * - else if (type == NOT), followed by COND + * - else if (type == MOD), followed by name and strings + * - else if (type == MODI), followed by name, left, right + * - else if (type == STR[N]EQ), followed by left, right, pattern-number + * - else if (has two args) followed by left, right + * - else followed by string + * + * WC_ARITH + * - followed by string (there's only one) + * + * WC_AUTOFN + * - only used by the autoload builtin + * + * Lists and sublists may also be simplified, indicated by the presence + * of the Z_SIMPLE or WC_SUBLIST_SIMPLE flags. In this case they are only + * followed by a slot containing the line number, not by a WC_SUBLIST or + * WC_PIPE, respectively. The real advantage of simplified lists and + * sublists is that they can be executed faster, see exec.c. In the + * parser, the test if a list can be simplified is done quite simply + * by passing a int* around which gets set to non-zero if the thing + * just parsed is `cmplx', i.e. may need to be run by forking or + * some such. + * + * In each of the above, strings are encoded as one word code. For empty + * strings this is the bit pattern 11x, the lowest bit is non-zero if the + * string contains tokens and zero otherwise (this is true for the other + * ways to encode strings, too). For short strings (one to three + * characters), this is the marker 01x with the 24 bits above that + * containing the characters. Longer strings are encoded as the offset + * into the strs character array stored in the eprog struct shifted by + * two and ored with the bit pattern 0x. + * The ecstrcode() function that adds the code for a string uses a simple + * binary tree of strings already added so that long strings are encoded + * only once. + * + * Note also that in the eprog struct the pattern, code, and string + * arrays all point to the same memory block. + * + * + * To make things even faster in future versions, we could not only + * test if the strings contain tokens, but instead what kind of + * expansions need to be done on strings. In the execution code we + * could then use these flags for a specialized version of prefork() + * to avoid a lot of string parsing and some more string duplication. + */ + +/**/ +int eclen, ecused, ecnpats; +/**/ +Wordcode ecbuf; +/**/ +Eccstr ecstrs; +/**/ +int ecsoffs, ecssub, ecnfunc; + +#define EC_INIT_SIZE 256 +#define EC_DOUBLE_THRESHOLD 32768 +#define EC_INCREMENT 1024 + +/* save parse context */ + +/**/ +void +parse_context_save(struct parse_stack *ps, int toplevel) +{ + (void)toplevel; + + ps->incmdpos = incmdpos; + ps->aliasspaceflag = aliasspaceflag; + ps->incond = incond; + ps->inredir = inredir; + ps->incasepat = incasepat; + ps->isnewlin = isnewlin; + ps->infor = infor; + ps->inrepeat_ = inrepeat_; + ps->intypeset = intypeset; + + ps->hdocs = hdocs; + ps->eclen = eclen; + ps->ecused = ecused; + ps->ecnpats = ecnpats; + ps->ecbuf = ecbuf; + ps->ecstrs = ecstrs; + ps->ecsoffs = ecsoffs; + ps->ecssub = ecssub; + ps->ecnfunc = ecnfunc; + ecbuf = NULL; + hdocs = NULL; +} + +/* restore parse context */ + +/**/ +void +parse_context_restore(const struct parse_stack *ps, int toplevel) +{ + (void)toplevel; + + if (ecbuf) + zfree(ecbuf, eclen); + + incmdpos = ps->incmdpos; + aliasspaceflag = ps->aliasspaceflag; + incond = ps->incond; + inredir = ps->inredir; + incasepat = ps->incasepat; + isnewlin = ps->isnewlin; + infor = ps->infor; + inrepeat_ = ps->inrepeat_; + intypeset = ps->intypeset; + + hdocs = ps->hdocs; + eclen = ps->eclen; + ecused = ps->ecused; + ecnpats = ps->ecnpats; + ecbuf = ps->ecbuf; + ecstrs = ps->ecstrs; + ecsoffs = ps->ecsoffs; + ecssub = ps->ecssub; + ecnfunc = ps->ecnfunc; + + errflag &= ~ERRFLAG_ERROR; +} + +/* Adjust pointers in here-doc structs. */ + +static void +ecadjusthere(int p, int d) +{ + struct heredocs *h; + + for (h = hdocs; h; h = h->next) + if (h->pc >= p) + h->pc += d; +} + +/* Insert n free code-slots at position p. */ + +static void +ecispace(int p, int n) +{ + int m; + + if ((eclen - ecused) < n) { + int a = (eclen < EC_DOUBLE_THRESHOLD ? eclen : EC_INCREMENT); + + if (n > a) a = n; + + ecbuf = (Wordcode) zrealloc((char *) ecbuf, (eclen + a) * sizeof(wordcode)); + eclen += a; + } + if ((m = ecused - p) > 0) + memmove(ecbuf + p + n, ecbuf + p, m * sizeof(wordcode)); + ecused += n; + ecadjusthere(p, n); +} + +/* Add one wordcode. */ + +static int +ecadd(wordcode c) +{ + if ((eclen - ecused) < 1) { + int a = (eclen < EC_DOUBLE_THRESHOLD ? eclen : EC_INCREMENT); + + ecbuf = (Wordcode) zrealloc((char *) ecbuf, (eclen + a) * sizeof(wordcode)); + eclen += a; + } + ecbuf[ecused] = c; + + return ecused++; +} + +/* Delete a wordcode. */ + +static void +ecdel(int p) +{ + int n = ecused - p - 1; + + if (n > 0) + memmove(ecbuf + p, ecbuf + p + 1, n * sizeof(wordcode)); + ecused--; + ecadjusthere(p, -1); +} + +/* Build the wordcode for a string. */ + +static wordcode +ecstrcode(char *s) +{ + int l, t; + + unsigned val = hasher(s); + + if ((l = strlen(s) + 1) && l <= 4) { + t = has_token(s); + wordcode c = (t ? 3 : 2); + switch (l) { + case 4: c |= ((wordcode) STOUC(s[2])) << 19; + case 3: c |= ((wordcode) STOUC(s[1])) << 11; + case 2: c |= ((wordcode) STOUC(s[0])) << 3; break; + case 1: c = (t ? 7 : 6); break; + } + return c; + } else { + Eccstr p, *pp; + int cmp; + + for (pp = &ecstrs; (p = *pp); ) { + if (!(cmp = p->nfunc - ecnfunc) && !(cmp = (((signed)p->hashval) - ((signed)val))) && !(cmp = strcmp(p->str, s))) { + return p->offs; + } + pp = (cmp < 0 ? &(p->left) : &(p->right)); + } + + t = has_token(s); + + p = *pp = (Eccstr) zhalloc(sizeof(*p)); + p->left = p->right = 0; + p->offs = ((ecsoffs - ecssub) << 2) | (t ? 1 : 0); + p->aoffs = ecsoffs; + p->str = s; + p->nfunc = ecnfunc; + p->hashval = val; + ecsoffs += l; + + return p->offs; + } +} + +#define ecstr(S) ecadd(ecstrcode(S)) + +#define par_save_list(C) \ + do { \ + int eu = ecused; \ + par_list(C); \ + if (eu == ecused) ecadd(WCB_END()); \ + } while (0) +#define par_save_list1(C) \ + do { \ + int eu = ecused; \ + par_list1(C); \ + if (eu == ecused) ecadd(WCB_END()); \ + } while (0) + + +/**/ +mod_export void +init_parse_status(void) +{ + /* + * These variables are currently declared by the parser, so we + * initialise them here. Possibly they are more naturally declared + * by the lexical anaylser; however, as they are used for signalling + * between the two it's a bit ambiguous. We clear them when + * using the lexical analyser for strings as well as here. + */ + incasepat = incond = inredir = infor = intypeset = 0; + inrepeat_ = 0; + incmdpos = 1; +} + +/* Initialise wordcode buffer. */ + +/**/ +void +init_parse(void) +{ + queue_signals(); + + if (ecbuf) zfree(ecbuf, eclen); + + ecbuf = (Wordcode) zalloc((eclen = EC_INIT_SIZE) * sizeof(wordcode)); + ecused = 0; + ecstrs = NULL; + ecsoffs = ecnpats = 0; + ecssub = 0; + ecnfunc = 0; + + init_parse_status(); + + unqueue_signals(); +} + +/* Build eprog. */ + +/* careful: copy_ecstr is from arg1 to arg2, unlike memcpy */ + +static void +copy_ecstr(Eccstr s, char *p) +{ + while (s) { + memcpy(p + s->aoffs, s->str, strlen(s->str) + 1); + copy_ecstr(s->left, p); + s = s->right; + } +} + +static Eprog +bld_eprog(int heap) +{ + Eprog ret; + int l; + + queue_signals(); + + ecadd(WCB_END()); + + ret = heap ? (Eprog) zhalloc(sizeof(*ret)) : (Eprog) zalloc(sizeof(*ret)); + ret->len = ((ecnpats * sizeof(Patprog)) + + (ecused * sizeof(wordcode)) + + ecsoffs); + ret->npats = ecnpats; + ret->nref = heap ? -1 : 1; + ret->pats = heap ? (Patprog *) zhalloc(ret->len) : + (Patprog *) zshcalloc(ret->len); + ret->prog = (Wordcode) (ret->pats + ecnpats); + ret->strs = (char *) (ret->prog + ecused); + ret->shf = NULL; + ret->flags = heap ? EF_HEAP : EF_REAL; + ret->dump = NULL; + for (l = 0; l < ecnpats; l++) + ret->pats[l] = dummy_patprog1; + memcpy(ret->prog, ecbuf, ecused * sizeof(wordcode)); + copy_ecstr(ecstrs, ret->strs); + + zfree(ecbuf, eclen); + ecbuf = NULL; + + unqueue_signals(); + + return ret; +} + +/**/ +mod_export int +empty_eprog(Eprog p) +{ + return (!p || !p->prog || *p->prog == WCB_END()); +} + +static void +clear_hdocs(void) +{ + struct heredocs *p, *n; + + for (p = hdocs; p; p = n) { + n = p->next; + zfree(p, sizeof(struct heredocs)); + } + hdocs = NULL; +} + +/* + * event : ENDINPUT + * | SEPER + * | sublist [ SEPER | AMPER | AMPERBANG ] + * + * cmdsubst indicates our event is part of a command-style + * substitution terminated by the token indicationg, usual closing + * parenthesis. In other cases endtok is ENDINPUT. + */ + +/**/ +Eprog +parse_event(int endtok) +{ + tok = ENDINPUT; + incmdpos = 1; + aliasspaceflag = 0; + zshlex(); + init_parse(); + + if (!par_event(endtok)) { + clear_hdocs(); + return NULL; + } + if (endtok != ENDINPUT) { + /* don't need to build an eprog for this */ + return &dummy_eprog; + } + return bld_eprog(1); +} + +/**/ +int +par_event(int endtok) +{ + int r = 0, p, c = 0; + + while (tok == SEPER) { + if (isnewlin > 0 && endtok == ENDINPUT) + return 0; + zshlex(); + } + if (tok == ENDINPUT) + return 0; + if (tok == endtok) + return 1; + + p = ecadd(0); + + if (par_sublist(&c)) { + if (tok == ENDINPUT || tok == endtok) { + set_list_code(p, Z_SYNC, c); + r = 1; + } else if (tok == SEPER) { + set_list_code(p, Z_SYNC, c); + if (isnewlin <= 0 || endtok != ENDINPUT) + zshlex(); + r = 1; + } else if (tok == AMPER) { + set_list_code(p, Z_ASYNC, c); + zshlex(); + r = 1; + } else if (tok == AMPERBANG) { + set_list_code(p, (Z_ASYNC | Z_DISOWN), c); + zshlex(); + r = 1; + } + } + if (!r) { + tok = LEXERR; + if (errflag) { + yyerror(0); + ecused--; + return 0; + } + yyerror(1); + herrflush(); + if (noerrs != 2) + errflag |= ERRFLAG_ERROR; + ecused--; + return 0; + } else { + int oec = ecused; + + if (!par_event(endtok)) { + ecused = oec; + ecbuf[p] |= wc_bdata(Z_END); + return errflag ? 0 : 1; + } + } + return 1; +} + +/**/ +mod_export Eprog +parse_list(void) +{ + int c = 0; + + tok = ENDINPUT; + init_parse(); + zshlex(); + par_list(&c); + if (tok != ENDINPUT) { + clear_hdocs(); + tok = LEXERR; + yyerror(0); + return NULL; + } + return bld_eprog(1); +} + +/* + * This entry point is only used for bin_test, our attempt to + * provide compatibility with /bin/[ and /bin/test. Hence + * at this point condlex should always be set to testlex. + */ + +/**/ +mod_export Eprog +parse_cond(void) +{ + init_parse(); + + if (!par_cond()) { + clear_hdocs(); + return NULL; + } + return bld_eprog(1); +} + +/* This adds a list wordcode. The important bit about this is that it also + * tries to optimise this to a Z_SIMPLE list code. */ + +/**/ +static void +set_list_code(int p, int type, int cmplx) +{ + if (!cmplx && (type == Z_SYNC || type == (Z_SYNC | Z_END)) && + WC_SUBLIST_TYPE(ecbuf[p + 1]) == WC_SUBLIST_END) { + int ispipe = !(WC_SUBLIST_FLAGS(ecbuf[p + 1]) & WC_SUBLIST_SIMPLE); + ecbuf[p] = WCB_LIST((type | Z_SIMPLE), ecused - 2 - p); + ecdel(p + 1); + if (ispipe) + ecbuf[p + 1] = WC_PIPE_LINENO(ecbuf[p + 1]); + } else + ecbuf[p] = WCB_LIST(type, 0); +} + +/* The same for sublists. */ + +/**/ +static void +set_sublist_code(int p, int type, int flags, int skip, int cmplx) +{ + if (cmplx) + ecbuf[p] = WCB_SUBLIST(type, flags, skip); + else { + ecbuf[p] = WCB_SUBLIST(type, (flags | WC_SUBLIST_SIMPLE), skip); + ecbuf[p + 1] = WC_PIPE_LINENO(ecbuf[p + 1]); + } +} + +/* + * list : { SEPER } [ sublist [ { SEPER | AMPER | AMPERBANG } list ] ] + */ + +/**/ +static void +par_list(int *cmplx) +{ + int p, lp = -1, c; + + rec: + + while (tok == SEPER) + zshlex(); + + p = ecadd(0); + c = 0; + + if (par_sublist(&c)) { + *cmplx |= c; + if (tok == SEPER || tok == AMPER || tok == AMPERBANG) { + if (tok != SEPER) + *cmplx = 1; + set_list_code(p, ((tok == SEPER) ? Z_SYNC : + (tok == AMPER) ? Z_ASYNC : + (Z_ASYNC | Z_DISOWN)), c); + incmdpos = 1; + do { + zshlex(); + } while (tok == SEPER); + lp = p; + goto rec; + } else + set_list_code(p, (Z_SYNC | Z_END), c); + } else { + ecused--; + if (lp >= 0) + ecbuf[lp] |= wc_bdata(Z_END); + } +} + +/**/ +static void +par_list1(int *cmplx) +{ + int p = ecadd(0), c = 0; + + if (par_sublist(&c)) { + set_list_code(p, (Z_SYNC | Z_END), c); + *cmplx |= c; + } else + ecused--; +} + +/* + * sublist : sublist2 [ ( DBAR | DAMPER ) { SEPER } sublist ] + */ + +/**/ +static int +par_sublist(int *cmplx) +{ + int f, p, c = 0; + + p = ecadd(0); + + if ((f = par_sublist2(&c)) != -1) { + int e = ecused; + + *cmplx |= c; + if (tok == DBAR || tok == DAMPER) { + enum lextok qtok = tok; + int sl; + + cmdpush(tok == DBAR ? CS_CMDOR : CS_CMDAND); + zshlex(); + while (tok == SEPER) + zshlex(); + sl = par_sublist(cmplx); + set_sublist_code(p, (sl ? (qtok == DBAR ? + WC_SUBLIST_OR : WC_SUBLIST_AND) : + WC_SUBLIST_END), + f, (e - 1 - p), c); + cmdpop(); + } else { + if (tok == AMPER || tok == AMPERBANG) { + c = 1; + *cmplx |= c; + } + set_sublist_code(p, WC_SUBLIST_END, f, (e - 1 - p), c); + } + return 1; + } else { + ecused--; + return 0; + } +} + +/* + * sublist2 : [ COPROC | BANG ] pline + */ + +/**/ +static int +par_sublist2(int *cmplx) +{ + int f = 0; + + if (tok == COPROC) { + *cmplx = 1; + f |= WC_SUBLIST_COPROC; + zshlex(); + } else if (tok == BANG) { + *cmplx = 1; + f |= WC_SUBLIST_NOT; + zshlex(); + } + if (!par_pline(cmplx) && !f) + return -1; + + return f; +} + +/* + * pline : cmd [ ( BAR | BARAMP ) { SEPER } pline ] + */ + +/**/ +static int +par_pline(int *cmplx) +{ + int p; + zlong line = toklineno; + + p = ecadd(0); + + if (!par_cmd(cmplx, 0)) { + ecused--; + return 0; + } + if (tok == BAR) { + *cmplx = 1; + cmdpush(CS_PIPE); + zshlex(); + while (tok == SEPER) + zshlex(); + ecbuf[p] = WCB_PIPE(WC_PIPE_MID, (line >= 0 ? line + 1 : 0)); + ecispace(p + 1, 1); + ecbuf[p + 1] = ecused - 1 - p; + if (!par_pline(cmplx)) { + tok = LEXERR; + } + cmdpop(); + return 1; + } else if (tok == BARAMP) { + int r; + + for (r = p + 1; wc_code(ecbuf[r]) == WC_REDIR; + r += WC_REDIR_WORDS(ecbuf[r])); + + ecispace(r, 3); + ecbuf[r] = WCB_REDIR(REDIR_MERGEOUT); + ecbuf[r + 1] = 2; + ecbuf[r + 2] = ecstrcode("1"); + + *cmplx = 1; + cmdpush(CS_ERRPIPE); + zshlex(); + while (tok == SEPER) + zshlex(); + ecbuf[p] = WCB_PIPE(WC_PIPE_MID, (line >= 0 ? line + 1 : 0)); + ecispace(p + 1, 1); + ecbuf[p + 1] = ecused - 1 - p; + if (!par_pline(cmplx)) { + tok = LEXERR; + } + cmdpop(); + return 1; + } else { + ecbuf[p] = WCB_PIPE(WC_PIPE_END, (line >= 0 ? line + 1 : 0)); + return 1; + } +} + +/* + * cmd : { redir } ( for | case | if | while | repeat | + * subsh | funcdef | time | dinbrack | dinpar | simple ) { redir } + * + * zsh_construct is passed through to par_subsh(), q.v. + */ + +/**/ +static int +par_cmd(int *cmplx, int zsh_construct) +{ + int r, nr = 0; + + r = ecused; + + if (IS_REDIROP(tok)) { + *cmplx = 1; + while (IS_REDIROP(tok)) { + nr += par_redir(&r, NULL); + } + } + switch (tok) { + case FOR: + cmdpush(CS_FOR); + par_for(cmplx); + cmdpop(); + break; + case FOREACH: + cmdpush(CS_FOREACH); + par_for(cmplx); + cmdpop(); + break; + case SELECT: + *cmplx = 1; + cmdpush(CS_SELECT); + par_for(cmplx); + cmdpop(); + break; + case CASE: + cmdpush(CS_CASE); + par_case(cmplx); + cmdpop(); + break; + case IF: + par_if(cmplx); + break; + case WHILE: + cmdpush(CS_WHILE); + par_while(cmplx); + cmdpop(); + break; + case UNTIL: + cmdpush(CS_UNTIL); + par_while(cmplx); + cmdpop(); + break; + case REPEAT: + cmdpush(CS_REPEAT); + par_repeat(cmplx); + cmdpop(); + break; + case INPAR: + *cmplx = 1; + cmdpush(CS_SUBSH); + par_subsh(cmplx, zsh_construct); + cmdpop(); + break; + case INBRACE: + cmdpush(CS_CURSH); + par_subsh(cmplx, zsh_construct); + cmdpop(); + break; + case FUNC: + cmdpush(CS_FUNCDEF); + par_funcdef(cmplx); + cmdpop(); + break; + case DINBRACK: + cmdpush(CS_COND); + par_dinbrack(); + cmdpop(); + break; + case DINPAR: + ecadd(WCB_ARITH()); + ecstr(tokstr); + zshlex(); + break; + case TIME: + { + static int inpartime = 0; + + if (!inpartime) { + *cmplx = 1; + inpartime = 1; + par_time(); + inpartime = 0; + break; + } + } + tok = STRING; + /* fall through */ + default: + { + int sr; + + if (!(sr = par_simple(cmplx, nr))) { + if (!nr) + return 0; + } else { + /* Take account of redirections */ + if (sr > 1) { + *cmplx = 1; + r += sr - 1; + } + } + } + break; + } + if (IS_REDIROP(tok)) { + *cmplx = 1; + while (IS_REDIROP(tok)) + (void)par_redir(&r, NULL); + } + incmdpos = 1; + incasepat = 0; + incond = 0; + intypeset = 0; + return 1; +} + +/* + * for : ( FOR DINPAR expr SEMI expr SEMI expr DOUTPAR | + * ( FOR[EACH] | SELECT ) name ( "in" wordlist | INPAR wordlist OUTPAR ) ) + * { SEPER } ( DO list DONE | INBRACE list OUTBRACE | list ZEND | list1 ) + */ + +/**/ +static void +par_for(int *cmplx) +{ + int oecused = ecused, csh = (tok == FOREACH), p, sel = (tok == SELECT); + int type; + + p = ecadd(0); + + incmdpos = 0; + infor = tok == FOR ? 2 : 0; + zshlex(); + if (tok == DINPAR) { + zshlex(); + if (tok != DINPAR) + YYERRORV(oecused); + ecstr(tokstr); + zshlex(); + if (tok != DINPAR) + YYERRORV(oecused); + ecstr(tokstr); + zshlex(); + if (tok != DOUTPAR) + YYERRORV(oecused); + ecstr(tokstr); + infor = 0; + incmdpos = 1; + zshlex(); + type = WC_FOR_COND; + } else { + int np = 0, n, posix_in, ona = noaliases, onc = nocorrect; + infor = 0; + if (tok != STRING || !isident(tokstr)) + YYERRORV(oecused); + if (!sel) + np = ecadd(0); + n = 0; + incmdpos = 1; + noaliases = nocorrect = 1; + for (;;) { + n++; + ecstr(tokstr); + zshlex(); + if (tok != STRING || !strcmp(tokstr, "in") || sel) + break; + if (!isident(tokstr) || errflag) + { + noaliases = ona; + nocorrect = onc; + YYERRORV(oecused); + } + } + noaliases = ona; + nocorrect = onc; + if (!sel) + ecbuf[np] = n; + posix_in = isnewlin; + while (isnewlin) + zshlex(); + if (tok == STRING && !strcmp(tokstr, "in")) { + incmdpos = 0; + zshlex(); + np = ecadd(0); + n = par_wordlist(); + if (tok != SEPER) + YYERRORV(oecused); + ecbuf[np] = n; + type = (sel ? WC_SELECT_LIST : WC_FOR_LIST); + } else if (!posix_in && tok == INPAR) { + incmdpos = 0; + zshlex(); + np = ecadd(0); + n = par_nl_wordlist(); + if (tok != OUTPAR) + YYERRORV(oecused); + ecbuf[np] = n; + incmdpos = 1; + zshlex(); + type = (sel ? WC_SELECT_LIST : WC_FOR_LIST); + } else + type = (sel ? WC_SELECT_PPARAM : WC_FOR_PPARAM); + } + incmdpos = 1; + while (tok == SEPER) + zshlex(); + if (tok == DOLOOP) { + zshlex(); + par_save_list(cmplx); + if (tok != DONE) + YYERRORV(oecused); + incmdpos = 0; + zshlex(); + } else if (tok == INBRACE) { + zshlex(); + par_save_list(cmplx); + if (tok != OUTBRACE) + YYERRORV(oecused); + incmdpos = 0; + zshlex(); + } else if (csh || isset(CSHJUNKIELOOPS)) { + par_save_list(cmplx); + if (tok != ZEND) + YYERRORV(oecused); + incmdpos = 0; + zshlex(); + } else if (unset(SHORTLOOPS)) { + YYERRORV(oecused); + } else + par_save_list1(cmplx); + + ecbuf[p] = (sel ? + WCB_SELECT(type, ecused - 1 - p) : + WCB_FOR(type, ecused - 1 - p)); +} + +/* + * case : CASE STRING { SEPER } ( "in" | INBRACE ) + { { SEPER } STRING { BAR STRING } OUTPAR + list [ DSEMI | SEMIAMP | SEMIBAR ] } + { SEPER } ( "esac" | OUTBRACE ) + */ + +/**/ +static void +par_case(int *cmplx) +{ + int oecused = ecused, brflag, p, pp, palts, type, nalts; + int ona, onc; + + p = ecadd(0); + + incmdpos = 0; + zshlex(); + if (tok != STRING) + YYERRORV(oecused); + ecstr(tokstr); + + incmdpos = 1; + ona = noaliases; + onc = nocorrect; + noaliases = nocorrect = 1; + zshlex(); + while (tok == SEPER) + zshlex(); + if (!(tok == STRING && !strcmp(tokstr, "in")) && tok != INBRACE) + { + noaliases = ona; + nocorrect = onc; + YYERRORV(oecused); + } + brflag = (tok == INBRACE); + incasepat = 1; + incmdpos = 0; + noaliases = ona; + nocorrect = onc; + zshlex(); + + for (;;) { + char *str; + int skip_zshlex; + + while (tok == SEPER) + zshlex(); + if (tok == OUTBRACE) + break; + if (tok == INPAR) + zshlex(); + if (tok == BAR) { + str = dupstring(""); + skip_zshlex = 1; + } else { + if (tok != STRING) + YYERRORV(oecused); + if (!strcmp(tokstr, "esac")) + break; + str = dupstring(tokstr); + skip_zshlex = 0; + } + type = WC_CASE_OR; + pp = ecadd(0); + palts = ecadd(0); + nalts = 0; + /* + * Hack here. + * + * [Pause for astonished hubbub to subside.] + * + * The next token we get may be + * - ")" or "|" if we're looking at an honest-to-god + * "case" pattern, either because there's no opening + * parenthesis, or because SH_GLOB is set and we + * managed to grab an initial "(" to mark the start + * of the case pattern. + * - Something else --- we don't care what --- because + * we're parsing a complete "(...)" as a complete + * zsh pattern. In that case, we treat this as a + * single instance of a case pattern but we pretend + * we're doing proper case parsing --- in which the + * parentheses and bar are in different words from + * the string, so may be separated by whitespace. + * So we quietly massage the whitespace and hope + * no one noticed. This is horrible, but it's + * unfortunately too difficult to combine traditional + * zsh patterns with a properly parsed case pattern + * without generating incompatibilities which aren't + * all that popular (I've discovered). + * - We can also end up with something other than ")" or "|" + * just because we're looking at garbage. + * + * Because of the second case, what happens next might + * be the start of the command after the pattern, so we + * need to treat it as in command position. Luckily + * this doesn't affect our ability to match a | or ) as + * these are valid on command lines. + */ + incasepat = -1; + incmdpos = 1; + if (!skip_zshlex) + zshlex(); + for (;;) { + if (tok == OUTPAR) { + ecstr(str); + ecadd(ecnpats++); + nalts++; + + incasepat = 0; + incmdpos = 1; + zshlex(); + break; + } else if (tok == BAR) { + ecstr(str); + ecadd(ecnpats++); + nalts++; + + incasepat = 1; + incmdpos = 0; + } else { + if (!nalts && str[0] == Inpar) { + int pct = 0, sl; + char *s; + + for (s = str; *s; s++) { + if (*s == Inpar) + pct++; + if (!pct) + break; + if (pct == 1) { + if (*s == Bar || *s == Inpar) + while (iblank(s[1])) + chuck(s+1); + if (*s == Bar || *s == Outpar) + while (iblank(s[-1]) && + (s < str + 1 || s[-2] != Meta)) + chuck(--s); + } + if (*s == Outpar) + pct--; + } + if (*s || pct || s == str) + YYERRORV(oecused); + /* Simplify pattern by removing surrounding (...) */ + sl = strlen(str); + DPUTS(*str != Inpar || str[sl - 1] != Outpar, + "BUG: strange case pattern"); + str[sl - 1] = '\0'; + chuck(str); + ecstr(str); + ecadd(ecnpats++); + nalts++; + break; + } + YYERRORV(oecused); + } + + zshlex(); + switch (tok) { + case STRING: + /* Normal case */ + str = dupstring(tokstr); + zshlex(); + break; + + case OUTPAR: + case BAR: + /* Empty string */ + str = dupstring(""); + break; + + default: + /* Oops. */ + YYERRORV(oecused); + break; + } + } + incasepat = 0; + par_save_list(cmplx); + if (tok == SEMIAMP) + type = WC_CASE_AND; + else if (tok == SEMIBAR) + type = WC_CASE_TESTAND; + ecbuf[pp] = WCB_CASE(type, ecused - 1 - pp); + ecbuf[palts] = nalts; + if ((tok == ESAC && !brflag) || (tok == OUTBRACE && brflag)) + break; + if (tok != DSEMI && tok != SEMIAMP && tok != SEMIBAR) + YYERRORV(oecused); + incasepat = 1; + incmdpos = 0; + zshlex(); + } + incmdpos = 1; + incasepat = 0; + zshlex(); + + ecbuf[p] = WCB_CASE(WC_CASE_HEAD, ecused - 1 - p); +} + +/* + * if : { ( IF | ELIF ) { SEPER } ( INPAR list OUTPAR | list ) + { SEPER } ( THEN list | INBRACE list OUTBRACE | list1 ) } + [ FI | ELSE list FI | ELSE { SEPER } INBRACE list OUTBRACE ] + (you get the idea...?) + */ + +/**/ +static void +par_if(int *cmplx) +{ + int oecused = ecused, p, pp, type, usebrace = 0; + enum lextok xtok; + unsigned char nc; + + p = ecadd(0); + + for (;;) { + xtok = tok; + cmdpush(xtok == IF ? CS_IF : CS_ELIF); + if (xtok == FI) { + incmdpos = 0; + zshlex(); + break; + } + zshlex(); + if (xtok == ELSE) + break; + while (tok == SEPER) + zshlex(); + if (!(xtok == IF || xtok == ELIF)) { + cmdpop(); + YYERRORV(oecused); + } + pp = ecadd(0); + type = (xtok == IF ? WC_IF_IF : WC_IF_ELIF); + par_save_list(cmplx); + incmdpos = 1; + if (tok == ENDINPUT) { + cmdpop(); + YYERRORV(oecused); + } + while (tok == SEPER) + zshlex(); + xtok = FI; + nc = cmdstack[cmdsp - 1] == CS_IF ? CS_IFTHEN : CS_ELIFTHEN; + if (tok == THEN) { + usebrace = 0; + cmdpop(); + cmdpush(nc); + zshlex(); + par_save_list(cmplx); + ecbuf[pp] = WCB_IF(type, ecused - 1 - pp); + incmdpos = 1; + cmdpop(); + } else if (tok == INBRACE) { + usebrace = 1; + cmdpop(); + cmdpush(nc); + zshlex(); + par_save_list(cmplx); + if (tok != OUTBRACE) { + cmdpop(); + YYERRORV(oecused); + } + ecbuf[pp] = WCB_IF(type, ecused - 1 - pp); + /* command word (else) allowed to follow immediately */ + zshlex(); + incmdpos = 1; + if (tok == SEPER) + break; + cmdpop(); + } else if (unset(SHORTLOOPS)) { + cmdpop(); + YYERRORV(oecused); + } else { + cmdpop(); + cmdpush(nc); + par_save_list1(cmplx); + ecbuf[pp] = WCB_IF(type, ecused - 1 - pp); + incmdpos = 1; + break; + } + } + cmdpop(); + if (xtok == ELSE || tok == ELSE) { + pp = ecadd(0); + cmdpush(CS_ELSE); + while (tok == SEPER) + zshlex(); + if (tok == INBRACE && usebrace) { + zshlex(); + par_save_list(cmplx); + if (tok != OUTBRACE) { + cmdpop(); + YYERRORV(oecused); + } + } else { + par_save_list(cmplx); + if (tok != FI) { + cmdpop(); + YYERRORV(oecused); + } + } + incmdpos = 0; + ecbuf[pp] = WCB_IF(WC_IF_ELSE, ecused - 1 - pp); + zshlex(); + cmdpop(); + } + ecbuf[p] = WCB_IF(WC_IF_HEAD, ecused - 1 - p); +} + +/* + * while : ( WHILE | UNTIL ) ( INPAR list OUTPAR | list ) { SEPER } + ( DO list DONE | INBRACE list OUTBRACE | list ZEND ) + */ + +/**/ +static void +par_while(int *cmplx) +{ + int oecused = ecused, p; + int type = (tok == UNTIL ? WC_WHILE_UNTIL : WC_WHILE_WHILE); + + p = ecadd(0); + zshlex(); + par_save_list(cmplx); + incmdpos = 1; + while (tok == SEPER) + zshlex(); + if (tok == DOLOOP) { + zshlex(); + par_save_list(cmplx); + if (tok != DONE) + YYERRORV(oecused); + incmdpos = 0; + zshlex(); + } else if (tok == INBRACE) { + zshlex(); + par_save_list(cmplx); + if (tok != OUTBRACE) + YYERRORV(oecused); + incmdpos = 0; + zshlex(); + } else if (isset(CSHJUNKIELOOPS)) { + par_save_list(cmplx); + if (tok != ZEND) + YYERRORV(oecused); + zshlex(); + } else if (unset(SHORTLOOPS)) { + YYERRORV(oecused); + } else + par_save_list1(cmplx); + + ecbuf[p] = WCB_WHILE(type, ecused - 1 - p); +} + +/* + * repeat : REPEAT STRING { SEPER } ( DO list DONE | list1 ) + */ + +/**/ +static void +par_repeat(int *cmplx) +{ + /* ### what to do about inrepeat_ here? */ + int oecused = ecused, p; + + p = ecadd(0); + + incmdpos = 0; + zshlex(); + if (tok != STRING) + YYERRORV(oecused); + ecstr(tokstr); + incmdpos = 1; + zshlex(); + while (tok == SEPER) + zshlex(); + if (tok == DOLOOP) { + zshlex(); + par_save_list(cmplx); + if (tok != DONE) + YYERRORV(oecused); + incmdpos = 0; + zshlex(); + } else if (tok == INBRACE) { + zshlex(); + par_save_list(cmplx); + if (tok != OUTBRACE) + YYERRORV(oecused); + incmdpos = 0; + zshlex(); + } else if (isset(CSHJUNKIELOOPS)) { + par_save_list(cmplx); + if (tok != ZEND) + YYERRORV(oecused); + zshlex(); + } else if (unset(SHORTLOOPS)) { + YYERRORV(oecused); + } else + par_save_list1(cmplx); + + ecbuf[p] = WCB_REPEAT(ecused - 1 - p); +} + +/* + * subsh : INPAR list OUTPAR | + * INBRACE list OUTBRACE [ "always" INBRACE list OUTBRACE ] + * + * With zsh_construct non-zero, we're doing a zsh special in which + * the following token is not considered in command position. This + * is used for arguments of anonymous functions. + */ + +/**/ +static void +par_subsh(int *cmplx, int zsh_construct) +{ + enum lextok otok = tok; + int oecused = ecused, p, pp; + + p = ecadd(0); + /* Extra word only needed for always block */ + pp = ecadd(0); + zshlex(); + par_list(cmplx); + ecadd(WCB_END()); + if (tok != ((otok == INPAR) ? OUTPAR : OUTBRACE)) + YYERRORV(oecused); + incmdpos = !zsh_construct; + zshlex(); + + /* Optional always block. No intervening SEPERs allowed. */ + if (otok == INBRACE && tok == STRING && !strcmp(tokstr, "always")) { + ecbuf[pp] = WCB_TRY(ecused - 1 - pp); + incmdpos = 1; + do { + zshlex(); + } while (tok == SEPER); + + if (tok != INBRACE) + YYERRORV(oecused); + cmdpop(); + cmdpush(CS_ALWAYS); + + zshlex(); + par_save_list(cmplx); + while (tok == SEPER) + zshlex(); + + incmdpos = 1; + + if (tok != OUTBRACE) + YYERRORV(oecused); + zshlex(); + ecbuf[p] = WCB_TRY(ecused - 1 - p); + } else { + ecbuf[p] = (otok == INPAR ? WCB_SUBSH(ecused - 1 - p) : + WCB_CURSH(ecused - 1 - p)); + } +} + +/* + * funcdef : FUNCTION wordlist [ INOUTPAR ] { SEPER } + * ( list1 | INBRACE list OUTBRACE ) + */ + +/**/ +static void +par_funcdef(int *cmplx) +{ + int oecused = ecused, num = 0, onp, p, c = 0; + int so, oecssub = ecssub; + zlong oldlineno = lineno; + + lineno = 0; + nocorrect = 1; + incmdpos = 0; + zshlex(); + + p = ecadd(0); + ecadd(0); + + while (tok == STRING) { + if ((*tokstr == Inbrace || *tokstr == '{') && + !tokstr[1]) { + tok = INBRACE; + break; + } + ecstr(tokstr); + num++; + zshlex(); + } + ecadd(0); + ecadd(0); + ecadd(0); + + nocorrect = 0; + incmdpos = 1; + if (tok == INOUTPAR) + zshlex(); + while (tok == SEPER) + zshlex(); + + ecnfunc++; + ecssub = so = ecsoffs; + onp = ecnpats; + ecnpats = 0; + + if (tok == INBRACE) { + zshlex(); + par_list(&c); + if (tok != OUTBRACE) { + lineno += oldlineno; + ecnpats = onp; + ecssub = oecssub; + YYERRORV(oecused); + } + if (num == 0) { + /* Anonymous function, possibly with arguments */ + incmdpos = 0; + } + zshlex(); + } else if (unset(SHORTLOOPS)) { + lineno += oldlineno; + ecnpats = onp; + ecssub = oecssub; + YYERRORV(oecused); + } else + par_list1(&c); + + ecadd(WCB_END()); + ecbuf[p + num + 2] = so - oecssub; + ecbuf[p + num + 3] = ecsoffs - so; + ecbuf[p + num + 4] = ecnpats; + ecbuf[p + 1] = num; + + ecnpats = onp; + ecssub = oecssub; + ecnfunc++; + + ecbuf[p] = WCB_FUNCDEF(ecused - 1 - p); + + if (num == 0) { + /* Unnamed function */ + int parg = ecadd(0); + ecadd(0); + while (tok == STRING) { + ecstr(tokstr); + num++; + zshlex(); + } + if (num > 0) + *cmplx = 1; + ecbuf[parg] = ecused - parg; /*?*/ + ecbuf[parg+1] = num; + } + lineno += oldlineno; +} + +/* + * time : TIME sublist2 + */ + +/**/ +static void +par_time(void) +{ + int p, f, c = 0; + + zshlex(); + + p = ecadd(0); + ecadd(0); + if ((f = par_sublist2(&c)) < 0) { + ecused--; + ecbuf[p] = WCB_TIMED(WC_TIMED_EMPTY); + } else { + ecbuf[p] = WCB_TIMED(WC_TIMED_PIPE); + set_sublist_code(p + 1, WC_SUBLIST_END, f, ecused - 2 - p, c); + } +} + +/* + * dinbrack : DINBRACK cond DOUTBRACK + */ + +/**/ +static void +par_dinbrack(void) +{ + int oecused = ecused; + + incond = 1; + incmdpos = 0; + zshlex(); + par_cond(); + if (tok != DOUTBRACK) + YYERRORV(oecused); + incond = 0; + incmdpos = 1; + zshlex(); +} + +/* + * simple : { COMMAND | EXEC | NOGLOB | NOCORRECT | DASH } + { STRING | ENVSTRING | ENVARRAY wordlist OUTPAR | redir } + [ INOUTPAR { SEPER } ( list1 | INBRACE list OUTBRACE ) ] + * + * Returns 0 if no code, else 1 plus the number of code words + * used up by redirections. + */ + +/**/ +static int +par_simple(int *cmplx, int nr) +{ + int oecused = ecused, isnull = 1, r, argc = 0, p, isfunc = 0, sr = 0; + int c = *cmplx, nrediradd, assignments = 0, ppost = 0, is_typeset = 0; + char *hasalias = input_hasalias(); + wordcode postassigns = 0; + + r = ecused; + for (;;) { + if (tok == NOCORRECT) { + *cmplx = c = 1; + nocorrect = 1; + } else if (tok == ENVSTRING) { + char *ptr, *name, *str; + + name = tokstr; + for (ptr = tokstr; + *ptr && *ptr != Inbrack && *ptr != '=' && *ptr != '+'; + ptr++); + if (*ptr == Inbrack) skipparens(Inbrack, Outbrack, &ptr); + if (*ptr == '+') { + *ptr++ = '\0'; + ecadd(WCB_ASSIGN(WC_ASSIGN_SCALAR, WC_ASSIGN_INC, 0)); + } else + ecadd(WCB_ASSIGN(WC_ASSIGN_SCALAR, WC_ASSIGN_NEW, 0)); + + if (*ptr == '=') { + *ptr = '\0'; + str = ptr + 1; + } else + equalsplit(tokstr, &str); + for (ptr = str; *ptr; ptr++) { + /* + * We can't treat this as "simple" if it contains + * expansions that require process subsitution, since then + * we need process handling. + */ + if (ptr[1] == Inpar && + (*ptr == Equals || *ptr == Inang || *ptr == OutangProc)) { + *cmplx = 1; + break; + } + } + ecstr(name); + ecstr(str); + isnull = 0; + assignments = 1; + } else if (tok == ENVARRAY) { + int oldcmdpos = incmdpos, n, type2; + + /* + * We consider array setting cmplx because it can + * contain process substitutions, which need a valid job. + */ + *cmplx = c = 1; + p = ecadd(0); + incmdpos = 0; + if ((type2 = strlen(tokstr) - 1) && tokstr[type2] == '+') { + tokstr[type2] = '\0'; + type2 = WC_ASSIGN_INC; + } else + type2 = WC_ASSIGN_NEW; + ecstr(tokstr); + cmdpush(CS_ARRAY); + zshlex(); + n = par_nl_wordlist(); + ecbuf[p] = WCB_ASSIGN(WC_ASSIGN_ARRAY, type2, n); + cmdpop(); + if (tok != OUTPAR) + YYERROR(oecused); + incmdpos = oldcmdpos; + isnull = 0; + assignments = 1; + } else if (IS_REDIROP(tok)) { + *cmplx = c = 1; + nr += par_redir(&r, NULL); + continue; + } else + break; + zshlex(); + if (!hasalias) + hasalias = input_hasalias(); + } + if (tok == AMPER || tok == AMPERBANG) + YYERROR(oecused); + + p = ecadd(WCB_SIMPLE(0)); + + for (;;) { + if (tok == STRING || tok == TYPESET) { + int redir_var = 0; + + *cmplx = 1; + incmdpos = 0; + + if (tok == TYPESET) + intypeset = is_typeset = 1; + + if (!isset(IGNOREBRACES) && *tokstr == Inbrace) + { + /* Look for redirs of the form {var}>file etc. */ + char *eptr = tokstr + strlen(tokstr) - 1; + char *ptr = eptr; + + if (*ptr == Outbrace && ptr > tokstr + 1) + { + if (itype_end(tokstr+1, IIDENT, 0) >= ptr) + { + char *toksave = tokstr; + char *idstring = dupstrpfx(tokstr+1, eptr-tokstr-1); + redir_var = 1; + zshlex(); + if (!hasalias) + hasalias = input_hasalias(); + + if (IS_REDIROP(tok) && tokfd == -1) + { + *cmplx = c = 1; + nrediradd = par_redir(&r, idstring); + p += nrediradd; + sr += nrediradd; + } + else + { + ecstr(toksave); + argc++; + } + } + } + } + + if (!redir_var) + { + if (postassigns) { + /* + * We're in the variable part of a typeset, + * but this doesn't have an assignment. + * We'll parse it as if it does, but mark + * it specially with WC_ASSIGN_INC. + */ + postassigns++; + ecadd(WCB_ASSIGN(WC_ASSIGN_SCALAR, WC_ASSIGN_INC, 0)); + ecstr(tokstr); + ecstr(""); /* TBD can possibly optimise out */ + } else { + ecstr(tokstr); + argc++; + } + zshlex(); + if (!hasalias) + hasalias = input_hasalias(); + } + } else if (IS_REDIROP(tok)) { + *cmplx = c = 1; + nrediradd = par_redir(&r, NULL); + p += nrediradd; + if (ppost) + ppost += nrediradd; + sr += nrediradd; + } else if (tok == ENVSTRING) { + char *ptr, *name, *str; + + if (!postassigns++) + ppost = ecadd(0); + + name = tokstr; + for (ptr = tokstr; *ptr && *ptr != Inbrack && *ptr != '=' && *ptr != '+'; + ptr++); + if (*ptr == Inbrack) skipparens(Inbrack, Outbrack, &ptr); + ecadd(WCB_ASSIGN(WC_ASSIGN_SCALAR, WC_ASSIGN_NEW, 0)); + + if (*ptr == '=') { + *ptr = '\0'; + str = ptr + 1; + } else + equalsplit(tokstr, &str); + ecstr(name); + ecstr(str); + zshlex(); + if (!hasalias) + hasalias = input_hasalias(); + } else if (tok == ENVARRAY) { + int n, parr; + + if (!postassigns++) + ppost = ecadd(0); + + parr = ecadd(0); + ecstr(tokstr); + cmdpush(CS_ARRAY); + /* + * Careful here: this must be the typeset case, + * but we need to tell the lexer not to look + * for assignments until we've finished the + * present one. + */ + intypeset = 0; + zshlex(); + n = par_nl_wordlist(); + ecbuf[parr] = WCB_ASSIGN(WC_ASSIGN_ARRAY, WC_ASSIGN_NEW, n); + cmdpop(); + intypeset = 1; + if (tok != OUTPAR) + YYERROR(oecused); + zshlex(); + } else if (tok == INOUTPAR) { + zlong oldlineno = lineno; + int onp, so, oecssub = ecssub; + + /* Error if too many function definitions at once */ + if (!isset(MULTIFUNCDEF) && argc > 1) + YYERROR(oecused); + /* Error if preceding assignments */ + if (assignments || postassigns) + YYERROR(oecused); + if (hasalias && !isset(ALIASFUNCDEF) && argc && + hasalias != input_hasalias()) { + zwarn("defining function based on alias `%s'", hasalias); + YYERROR(oecused); + } + + *cmplx = c; + lineno = 0; + incmdpos = 1; + cmdpush(CS_FUNCDEF); + zshlex(); + while (tok == SEPER) + zshlex(); + + ecispace(p + 1, 1); + ecbuf[p + 1] = argc; + ecadd(0); + ecadd(0); + ecadd(0); + + ecnfunc++; + ecssub = so = ecsoffs; + onp = ecnpats; + ecnpats = 0; + + if (tok == INBRACE) { + int c = 0; + + zshlex(); + par_list(&c); + if (tok != OUTBRACE) { + cmdpop(); + lineno += oldlineno; + ecnpats = onp; + ecssub = oecssub; + YYERROR(oecused); + } + if (argc == 0) { + /* Anonymous function, possibly with arguments */ + incmdpos = 0; + } + zshlex(); + } else { + int ll, sl, c = 0; + + ll = ecadd(0); + sl = ecadd(0); + (void)ecadd(WCB_PIPE(WC_PIPE_END, 0)); + + if (!par_cmd(&c, argc == 0)) { + cmdpop(); + YYERROR(oecused); + } + if (argc == 0) { + /* + * Anonymous function, possibly with arguments. + * N.B. for cmplx structures in particular + * ( ... ) we rely on lower level code doing this + * to get the immediately following word (the + * first token after the ")" has already been + * read). + */ + incmdpos = 0; + } + + set_sublist_code(sl, WC_SUBLIST_END, 0, ecused - 1 - sl, c); + set_list_code(ll, (Z_SYNC | Z_END), c); + } + cmdpop(); + + ecadd(WCB_END()); + ecbuf[p + argc + 2] = so - oecssub; + ecbuf[p + argc + 3] = ecsoffs - so; + ecbuf[p + argc + 4] = ecnpats; + + ecnpats = onp; + ecssub = oecssub; + ecnfunc++; + + ecbuf[p] = WCB_FUNCDEF(ecused - 1 - p); + + if (argc == 0) { + /* Unnamed function */ + int parg = ecadd(0); + ecadd(0); + while (tok == STRING || IS_REDIROP(tok)) { + if (tok == STRING) + { + ecstr(tokstr); + argc++; + zshlex(); + } else { + *cmplx = c = 1; + nrediradd = par_redir(&r, NULL); + p += nrediradd; + if (ppost) + ppost += nrediradd; + sr += nrediradd; + parg += nrediradd; + } + } + if (argc > 0) + *cmplx = 1; + ecbuf[parg] = ecused - parg; /*?*/ + ecbuf[parg+1] = argc; + } + lineno += oldlineno; + + isfunc = 1; + isnull = 0; + break; + } else + break; + isnull = 0; + } + if (isnull && !(sr + nr)) { + ecused = p; + return 0; + } + incmdpos = 1; + intypeset = 0; + + if (!isfunc) { + if (is_typeset) { + ecbuf[p] = WCB_TYPESET(argc); + if (postassigns) + ecbuf[ppost] = postassigns; + else + ecadd(0); + } else + ecbuf[p] = WCB_SIMPLE(argc); + } + + return sr + 1; +} + +/* + * redir : ( OUTANG | ... | TRINANG ) STRING + * + * Return number of code words required for redirection + */ + +static int redirtab[TRINANG - OUTANG + 1] = { + REDIR_WRITE, + REDIR_WRITENOW, + REDIR_APP, + REDIR_APPNOW, + REDIR_READ, + REDIR_READWRITE, + REDIR_HEREDOC, + REDIR_HEREDOCDASH, + REDIR_MERGEIN, + REDIR_MERGEOUT, + REDIR_ERRWRITE, + REDIR_ERRWRITENOW, + REDIR_ERRAPP, + REDIR_ERRAPPNOW, + REDIR_HERESTR, +}; + +/**/ +static int +par_redir(int *rp, char *idstring) +{ + int r = *rp, type, fd1, oldcmdpos, oldnc, ncodes; + char *name; + + oldcmdpos = incmdpos; + incmdpos = 0; + oldnc = nocorrect; + if (tok != INANG && tok != INOUTANG) + nocorrect = 1; + type = redirtab[tok - OUTANG]; + fd1 = tokfd; + zshlex(); + if (tok != STRING && tok != ENVSTRING) + YYERROR(ecused); + incmdpos = oldcmdpos; + nocorrect = oldnc; + + /* assign default fd */ + if (fd1 == -1) + fd1 = IS_READFD(type) ? 0 : 1; + + name = tokstr; + + switch (type) { + case REDIR_HEREDOC: + case REDIR_HEREDOCDASH: { + /* <<[-] name */ + struct heredocs **hd; + int htype = type; + + /* + * Add two here for the string to remember the HERE + * terminator in raw and munged form. + */ + if (idstring) + { + type |= REDIR_VARID_MASK; + ncodes = 6; + } + else + ncodes = 5; + + /* If we ever to change the number of codes, we have to change + * the definition of WC_REDIR_WORDS. */ + ecispace(r, ncodes); + *rp = r + ncodes; + ecbuf[r] = WCB_REDIR(type | REDIR_FROM_HEREDOC_MASK); + ecbuf[r + 1] = fd1; + + /* + * r + 2: the HERE string we recover + * r + 3: the HERE document terminator, raw + * r + 4: the HERE document terminator, munged + */ + if (idstring) + ecbuf[r + 5] = ecstrcode(idstring); + + for (hd = &hdocs; *hd; hd = &(*hd)->next) + ; + *hd = zalloc(sizeof(struct heredocs)); + (*hd)->next = NULL; + (*hd)->type = htype; + (*hd)->pc = r; + (*hd)->str = tokstr; + + zshlex(); + return ncodes; + } + case REDIR_WRITE: + case REDIR_WRITENOW: + if (tokstr[0] == OutangProc && tokstr[1] == Inpar) + /* > >(...) */ + type = REDIR_OUTPIPE; + else if (tokstr[0] == Inang && tokstr[1] == Inpar) + YYERROR(ecused); + break; + case REDIR_READ: + if (tokstr[0] == Inang && tokstr[1] == Inpar) + /* < <(...) */ + type = REDIR_INPIPE; + else if (tokstr[0] == OutangProc && tokstr[1] == Inpar) + YYERROR(ecused); + break; + case REDIR_READWRITE: + if ((tokstr[0] == Inang || tokstr[0] == OutangProc) && + tokstr[1] == Inpar) + type = tokstr[0] == Inang ? REDIR_INPIPE : REDIR_OUTPIPE; + break; + } + zshlex(); + + /* If we ever to change the number of codes, we have to change + * the definition of WC_REDIR_WORDS. */ + if (idstring) + { + type |= REDIR_VARID_MASK; + ncodes = 4; + } + else + ncodes = 3; + + ecispace(r, ncodes); + *rp = r + ncodes; + ecbuf[r] = WCB_REDIR(type); + ecbuf[r + 1] = fd1; + ecbuf[r + 2] = ecstrcode(name); + if (idstring) + ecbuf[r + 3] = ecstrcode(idstring); + + return ncodes; +} + +/**/ +void +setheredoc(int pc, int type, char *str, char *termstr, char *munged_termstr) +{ + ecbuf[pc] = WCB_REDIR(type | REDIR_FROM_HEREDOC_MASK); + ecbuf[pc + 2] = ecstrcode(str); + ecbuf[pc + 3] = ecstrcode(termstr); + ecbuf[pc + 4] = ecstrcode(munged_termstr); +} + +/* + * wordlist : { STRING } + */ + +/**/ +static int +par_wordlist(void) +{ + int num = 0; + while (tok == STRING) { + ecstr(tokstr); + num++; + zshlex(); + } + return num; +} + +/* + * nl_wordlist : { STRING | SEPER } + */ + +/**/ +static int +par_nl_wordlist(void) +{ + int num = 0; + + while (tok == STRING || tok == SEPER) { + if (tok != SEPER) { + ecstr(tokstr); + num++; + } + zshlex(); + } + return num; +} + +/* + * condlex is zshlex for normal parsing, but is altered to allow + * the test builtin to use par_cond. + */ + +/**/ +void (*condlex) _((void)) = zshlex; + +/* + * cond : cond_1 { SEPER } [ DBAR { SEPER } cond ] + */ + +#define COND_SEP() (tok == SEPER && condlex != testlex && *zshlextext != ';') + +/**/ +static int +par_cond(void) +{ + int p = ecused, r; + + r = par_cond_1(); + while (COND_SEP()) + condlex(); + if (tok == DBAR) { + condlex(); + while (COND_SEP()) + condlex(); + ecispace(p, 1); + par_cond(); + ecbuf[p] = WCB_COND(COND_OR, ecused - 1 - p); + return 1; + } + return r; +} + +/* + * cond_1 : cond_2 { SEPER } [ DAMPER { SEPER } cond_1 ] + */ + +/**/ +static int +par_cond_1(void) +{ + int r, p = ecused; + + r = par_cond_2(); + while (COND_SEP()) + condlex(); + if (tok == DAMPER) { + condlex(); + while (COND_SEP()) + condlex(); + ecispace(p, 1); + par_cond_1(); + ecbuf[p] = WCB_COND(COND_AND, ecused - 1 - p); + return 1; + } + return r; +} + +/* + * Return 1 if condition matches. This also works for non-elided options. + * + * input is test string, may begin - or Dash. + * cond is condition following the -. + */ +static int check_cond(const char *input, const char *cond) +{ + if (!IS_DASH(input[0])) + return 0; + return !strcmp(input + 1, cond); +} + +/* + * cond_2 : BANG cond_2 + | INPAR { SEPER } cond_2 { SEPER } OUTPAR + | STRING STRING STRING + | STRING STRING + | STRING ( INANG | OUTANG ) STRING + */ + +/**/ +static int +par_cond_2(void) +{ + char *s1, *s2, *s3; + int dble = 0; + int n_testargs = (condlex == testlex) ? arrlen(testargs) + 1 : 0; + + if (n_testargs) { + /* See the description of test in POSIX 1003.2 */ + if (tok == NULLTOK) + /* no arguments: false */ + return par_cond_double(dupstring("-n"), dupstring("")); + if (n_testargs == 1) { + /* one argument: [ foo ] is equivalent to [ -n foo ] */ + s1 = tokstr; + condlex(); + /* ksh behavior: [ -t ] means [ -t 1 ]; bash disagrees */ + if (unset(POSIXBUILTINS) && check_cond(s1, "t")) + return par_cond_double(s1, dupstring("1")); + return par_cond_double(dupstring("-n"), s1); + } + if (n_testargs > 2) { + /* three arguments: if the second argument is a binary operator, * + * perform that binary test on the first and the third argument */ + if (!strcmp(*testargs, "=") || + !strcmp(*testargs, "==") || + !strcmp(*testargs, "!=") || + (IS_DASH(**testargs) && get_cond_num(*testargs + 1) >= 0)) { + s1 = tokstr; + condlex(); + s2 = tokstr; + condlex(); + s3 = tokstr; + condlex(); + return par_cond_triple(s1, s2, s3); + } + } + /* + * We fall through here on any non-numeric infix operator + * or any other time there are at least two arguments. + */ + } else + while (COND_SEP()) + condlex(); + if (tok == BANG) { + /* + * In "test" compatibility mode, "! -a ..." and "! -o ..." + * are treated as "[string] [and] ..." and "[string] [or] ...". + */ + if (!(n_testargs > 1 && (check_cond(*testargs, "a") || + check_cond(*testargs, "o")))) + { + condlex(); + ecadd(WCB_COND(COND_NOT, 0)); + return par_cond_2(); + } + } + if (tok == INPAR) { + int r; + + condlex(); + while (COND_SEP()) + condlex(); + r = par_cond(); + while (COND_SEP()) + condlex(); + if (tok != OUTPAR) + YYERROR(ecused); + condlex(); + return r; + } + s1 = tokstr; + dble = (s1 && IS_DASH(*s1) + && (!n_testargs + || strspn(s1+1, "abcdefghknoprstuvwxzLONGS") == 1) + && !s1[2]); + if (tok != STRING) { + /* Check first argument for [[ STRING ]] re-interpretation */ + if (s1 /* tok != DOUTBRACK && tok != DAMPER && tok != DBAR */ + && tok != LEXERR && (!dble || n_testargs)) { + do condlex(); while (COND_SEP()); + return par_cond_double(dupstring("-n"), s1); + } else + YYERROR(ecused); + } + condlex(); + if (n_testargs == 2 && tok != STRING && tokstr && IS_DASH(s1[0])) { + /* + * Something like "test -z" followed by a token. + * We'll turn the token into a string (we've also + * checked it does have a string representation). + */ + tok = STRING; + } else + while (COND_SEP()) + condlex(); + if (tok == INANG || tok == OUTANG) { + enum lextok xtok = tok; + do condlex(); while (COND_SEP()); + if (tok != STRING) + YYERROR(ecused); + s3 = tokstr; + do condlex(); while (COND_SEP()); + ecadd(WCB_COND((xtok == INANG ? COND_STRLT : COND_STRGTR), 0)); + ecstr(s1); + ecstr(s3); + return 1; + } + if (tok != STRING) { + /* + * Check second argument in case semantics e.g. [ = -a = ] + * mean we have to go back and fix up the first one + */ + if (tok != LEXERR) { + if (!dble || n_testargs) + return par_cond_double(dupstring("-n"), s1); + else + return par_cond_multi(s1, newlinklist()); + } else + YYERROR(ecused); + } + s2 = tokstr; + if (!n_testargs) + dble = (s2 && IS_DASH(*s2) && !s2[2]); + incond++; /* parentheses do globbing */ + do condlex(); while (COND_SEP()); + incond--; /* parentheses do grouping */ + if (tok == STRING && !dble) { + s3 = tokstr; + do condlex(); while (COND_SEP()); + if (tok == STRING) { + LinkList l = newlinklist(); + + addlinknode(l, s2); + addlinknode(l, s3); + + while (tok == STRING) { + addlinknode(l, tokstr); + do condlex(); while (COND_SEP()); + } + return par_cond_multi(s1, l); + } else + return par_cond_triple(s1, s2, s3); + } else + return par_cond_double(s1, s2); +} + +/**/ +static int +par_cond_double(char *a, char *b) +{ + if (!IS_DASH(a[0]) || !a[1]) + COND_ERROR("parse error: condition expected: %s", a); + else if (!a[2] && strspn(a+1, "abcdefgknoprstuvwxzhLONGS") == 1) { + ecadd(WCB_COND(a[1], 0)); + ecstr(b); + } else { + ecadd(WCB_COND(COND_MOD, 1)); + ecstr(a); + ecstr(b); + } + return 1; +} + +/**/ +static int +get_cond_num(char *tst) +{ + static char *condstrs[] = + { + "nt", "ot", "ef", "eq", "ne", "lt", "gt", "le", "ge", NULL + }; + int t0; + + for (t0 = 0; condstrs[t0]; t0++) + if (!strcmp(condstrs[t0], tst)) + return t0; + return -1; +} + +/**/ +static int +par_cond_triple(char *a, char *b, char *c) +{ + int t0; + + if ((b[0] == Equals || b[0] == '=') && !b[1]) { + ecadd(WCB_COND(COND_STREQ, 0)); + ecstr(a); + ecstr(c); + ecadd(ecnpats++); + } else if ((b[0] == Equals || b[0] == '=') && + (b[1] == Equals || b[1] == '=') && !b[2]) { + ecadd(WCB_COND(COND_STRDEQ, 0)); + ecstr(a); + ecstr(c); + ecadd(ecnpats++); + } else if (b[0] == '!' && (b[1] == Equals || b[1] == '=') && !b[2]) { + ecadd(WCB_COND(COND_STRNEQ, 0)); + ecstr(a); + ecstr(c); + ecadd(ecnpats++); + } else if ((b[0] == Equals || b[0] == '=') && + (b[1] == '~' || b[1] == Tilde) && !b[2]) { + /* We become an implicit COND_MODI but do not provide the first + * item, it's skipped */ + ecadd(WCB_COND(COND_REGEX, 0)); + ecstr(a); + ecstr(c); + } else if (IS_DASH(b[0])) { + if ((t0 = get_cond_num(b + 1)) > -1) { + ecadd(WCB_COND(t0 + COND_NT, 0)); + ecstr(a); + ecstr(c); + } else { + ecadd(WCB_COND(COND_MODI, 0)); + ecstr(b); + ecstr(a); + ecstr(c); + } + } else if (IS_DASH(a[0]) && a[1]) { + ecadd(WCB_COND(COND_MOD, 2)); + ecstr(a); + ecstr(b); + ecstr(c); + } else + COND_ERROR("condition expected: %s", b); + + return 1; +} + +/**/ +static int +par_cond_multi(char *a, LinkList l) +{ + if (!IS_DASH(a[0]) || !a[1]) + COND_ERROR("condition expected: %s", a); + else { + LinkNode n; + + ecadd(WCB_COND(COND_MOD, countlinknodes(l))); + ecstr(a); + for (n = firstnode(l); n; incnode(n)) + ecstr((char *) getdata(n)); + } + return 1; +} + +/**/ +static void +yyerror(int noerr) +{ + int t0; + char *t; + + if ((t = dupstring(zshlextext))) + untokenize(t); + + for (t0 = 0; t0 != 20; t0++) + if (!t || !t[t0] || t[t0] == '\n') + break; + if (!(histdone & HISTFLAG_NOEXEC) && !(errflag & ERRFLAG_INT)) { + if (t0 == 20) + zwarn("parse error near `%l...'", t, 20); + else if (t0) + zwarn("parse error near `%l'", t, t0); + else + zwarn("parse error"); + } + if (!noerr && noerrs != 2) + errflag |= ERRFLAG_ERROR; +} + +/* + * Duplicate a programme list, on the heap if heap is 1, else + * in permanent storage. + * + * Be careful in case p is the Eprog for a function which will + * later be autoloaded. The shf element of the returned Eprog + * must be set appropriately by the caller. (Normally we create + * the Eprog in this case by using mkautofn.) + */ + +/**/ +mod_export Eprog +dupeprog(Eprog p, int heap) +{ + Eprog r; + int i; + Patprog *pp; + + if (p == &dummy_eprog) + return p; + + r = (heap ? (Eprog) zhalloc(sizeof(*r)) : (Eprog) zalloc(sizeof(*r))); + r->flags = (heap ? EF_HEAP : EF_REAL) | (p->flags & EF_RUN); + r->dump = NULL; + r->len = p->len; + r->npats = p->npats; + /* + * If Eprog is on the heap, reference count is not valid. + * Otherwise, initialise reference count to 1 so that a freeeprog() + * will delete it if it is not in use. + */ + r->nref = heap ? -1 : 1; + pp = r->pats = (heap ? (Patprog *) hcalloc(r->len) : + (Patprog *) zshcalloc(r->len)); + r->prog = (Wordcode) (r->pats + r->npats); + r->strs = ((char *) r->prog) + (p->strs - ((char *) p->prog)); + memcpy(r->prog, p->prog, r->len - (p->npats * sizeof(Patprog))); + r->shf = NULL; + + for (i = r->npats; i--; pp++) + *pp = dummy_patprog1; + + return r; +} + + +/* + * Pair of functions to mark an Eprog as in use, and to delete it + * when it is no longer in use, by means of the reference count in + * then nref element. + * + * If nref is negative, the Eprog is on the heap and is never freed. + */ + +/* Increase the reference count of an Eprog so it won't be deleted. */ + +/**/ +mod_export void +useeprog(Eprog p) +{ + if (p && p != &dummy_eprog && p->nref >= 0) + p->nref++; +} + +/* Free an Eprog if we have finished with it */ + +/**/ +mod_export void +freeeprog(Eprog p) +{ + int i; + Patprog *pp; + + if (p && p != &dummy_eprog) { + /* paranoia */ + DPUTS(p->nref > 0 && (p->flags & EF_HEAP), "Heap EPROG has nref > 0"); + DPUTS(p->nref < 0 && !(p->flags & EF_HEAP), "Real EPROG has nref < 0"); + DPUTS(p->nref < -1, "Uninitialised EPROG nref"); +#ifdef MAX_FUNCTION_DEPTH + DPUTS(zsh_funcnest >=0 && p->nref > zsh_funcnest + 10, + "Overlarge EPROG nref"); +#endif + if (p->nref > 0 && !--p->nref) { + for (i = p->npats, pp = p->pats; i--; pp++) + freepatprog(*pp); + if (p->dump) { + decrdumpcount(p->dump); + zfree(p->pats, p->npats * sizeof(Patprog)); + } else + zfree(p->pats, p->len); + zfree(p, sizeof(*p)); + } + } +} + +/**/ +char * +ecgetstr(Estate s, int dup, int *tokflag) +{ + static char buf[4]; + wordcode c = *s->pc++; + char *r; + + if (c == 6 || c == 7) + r = ""; + else if (c & 2) { + buf[0] = (char) ((c >> 3) & 0xff); + buf[1] = (char) ((c >> 11) & 0xff); + buf[2] = (char) ((c >> 19) & 0xff); + buf[3] = '\0'; + r = dupstring(buf); + dup = EC_NODUP; + } else { + r = s->strs + (c >> 2); + } + if (tokflag) + *tokflag = (c & 1); + + /*** Since function dump files are mapped read-only, avoiding to + * to duplicate strings when they don't contain tokens may fail + * when one of the many utility functions happens to write to + * one of the strings (without really modifying it). + * If that happens to you and you don't feel like debugging it, + * just change the line below to: + * + * return (dup ? dupstring(r) : r); + */ + + return ((dup == EC_DUP || (dup && (c & 1))) ? dupstring(r) : r); +} + +/**/ +char * +ecrawstr(Eprog p, Wordcode pc, int *tokflag) +{ + static char buf[4]; + wordcode c = *pc; + + if (c == 6 || c == 7) { + if (tokflag) + *tokflag = (c & 1); + return ""; + } else if (c & 2) { + buf[0] = (char) ((c >> 3) & 0xff); + buf[1] = (char) ((c >> 11) & 0xff); + buf[2] = (char) ((c >> 19) & 0xff); + buf[3] = '\0'; + if (tokflag) + *tokflag = (c & 1); + return buf; + } else { + if (tokflag) + *tokflag = (c & 1); + return p->strs + (c >> 2); + } +} + +/**/ +char ** +ecgetarr(Estate s, int num, int dup, int *tokflag) +{ + char **ret, **rp; + int tf = 0, tmp = 0; + + ret = rp = (char **) zhalloc((num + 1) * sizeof(char *)); + + while (num--) { + *rp++ = ecgetstr(s, dup, &tmp); + tf |= tmp; + } + *rp = NULL; + if (tokflag) + *tokflag = tf; + + return ret; +} + +/**/ +LinkList +ecgetlist(Estate s, int num, int dup, int *tokflag) +{ + if (num) { + LinkList ret; + int i, tf = 0, tmp = 0; + + ret = newsizedlist(num); + for (i = 0; i < num; i++) { + setsizednode(ret, i, ecgetstr(s, dup, &tmp)); + tf |= tmp; + } + if (tokflag) + *tokflag = tf; + return ret; + } + if (tokflag) + *tokflag = 0; + return NULL; +} + +/**/ +LinkList +ecgetredirs(Estate s) +{ + LinkList ret = newlinklist(); + wordcode code = *s->pc++; + + while (wc_code(code) == WC_REDIR) { + Redir r = (Redir) zhalloc(sizeof(*r)); + + r->type = WC_REDIR_TYPE(code); + r->fd1 = *s->pc++; + r->name = ecgetstr(s, EC_DUP, NULL); + if (WC_REDIR_FROM_HEREDOC(code)) { + r->flags = REDIRF_FROM_HEREDOC; + r->here_terminator = ecgetstr(s, EC_DUP, NULL); + r->munged_here_terminator = ecgetstr(s, EC_DUP, NULL); + } else { + r->flags = 0; + r->here_terminator = NULL; + r->munged_here_terminator = NULL; + } + if (WC_REDIR_VARID(code)) + r->varid = ecgetstr(s, EC_DUP, NULL); + else + r->varid = NULL; + + addlinknode(ret, r); + + code = *s->pc++; + } + s->pc--; + + return ret; +} + +/* + * Copy the consecutive set of redirections in the state at s. + * Return NULL if none, else an Eprog consisting only of the + * redirections from permanently allocated memory. + * + * s is left in the state ready for whatever follows the redirections. + */ + +/**/ +Eprog +eccopyredirs(Estate s) +{ + Wordcode pc = s->pc; + wordcode code = *pc; + int ncode, ncodes = 0, r; + + if (wc_code(code) != WC_REDIR) + return NULL; + + init_parse(); + + while (wc_code(code) == WC_REDIR) { +#ifdef DEBUG + int type = WC_REDIR_TYPE(code); +#endif + + DPUTS(type == REDIR_HEREDOC || type == REDIR_HEREDOCDASH, + "unexpanded here document"); + + if (WC_REDIR_FROM_HEREDOC(code)) + ncode = 5; + else + ncode = 3; + if (WC_REDIR_VARID(code)) + ncode++; + pc += ncode; + ncodes += ncode; + code = *pc; + } + r = ecused; + ecispace(r, ncodes); + + code = *s->pc; + while (wc_code(code) == WC_REDIR) { + s->pc++; + + ecbuf[r++] = code; + /* fd1 */ + ecbuf[r++] = *s->pc++; + /* name or HERE string */ + /* No DUP needed as we'll copy into Eprog immediately below */ + ecbuf[r++] = ecstrcode(ecgetstr(s, EC_NODUP, NULL)); + if (WC_REDIR_FROM_HEREDOC(code)) + { + /* terminator, raw */ + ecbuf[r++] = ecstrcode(ecgetstr(s, EC_NODUP, NULL)); + /* terminator, munged */ + ecbuf[r++] = ecstrcode(ecgetstr(s, EC_NODUP, NULL)); + } + if (WC_REDIR_VARID(code)) + ecbuf[r++] = ecstrcode(ecgetstr(s, EC_NODUP, NULL)); + + code = *s->pc; + } + + /* bld_eprog() appends a useful WC_END marker */ + return bld_eprog(0); +} + +/**/ +mod_export struct eprog dummy_eprog; + +static wordcode dummy_eprog_code; + +/**/ +void +init_eprog(void) +{ + dummy_eprog_code = WCB_END(); + dummy_eprog.len = sizeof(wordcode); + dummy_eprog.prog = &dummy_eprog_code; + dummy_eprog.strs = NULL; +} + +/* Code for function dump files. + * + * Dump files consist of a header and the function bodies (the wordcode + * plus the string table) and that twice: once for the byte-order of the + * host the file was created on and once for the other byte-order. The + * header describes where the beginning of the `other' version is and it + * is up to the shell reading the file to decide which version it needs. + * This is done by checking if the first word is FD_MAGIC (then the + * shell reading the file has the same byte order as the one that created + * the file) or if it is FD_OMAGIC, then the `other' version has to be + * read. + * The header is the magic number, a word containing the flags (if the + * file should be mapped or read and if this header is the `other' one), + * the version string in a field of 40 characters and the descriptions + * for the functions in the dump file. + * + * NOTES: + * - This layout has to be kept; everything after it may be changed. + * - When incompatible changes are made, the FD_MAGIC and FD_OMAGIC + * numbers have to be changed. + * + * Each description consists of a struct fdhead followed by the name, + * aligned to sizeof(wordcode) (i.e. 4 bytes). + */ + +#include "version.h" + +#define FD_EXT ".zwc" +#define FD_MINMAP 4096 + +#define FD_PRELEN 12 +#define FD_MAGIC 0x04050607 +#define FD_OMAGIC 0x07060504 + +#define FDF_MAP 1 +#define FDF_OTHER 2 + +typedef struct fdhead *FDHead; + +struct fdhead { + wordcode start; /* offset to function definition */ + wordcode len; /* length of wordcode/strings */ + wordcode npats; /* number of patterns needed */ + wordcode strs; /* offset to strings */ + wordcode hlen; /* header length (incl. name) */ + wordcode flags; /* flags and offset to name tail */ +}; + +#define fdheaderlen(f) (((Wordcode) (f))[FD_PRELEN]) + +#define fdmagic(f) (((Wordcode) (f))[0]) +#define fdsetbyte(f,i,v) \ + ((((unsigned char *) (((Wordcode) (f)) + 1))[i]) = ((unsigned char) (v))) +#define fdbyte(f,i) ((wordcode) (((unsigned char *) (((Wordcode) (f)) + 1))[i])) +#define fdflags(f) fdbyte(f, 0) +#define fdsetflags(f,v) fdsetbyte(f, 0, v) +#define fdother(f) (fdbyte(f, 1) + (fdbyte(f, 2) << 8) + (fdbyte(f, 3) << 16)) +#define fdsetother(f, o) \ + do { \ + fdsetbyte(f, 1, ((o) & 0xff)); \ + fdsetbyte(f, 2, (((o) >> 8) & 0xff)); \ + fdsetbyte(f, 3, (((o) >> 16) & 0xff)); \ + } while (0) +#define fdversion(f) ((char *) ((f) + 2)) + +#define firstfdhead(f) ((FDHead) (((Wordcode) (f)) + FD_PRELEN)) +#define nextfdhead(f) ((FDHead) (((Wordcode) (f)) + (f)->hlen)) + +#define fdhflags(f) (((FDHead) (f))->flags) +#define fdhtail(f) (((FDHead) (f))->flags >> 2) +#define fdhbldflags(f,t) ((f) | ((t) << 2)) + +#define FDHF_KSHLOAD 1 +#define FDHF_ZSHLOAD 2 + +#define fdname(f) ((char *) (((FDHead) (f)) + 1)) + +/* This is used when building wordcode files. */ + +typedef struct wcfunc *WCFunc; + +struct wcfunc { + char *name; + Eprog prog; + int flags; +}; + +/* Try to find the description for the given function name. */ + +static FDHead +dump_find_func(Wordcode h, char *name) +{ + FDHead n, e = (FDHead) (h + fdheaderlen(h)); + + for (n = firstfdhead(h); n < e; n = nextfdhead(n)) + if (!strcmp(name, fdname(n) + fdhtail(n))) + return n; + + return NULL; +} + +/**/ +int +bin_zcompile(char *nam, char **args, Options ops, UNUSED(int func)) +{ + int map, flags, ret; + char *dump; + + if ((OPT_ISSET(ops,'k') && OPT_ISSET(ops,'z')) || + (OPT_ISSET(ops,'R') && OPT_ISSET(ops,'M')) || + (OPT_ISSET(ops,'c') && + (OPT_ISSET(ops,'U') || OPT_ISSET(ops,'k') || OPT_ISSET(ops,'z'))) || + (!(OPT_ISSET(ops,'c') || OPT_ISSET(ops,'a')) && OPT_ISSET(ops,'m'))) { + zwarnnam(nam, "illegal combination of options"); + return 1; + } + if ((OPT_ISSET(ops,'c') || OPT_ISSET(ops,'a')) && isset(KSHAUTOLOAD)) + zwarnnam(nam, "functions will use zsh style autoloading"); + + flags = (OPT_ISSET(ops,'k') ? FDHF_KSHLOAD : + (OPT_ISSET(ops,'z') ? FDHF_ZSHLOAD : 0)); + + if (OPT_ISSET(ops,'t')) { + Wordcode f; + + if (!*args) { + zwarnnam(nam, "too few arguments"); + return 1; + } + if (!(f = load_dump_header(nam, (strsfx(FD_EXT, *args) ? *args : + dyncat(*args, FD_EXT)), 1))) + return 1; + + if (args[1]) { + for (args++; *args; args++) + if (!dump_find_func(f, *args)) + return 1; + return 0; + } else { + FDHead h, e = (FDHead) (f + fdheaderlen(f)); + + printf("zwc file (%s) for zsh-%s\n", + ((fdflags(f) & FDF_MAP) ? "mapped" : "read"), fdversion(f)); + for (h = firstfdhead(f); h < e; h = nextfdhead(h)) + printf("%s\n", fdname(h)); + return 0; + } + } + if (!*args) { + zwarnnam(nam, "too few arguments"); + return 1; + } + map = (OPT_ISSET(ops,'M') ? 2 : (OPT_ISSET(ops,'R') ? 0 : 1)); + + if (!args[1] && !(OPT_ISSET(ops,'c') || OPT_ISSET(ops,'a'))) { + queue_signals(); + ret = build_dump(nam, dyncat(*args, FD_EXT), args, OPT_ISSET(ops,'U'), + map, flags); + unqueue_signals(); + return ret; + } + dump = (strsfx(FD_EXT, *args) ? *args : dyncat(*args, FD_EXT)); + + queue_signals(); + ret = ((OPT_ISSET(ops,'c') || OPT_ISSET(ops,'a')) ? + build_cur_dump(nam, dump, args + 1, OPT_ISSET(ops,'m'), map, + (OPT_ISSET(ops,'c') ? 1 : 0) | + (OPT_ISSET(ops,'a') ? 2 : 0)) : + build_dump(nam, dump, args + 1, OPT_ISSET(ops,'U'), map, flags)); + unqueue_signals(); + + return ret; +} + +/* Load the header of a dump file. Returns NULL if the file isn't a + * valid dump file. */ + +/**/ +static Wordcode +load_dump_header(char *nam, char *name, int err) +{ + int fd, v = 1; + wordcode buf[FD_PRELEN + 1]; + + if ((fd = open(name, O_RDONLY)) < 0) { + if (err) + zwarnnam(nam, "can't open zwc file: %s", name); + return NULL; + } + if (read(fd, buf, (FD_PRELEN + 1) * sizeof(wordcode)) != + ((FD_PRELEN + 1) * sizeof(wordcode)) || + (v = (fdmagic(buf) != FD_MAGIC && fdmagic(buf) != FD_OMAGIC)) || + strcmp(fdversion(buf), ZSH_VERSION)) { + if (err) { + if (!v) { + zwarnnam(nam, "zwc file has wrong version (zsh-%s): %s", + fdversion(buf), name); + } else + zwarnnam(nam, "invalid zwc file: %s" , name); + } + close(fd); + return NULL; + } else { + int len; + Wordcode head; + + if (fdmagic(buf) == FD_MAGIC) { + len = fdheaderlen(buf) * sizeof(wordcode); + head = (Wordcode) zhalloc(len); + } + else { + int o = fdother(buf); + + if (lseek(fd, o, 0) == -1 || + read(fd, buf, (FD_PRELEN + 1) * sizeof(wordcode)) != + ((FD_PRELEN + 1) * sizeof(wordcode))) { + zwarnnam(nam, "invalid zwc file: %s" , name); + close(fd); + return NULL; + } + len = fdheaderlen(buf) * sizeof(wordcode); + head = (Wordcode) zhalloc(len); + } + memcpy(head, buf, (FD_PRELEN + 1) * sizeof(wordcode)); + + len -= (FD_PRELEN + 1) * sizeof(wordcode); + if (read(fd, head + (FD_PRELEN + 1), len) != len) { + close(fd); + zwarnnam(nam, "invalid zwc file: %s" , name); + return NULL; + } + close(fd); + return head; + } +} + +/* Swap the bytes in a wordcode. */ + +static void +fdswap(Wordcode p, int n) +{ + wordcode c; + + for (; n--; p++) { + c = *p; + *p = (((c & 0xff) << 24) | + ((c & 0xff00) << 8) | + ((c & 0xff0000) >> 8) | + ((c & 0xff000000) >> 24)); + } +} + +/* Write a dump file. */ + +static void +write_dump(int dfd, LinkList progs, int map, int hlen, int tlen) +{ + LinkNode node; + WCFunc wcf; + int other = 0, ohlen, tmp; + wordcode pre[FD_PRELEN]; + char *tail, *n; + struct fdhead head; + Eprog prog; + + if (map == 1) + map = (tlen >= FD_MINMAP); + + memset(pre, 0, sizeof(wordcode) * FD_PRELEN); + + for (ohlen = hlen; ; hlen = ohlen) { + fdmagic(pre) = (other ? FD_OMAGIC : FD_MAGIC); + fdsetflags(pre, ((map ? FDF_MAP : 0) | other)); + fdsetother(pre, tlen); + strcpy(fdversion(pre), ZSH_VERSION); + write_loop(dfd, (char *)pre, FD_PRELEN * sizeof(wordcode)); + + for (node = firstnode(progs); node; incnode(node)) { + wcf = (WCFunc) getdata(node); + n = wcf->name; + prog = wcf->prog; + head.start = hlen; + hlen += (prog->len - (prog->npats * sizeof(Patprog)) + + sizeof(wordcode) - 1) / sizeof(wordcode); + head.len = prog->len - (prog->npats * sizeof(Patprog)); + head.npats = prog->npats; + head.strs = prog->strs - ((char *) prog->prog); + head.hlen = (sizeof(struct fdhead) / sizeof(wordcode)) + + (strlen(n) + sizeof(wordcode)) / sizeof(wordcode); + if ((tail = strrchr(n, '/'))) + tail++; + else + tail = n; + head.flags = fdhbldflags(wcf->flags, (tail - n)); + if (other) + fdswap((Wordcode) &head, sizeof(head) / sizeof(wordcode)); + write_loop(dfd, (char *)&head, sizeof(head)); + tmp = strlen(n) + 1; + write_loop(dfd, n, tmp); + if ((tmp &= (sizeof(wordcode) - 1))) + write_loop(dfd, (char *)&head, sizeof(wordcode) - tmp); + } + for (node = firstnode(progs); node; incnode(node)) { + prog = ((WCFunc) getdata(node))->prog; + tmp = (prog->len - (prog->npats * sizeof(Patprog)) + + sizeof(wordcode) - 1) / sizeof(wordcode); + if (other) + fdswap(prog->prog, (((Wordcode) prog->strs) - prog->prog)); + write_loop(dfd, (char *)prog->prog, tmp * sizeof(wordcode)); + } + if (other) + break; + other = FDF_OTHER; + } +} + +/**/ +static int +build_dump(char *nam, char *dump, char **files, int ali, int map, int flags) +{ + int dfd, fd, hlen, tlen, flen, ona = noaliases; + LinkList progs; + char *file; + Eprog prog; + WCFunc wcf; + + if (!strsfx(FD_EXT, dump)) + dump = dyncat(dump, FD_EXT); + + unlink(dump); + if ((dfd = open(dump, O_WRONLY|O_CREAT, 0444)) < 0) { + zwarnnam(nam, "can't write zwc file: %s", dump); + return 1; + } + progs = newlinklist(); + noaliases = ali; + + for (hlen = FD_PRELEN, tlen = 0; *files; files++) { + struct stat st; + + if (check_cond(*files, "k")) { + flags = (flags & ~(FDHF_KSHLOAD | FDHF_ZSHLOAD)) | FDHF_KSHLOAD; + continue; + } else if (check_cond(*files, "z")) { + flags = (flags & ~(FDHF_KSHLOAD | FDHF_ZSHLOAD)) | FDHF_ZSHLOAD; + continue; + } + if ((fd = open(*files, O_RDONLY)) < 0 || + fstat(fd, &st) != 0 || !S_ISREG(st.st_mode) || + (flen = lseek(fd, 0, 2)) == -1) { + if (fd >= 0) + close(fd); + close(dfd); + zwarnnam(nam, "can't open file: %s", *files); + noaliases = ona; + unlink(dump); + return 1; + } + file = (char *) zalloc(flen + 1); + file[flen] = '\0'; + lseek(fd, 0, 0); + if (read(fd, file, flen) != flen) { + close(fd); + close(dfd); + zfree(file, flen); + zwarnnam(nam, "can't read file: %s", *files); + noaliases = ona; + unlink(dump); + return 1; + } + close(fd); + file = metafy(file, flen, META_REALLOC); + + if (!(prog = parse_string(file, 1)) || errflag) { + errflag &= ~ERRFLAG_ERROR; + close(dfd); + zfree(file, flen); + zwarnnam(nam, "can't read file: %s", *files); + noaliases = ona; + unlink(dump); + return 1; + } + zfree(file, flen); + + wcf = (WCFunc) zhalloc(sizeof(*wcf)); + wcf->name = *files; + wcf->prog = prog; + wcf->flags = ((prog->flags & EF_RUN) ? FDHF_KSHLOAD : flags); + addlinknode(progs, wcf); + + flen = (strlen(*files) + sizeof(wordcode)) / sizeof(wordcode); + hlen += (sizeof(struct fdhead) / sizeof(wordcode)) + flen; + + tlen += (prog->len - (prog->npats * sizeof(Patprog)) + + sizeof(wordcode) - 1) / sizeof(wordcode); + } + noaliases = ona; + + tlen = (tlen + hlen) * sizeof(wordcode); + + write_dump(dfd, progs, map, hlen, tlen); + + close(dfd); + + return 0; +} + +static int +cur_add_func(char *nam, Shfunc shf, LinkList names, LinkList progs, + int *hlen, int *tlen, int what) +{ + Eprog prog; + WCFunc wcf; + + if (shf->node.flags & PM_UNDEFINED) { + int ona = noaliases; + + if (!(what & 2)) { + zwarnnam(nam, "function is not loaded: %s", shf->node.nam); + return 1; + } + noaliases = (shf->node.flags & PM_UNALIASED); + if (!(prog = getfpfunc(shf->node.nam, NULL, NULL, NULL, 0)) || + prog == &dummy_eprog) { + noaliases = ona; + zwarnnam(nam, "can't load function: %s", shf->node.nam); + return 1; + } + if (prog->dump) + prog = dupeprog(prog, 1); + noaliases = ona; + } else { + if (!(what & 1)) { + zwarnnam(nam, "function is already loaded: %s", shf->node.nam); + return 1; + } + prog = dupeprog(shf->funcdef, 1); + } + wcf = (WCFunc) zhalloc(sizeof(*wcf)); + wcf->name = shf->node.nam; + wcf->prog = prog; + wcf->flags = ((prog->flags & EF_RUN) ? FDHF_KSHLOAD : FDHF_ZSHLOAD); + addlinknode(progs, wcf); + addlinknode(names, shf->node.nam); + + *hlen += ((sizeof(struct fdhead) / sizeof(wordcode)) + + ((strlen(shf->node.nam) + sizeof(wordcode)) / sizeof(wordcode))); + *tlen += (prog->len - (prog->npats * sizeof(Patprog)) + + sizeof(wordcode) - 1) / sizeof(wordcode); + + return 0; +} + +/**/ +static int +build_cur_dump(char *nam, char *dump, char **names, int match, int map, + int what) +{ + int dfd, hlen, tlen; + LinkList progs, lnames; + Shfunc shf = NULL; + + if (!strsfx(FD_EXT, dump)) + dump = dyncat(dump, FD_EXT); + + unlink(dump); + if ((dfd = open(dump, O_WRONLY|O_CREAT, 0444)) < 0) { + zwarnnam(nam, "can't write zwc file: %s", dump); + return 1; + } + progs = newlinklist(); + lnames = newlinklist(); + + hlen = FD_PRELEN; + tlen = 0; + + if (!*names) { + int i; + HashNode hn; + + for (i = 0; i < shfunctab->hsize; i++) + for (hn = shfunctab->nodes[i]; hn; hn = hn->next) + if (cur_add_func(nam, (Shfunc) hn, lnames, progs, + &hlen, &tlen, what)) { + errflag &= ~ERRFLAG_ERROR; + close(dfd); + unlink(dump); + return 1; + } + } else if (match) { + char *pat; + Patprog pprog; + int i; + HashNode hn; + + for (; *names; names++) { + tokenize(pat = dupstring(*names)); + /* Signal-safe here, caller queues signals */ + if (!(pprog = patcompile(pat, PAT_STATIC, NULL))) { + zwarnnam(nam, "bad pattern: %s", *names); + close(dfd); + unlink(dump); + return 1; + } + for (i = 0; i < shfunctab->hsize; i++) + for (hn = shfunctab->nodes[i]; hn; hn = hn->next) + if (!linknodebydatum(lnames, hn->nam) && + pattry(pprog, hn->nam) && + cur_add_func(nam, (Shfunc) hn, lnames, progs, + &hlen, &tlen, what)) { + errflag &= ~ERRFLAG_ERROR; + close(dfd); + unlink(dump); + return 1; + } + } + } else { + for (; *names; names++) { + if (errflag || + !(shf = (Shfunc) shfunctab->getnode(shfunctab, *names))) { + zwarnnam(nam, "unknown function: %s", *names); + errflag &= ~ERRFLAG_ERROR; + close(dfd); + unlink(dump); + return 1; + } + if (cur_add_func(nam, shf, lnames, progs, &hlen, &tlen, what)) { + errflag &= ~ERRFLAG_ERROR; + close(dfd); + unlink(dump); + return 1; + } + } + } + if (empty(progs)) { + zwarnnam(nam, "no functions"); + errflag &= ~ERRFLAG_ERROR; + close(dfd); + unlink(dump); + return 1; + } + tlen = (tlen + hlen) * sizeof(wordcode); + + write_dump(dfd, progs, map, hlen, tlen); + + close(dfd); + + return 0; +} + +/**/ +#if defined(HAVE_SYS_MMAN_H) && defined(HAVE_MMAP) && defined(HAVE_MUNMAP) + +#include + +/**/ +#if defined(MAP_SHARED) && defined(PROT_READ) + +/**/ +#define USE_MMAP 1 + +/**/ +#endif +/**/ +#endif + +/**/ +#ifdef USE_MMAP + +/* List of dump files mapped. */ + +static FuncDump dumps; + +/**/ +static int +zwcstat(char *filename, struct stat *buf) +{ + if (stat(filename, buf)) { +#ifdef HAVE_FSTAT + FuncDump f; + + for (f = dumps; f; f = f->next) { + if (!strncmp(filename, f->filename, strlen(f->filename)) && + !fstat(f->fd, buf)) + return 0; + } +#endif + return 1; + } else return 0; +} + +/* Load a dump file (i.e. map it). */ + +static void +load_dump_file(char *dump, struct stat *sbuf, int other, int len) +{ + FuncDump d; + Wordcode addr; + int fd, off, mlen; + + if (other) { + static size_t pgsz = 0; + + if (!pgsz) { + +#ifdef _SC_PAGESIZE + pgsz = sysconf(_SC_PAGESIZE); /* SVR4 */ +#else +# ifdef _SC_PAGE_SIZE + pgsz = sysconf(_SC_PAGE_SIZE); /* HPUX */ +# else + pgsz = getpagesize(); +# endif +#endif + + pgsz--; + } + off = len & ~pgsz; + mlen = len + (len - off); + } else { + off = 0; + mlen = len; + } + if ((fd = open(dump, O_RDONLY)) < 0) + return; + + fd = movefd(fd); + if (fd == -1) + return; + + if ((addr = (Wordcode) mmap(NULL, mlen, PROT_READ, MAP_SHARED, fd, off)) == + ((Wordcode) -1)) { + close(fd); + return; + } + d = (FuncDump) zalloc(sizeof(*d)); + d->next = dumps; + dumps = d; + d->dev = sbuf->st_dev; + d->ino = sbuf->st_ino; + d->fd = fd; +#ifdef FD_CLOEXEC + fcntl(fd, F_SETFD, FD_CLOEXEC); +#endif + d->map = addr + (other ? (len - off) / sizeof(wordcode) : 0); + d->addr = addr; + d->len = len; + d->count = 0; + d->filename = ztrdup(dump); +} + +#else + +#define zwcstat(f, b) (!!stat(f, b)) + +/**/ +#endif + +/* Try to load a function from one of the possible wordcode files for it. + * The first argument is a element of $fpath, the second one is the name + * of the function searched and the last one is the possible name for the + * uncompiled function file (/). */ + +/**/ +Eprog +try_dump_file(char *path, char *name, char *file, int *ksh, int test_only) +{ + Eprog prog; + struct stat std, stc, stn; + int rd, rc, rn; + char *dig, *wc; + + if (strsfx(FD_EXT, path)) { + queue_signals(); + prog = check_dump_file(path, NULL, name, ksh, test_only); + unqueue_signals(); + return prog; + } + dig = dyncat(path, FD_EXT); + wc = dyncat(file, FD_EXT); + + rd = zwcstat(dig, &std); + rc = stat(wc, &stc); + rn = stat(file, &stn); + + /* See if there is a digest file for the directory, it is younger than + * both the uncompiled function file and its compiled version (or they + * don't exist) and the digest file contains the definition for the + * function. */ + queue_signals(); + if (!rd && + (rc || std.st_mtime >= stc.st_mtime) && + (rn || std.st_mtime >= stn.st_mtime) && + (prog = check_dump_file(dig, &std, name, ksh, test_only))) { + unqueue_signals(); + return prog; + } + /* No digest file. Now look for the per-function compiled file. */ + if (!rc && + (rn || stc.st_mtime >= stn.st_mtime) && + (prog = check_dump_file(wc, &stc, name, ksh, test_only))) { + unqueue_signals(); + return prog; + } + /* No compiled file for the function. The caller (getfpfunc() will + * check if the directory contains the uncompiled file for it. */ + unqueue_signals(); + return NULL; +} + +/* Almost the same, but for sourced files. */ + +/**/ +Eprog +try_source_file(char *file) +{ + Eprog prog; + struct stat stc, stn; + int rc, rn; + char *wc, *tail; + + if ((tail = strrchr(file, '/'))) + tail++; + else + tail = file; + + if (strsfx(FD_EXT, file)) { + queue_signals(); + prog = check_dump_file(file, NULL, tail, NULL, 0); + unqueue_signals(); + return prog; + } + wc = dyncat(file, FD_EXT); + + rc = stat(wc, &stc); + rn = stat(file, &stn); + + queue_signals(); + if (!rc && (rn || stc.st_mtime >= stn.st_mtime) && + (prog = check_dump_file(wc, &stc, tail, NULL, 0))) { + unqueue_signals(); + return prog; + } + unqueue_signals(); + return NULL; +} + +/* See if `file' names a wordcode dump file and that contains the + * definition for the function `name'. If so, return an eprog for it. */ + +/**/ +static Eprog +check_dump_file(char *file, struct stat *sbuf, char *name, int *ksh, + int test_only) +{ + int isrec = 0; + Wordcode d; + FDHead h; + FuncDump f; + struct stat lsbuf; + + if (!sbuf) { + if (zwcstat(file, &lsbuf)) + return NULL; + sbuf = &lsbuf; + } + +#ifdef USE_MMAP + + rec: + +#endif + + d = NULL; + +#ifdef USE_MMAP + + for (f = dumps; f; f = f->next) + if (f->dev == sbuf->st_dev && f->ino == sbuf->st_ino) { + d = f->map; + break; + } + +#else + + f = NULL; + +#endif + + if (!f && (isrec || !(d = load_dump_header(NULL, file, 0)))) + return NULL; + + if ((h = dump_find_func(d, name))) { + /* Found the name. If the file is already mapped, return the eprog, + * otherwise map it and just go up. */ + if (test_only) + { + /* This is all we need. Just return dummy. */ + return &dummy_eprog; + } + +#ifdef USE_MMAP + + if (f) { + Eprog prog = (Eprog) zalloc(sizeof(*prog)); + Patprog *pp; + int np; + + prog->flags = EF_MAP; + prog->len = h->len; + prog->npats = np = h->npats; + prog->nref = 1; /* allocated from permanent storage */ + prog->pats = pp = (Patprog *) zalloc(np * sizeof(Patprog)); + prog->prog = f->map + h->start; + prog->strs = ((char *) prog->prog) + h->strs; + prog->shf = NULL; + prog->dump = f; + + incrdumpcount(f); + + while (np--) + *pp++ = dummy_patprog1; + + if (ksh) + *ksh = ((fdhflags(h) & FDHF_KSHLOAD) ? 2 : + ((fdhflags(h) & FDHF_ZSHLOAD) ? 0 : 1)); + + return prog; + } else if (fdflags(d) & FDF_MAP) { + load_dump_file(file, sbuf, (fdflags(d) & FDF_OTHER), fdother(d)); + isrec = 1; + goto rec; + } else + +#endif + + { + Eprog prog; + Patprog *pp; + int np, fd, po = h->npats * sizeof(Patprog); + + if ((fd = open(file, O_RDONLY)) < 0 || + lseek(fd, ((h->start * sizeof(wordcode)) + + ((fdflags(d) & FDF_OTHER) ? fdother(d) : 0)), 0) < 0) { + if (fd >= 0) + close(fd); + return NULL; + } + d = (Wordcode) zalloc(h->len + po); + + if (read(fd, ((char *) d) + po, h->len) != (int)h->len) { + close(fd); + zfree(d, h->len); + + return NULL; + } + close(fd); + + prog = (Eprog) zalloc(sizeof(*prog)); + + prog->flags = EF_REAL; + prog->len = h->len + po; + prog->npats = np = h->npats; + prog->nref = 1; /* allocated from permanent storage */ + prog->pats = pp = (Patprog *) d; + prog->prog = (Wordcode) (((char *) d) + po); + prog->strs = ((char *) prog->prog) + h->strs; + prog->shf = NULL; + prog->dump = f; + + while (np--) + *pp++ = dummy_patprog1; + + if (ksh) + *ksh = ((fdhflags(h) & FDHF_KSHLOAD) ? 2 : + ((fdhflags(h) & FDHF_ZSHLOAD) ? 0 : 1)); + + return prog; + } + } + return NULL; +} + +#ifdef USE_MMAP + +/* Increment the reference counter for a dump file. */ + +/**/ +void +incrdumpcount(FuncDump f) +{ + f->count++; +} + +/**/ +static void +freedump(FuncDump f) +{ + munmap((void *) f->addr, f->len); + zclose(f->fd); + zsfree(f->filename); + zfree(f, sizeof(*f)); +} + +/* Decrement the reference counter for a dump file. If zero, unmap the file. */ + +/**/ +void +decrdumpcount(FuncDump f) +{ + f->count--; + if (!f->count) { + FuncDump p, q; + + for (q = NULL, p = dumps; p && p != f; q = p, p = p->next); + if (p) { + if (q) + q->next = p->next; + else + dumps = p->next; + freedump(f); + } + } +} + +#ifndef FD_CLOEXEC +/**/ +mod_export void +closedumps(void) +{ + while (dumps) { + FuncDump p = dumps->next; + freedump(dumps); + dumps = p; + } +} +#endif + +#else + +void +incrdumpcount(FuncDump f) +{ +} + +void +decrdumpcount(FuncDump f) +{ +} + +#ifndef FD_CLOEXEC +/**/ +mod_export void +closedumps(void) +{ +} +#endif + +#endif + +/**/ +int +dump_autoload(char *nam, char *file, int on, Options ops, int func) +{ + Wordcode h; + FDHead n, e; + Shfunc shf; + int ret = 0; + + if (!strsfx(FD_EXT, file)) + file = dyncat(file, FD_EXT); + + if (!(h = load_dump_header(nam, file, 1))) + return 1; + + for (n = firstfdhead(h), e = (FDHead) (h + fdheaderlen(h)); n < e; + n = nextfdhead(n)) { + shf = (Shfunc) zshcalloc(sizeof *shf); + shf->node.flags = on; + shf->funcdef = mkautofn(shf); + shf->sticky = NULL; + shfunctab->addnode(shfunctab, ztrdup(fdname(n) + fdhtail(n)), shf); + if (OPT_ISSET(ops,'X') && eval_autoload(shf, shf->node.nam, ops, func)) + ret = 1; + } + return ret; +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/pattern.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/pattern.c new file mode 100644 index 00000000..737f5cdc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/pattern.c @@ -0,0 +1,4336 @@ +/* + * pattern.c - pattern matching + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1999 Peter Stephenson + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Peter Stephenson or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Peter Stephenson and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Peter Stephenson and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Peter Stephenson and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + * Pattern matching code derived from the regexp library by Henry + * Spencer, which has the following copyright. + * + * Copyright (c) 1986 by University of Toronto. + * Written by Henry Spencer. Not derived from licensed software. + * + * Permission is granted to anyone to use this software for any + * purpose on any computer system, and to redistribute it freely, + * subject to the following restrictions: + * + * 1. The author is not responsible for the consequences of use of + * this software, no matter how awful, even if they arise + * from defects in it. + * + * 2. The origin of this software must not be misrepresented, either + * by explicit claim or by omission. + * + * 3. Altered versions must be plainly marked as such, and must not + * be misrepresented as being the original software. + * + * Eagle-eyed readers will notice this is an altered version. Incredibly + * sharp-eyed readers might even find bits that weren't altered. + * + * + * And I experienced a sense that, like certain regular + * expressions, seemed to match the day from beginning to end, so + * that I did not need to identify the parenthesised subexpression + * that told of dawn, nor the group of characters that indicated + * the moment when my grandfather returned home with news of + * Swann's departure for Paris; and the whole length of the month + * of May, as if matched by a closure, fitted into the buffer of my + * life with no sign of overflowing, turning the days, like a + * procession of insects that could consist of this or that + * species, into a random and unstructured repetition of different + * sequences, anchored from the first day of the month to the last + * in the same fashion as the weeks when I knew I would not see + * Gilberte and would search in vain for any occurrences of the + * string in the avenue of hawthorns by Tansonville, without my + * having to delimit explicitly the start or finish of the pattern. + * + * M. Proust, "In Search of Lost Files", + * bk I, "The Walk by Bourne's Place". + */ + +#include "zsh.mdh" + +/* + * The following union is used mostly for alignment purposes. + * Normal nodes are longs, while certain nodes take a char * as an argument; + * here we make sure that they both work out to the same length. + * The compiled regexp we construct consists of upats stuck together; + * anything else to be added (strings, numbers) is stuck after and + * then aligned to a whole number of upat units. + * + * Note also that offsets are in terms of the sizes of these things. + */ +union upat { + long l; + unsigned char *p; +}; + +typedef union upat *Upat; + +#include "pattern.pro" + +/* Number of active parenthesized expressions allowed in backreferencing */ +#define NSUBEXP 9 + +/* definition number opnd? meaning */ +#define P_END 0x00 /* no End of program. */ +#define P_EXCSYNC 0x01 /* no Test if following exclude already failed */ +#define P_EXCEND 0x02 /* no Test if exclude matched orig branch */ +#define P_BACK 0x03 /* no Match "", "next" ptr points backward. */ +#define P_EXACTLY 0x04 /* lstr Match this string. */ +#define P_NOTHING 0x05 /* no Match empty string. */ +#define P_ONEHASH 0x06 /* node Match this (simple) thing 0 or more times. */ +#define P_TWOHASH 0x07 /* node Match this (simple) thing 1 or more times. */ +#define P_GFLAGS 0x08 /* long Match nothing and set globbing flags */ +#define P_ISSTART 0x09 /* no Match start of string. */ +#define P_ISEND 0x0a /* no Match end of string. */ +#define P_COUNTSTART 0x0b /* no Initialise P_COUNT */ +#define P_COUNT 0x0c /* 3*long uc* node Match a number of repetitions */ +/* numbered so we can test bit 5 for a branch */ +#define P_BRANCH 0x20 /* node Match this alternative, or the next... */ +#define P_WBRANCH 0x21 /* uc* node P_BRANCH, but match at least 1 char */ +/* excludes are also branches, but have bit 4 set, too */ +#define P_EXCLUDE 0x30 /* uc* node Exclude this from previous branch */ +#define P_EXCLUDP 0x31 /* uc* node Exclude, using full file path so far */ +/* numbered so we can test bit 6 so as not to match initial '.' */ +#define P_ANY 0x40 /* no Match any one character. */ +#define P_ANYOF 0x41 /* str Match any character in this string. */ +#define P_ANYBUT 0x42 /* str Match any character not in this string. */ +#define P_STAR 0x43 /* no Match any set of characters. */ +#define P_NUMRNG 0x44 /* zr, zr Match a numeric range. */ +#define P_NUMFROM 0x45 /* zr Match a number >= X */ +#define P_NUMTO 0x46 /* zr Match a number <= X */ +#define P_NUMANY 0x47 /* no Match any set of decimal digits */ +/* spaces left for P_OPEN+n,... for backreferences */ +#define P_OPEN 0x80 /* no Mark this point in input as start of n. */ +#define P_CLOSE 0x90 /* no Analogous to OPEN. */ +/* + * no no argument + * zr the range type zrange_t: may be zlong or unsigned long + * char a single char + * uc* a pointer to unsigned char, used at run time and initialised + * to NULL. + * str null-terminated, metafied string + * lstr length as long then string, not null-terminated, unmetafied. + */ + +/* + * Notes on usage: + * P_WBRANCH: This works like a branch and is used in complex closures, + * to ensure we don't succeed on a zero-length match of the pattern, + * since that would cause an infinite loop. We do this by recording + * the positions where we have already tried to match. See the + * P_WBRANCH test in patmatch(). + * + * P_ANY, P_ANYOF: the operand is a null terminated + * string. Normal characters match as expected. Characters + * in the range Meta+PP_ALPHA..Meta+PP_UNKWN do the appropriate + * Posix range tests. This relies on imeta returning true for these + * characters. We treat unknown POSIX ranges as never matching. + * PP_RANGE means the next two (possibly metafied) characters form + * the limits of a range to test; it's too much like hard work to + * expand the range. + * + * P_EXCLUDE, P_EXCSYNC, PEXCEND: P_EXCLUDE appears in the pattern like + * P_BRANCH, but applies to the immediately preceding branch. The code in + * the corresponding branch is followed by a P_EXCSYNC, which simply + * acts as a marker that a P_EXCLUDE comes next. The P_EXCLUDE + * has a pointer to char embeded in it, which works + * like P_WBRANCH: if we get to the P_EXCSYNC, and we already matched + * up to the same position, fail. Thus we are forced to backtrack + * on closures in the P_BRANCH if the first attempt was excluded. + * Corresponding to P_EXCSYNC in the original branch, there is a + * P_EXCEND in the exclusion. If we get to this point, and we did + * *not* match in the original branch, the exclusion itself fails, + * otherwise it succeeds since we know the tail already matches, + * so P_EXCEND is the end of the exclusion test. + * The whole sorry mess looks like this, where the upper lines + * show the linkage of the branches, and the lower shows the linkage + * of their pattern arguments. + * + * --------------------- ---------------------- + * ^ v ^ v + * ( :apat-> :excpat-> ) tail + * ^ + * | | + * -------------------------------------- + * + * P_EXCLUDP: this behaves exactly like P_EXCLUDE, with the sole exception + * that we prepend the path so far to the exclude pattern. This is + * for top level file globs, e.g. ** / *.c~*foo.c + * ^ I had to leave this space + * P_NUM*: zl is a zlong if that is 64-bit, else an unsigned long. + * + * P_COUNTSTART, P_COUNT: a P_COUNTSTART flags the start of a quantified + * closure (#cN,M) and is used to initialise the count. Executing + * the pattern leads back to the P_COUNT, while the next links of the + * P_COUNTSTART and P_COUNT lead to the tail of the pattern: + * + * ---------------- + * v ^ + * pattern tail + * v v ^ + * ------------------------ + */ + +#define P_OP(p) ((p)->l & 0xff) +#define P_NEXT(p) ((p)->l >> 8) +#define P_OPERAND(p) ((p) + 1) +#define P_ISBRANCH(p) ((p)->l & 0x20) +#define P_ISEXCLUDE(p) (((p)->l & 0x30) == 0x30) +#define P_NOTDOT(p) ((p)->l & 0x40) + +/* Specific to lstr type, i.e. P_EXACTLY. */ +#define P_LS_LEN(p) ((p)[1].l) /* can be used as lvalue */ +#define P_LS_STR(p) ((char *)((p) + 2)) + +/* Specific to P_COUNT: arguments as offset in nodes from operator */ +#define P_CT_CURRENT (1) /* Current count */ +#define P_CT_MIN (2) /* Minimum count */ +#define P_CT_MAX (3) /* Maximum count, -1 for none */ +#define P_CT_PTR (4) /* Pointer to last match start */ +#define P_CT_OPERAND (5) /* Operand of P_COUNT */ + +/* Flags needed when pattern is executed */ +#define P_SIMPLE 0x01 /* Simple enough to be #/## operand. */ +#define P_HSTART 0x02 /* Starts with # or ##'d pattern. */ +#define P_PURESTR 0x04 /* Can be matched with a strcmp */ + +#if defined(ZSH_64_BIT_TYPE) || defined(LONG_IS_64_BIT) +typedef zlong zrange_t; +#define ZRANGE_T_IS_SIGNED (1) +#define ZRANGE_MAX ZLONG_MAX +#else +typedef unsigned long zrange_t; +#define ZRANGE_MAX ULONG_MAX +#endif + +#ifdef MULTIBYTE_SUPPORT +/* + * Handle a byte that's not part of a valid character. + * + * This range in Unicode is recommended for purposes of this + * kind as it corresponds to invalid characters. + * + * Note that this strictly only works if wchar_t represents + * Unicode code points, which isn't necessarily true; however, + * converting an invalid character into an unknown format is + * a bit tricky... + */ +#define WCHAR_INVALID(ch) \ + ((wchar_t) (0xDC00 + STOUC(ch))) +#endif /* MULTIBYTE_SUPPORT */ + +/* + * Array of characters corresponding to zpc_chars enum, which it must match. + */ +static const char zpc_chars[ZPC_COUNT] = { + '/', '\0', Bar, Outpar, Tilde, Inpar, Quest, Star, Inbrack, Inang, + Hat, Pound, Bnullkeep, Quest, Star, '+', Bang, '!', '@' +}; + +/* + * Corresponding strings used in enable/disable -p. + * NULL means no way of turning this on or off. + */ +/**/ +mod_export const char *zpc_strings[ZPC_COUNT] = { + NULL, NULL, "|", NULL, "~", "(", "?", "*", "[", "<", + "^", "#", NULL, "?(", "*(", "+(", "!(", "\\!(", "@(" +}; + +/* + * Corresponding array of pattern disables as set by the user + * using "disable -p". + */ +/**/ +mod_export char zpc_disables[ZPC_COUNT]; + +/* + * Stack of saved (compressed) zpc_disables for function scope. + */ + +static struct zpc_disables_save *zpc_disables_stack; + +/* + * Characters which terminate a simple string (ZPC_COUNT) or + * an entire pattern segment (the first ZPC_SEG_COUNT). + * Each entry is either the corresponding character in zpc_chars + * or Marker which is guaranteed not to match a character in a + * pattern we are compiling. + * + * The complete list indicates characters that are special, so e.g. + * (testchar == special[ZPC_TILDE]) succeeds only if testchar is a Tilde + * *and* Tilde is currently special. + */ + +/**/ +char zpc_special[ZPC_COUNT]; + +/* Default size for pattern buffer */ +#define P_DEF_ALLOC 256 + +/* Flags used in compilation */ +static char *patstart, *patparse; /* input pointers */ +static int patnpar; /* () count */ +static char *patcode; /* point of code emission */ +static long patsize; /* size of code */ +static char *patout; /* start of code emission string */ +static long patalloc; /* size allocated for same */ + +/* Flags used in both compilation and execution */ +static int patflags; /* flags passed down to patcompile */ +static int patglobflags; /* globbing flags & approx */ + +/* + * Increment pointer to metafied multibyte string. + */ +#ifdef MULTIBYTE_SUPPORT +typedef wint_t patint_t; + +#define PEOF WEOF + +#define METACHARINC(x) ((void)metacharinc(&x)) + +/* + * TODO: the shiftstate isn't well handled; we don't guarantee + * to maintain it properly between characters. If we don't + * need it we should use mbtowc() instead. + */ +static mbstate_t shiftstate; + +/* + * Multibyte version: it's (almost) as easy to return the + * value as not, so do so since we sometimes need it.. + */ +static wchar_t +metacharinc(char **x) +{ + char *inptr = *x; + char inchar; + size_t ret = MB_INVALID; + wchar_t wc; + + /* + * Cheat if the top bit isn't set. This is second-guessing + * the library, but we know for sure that if the character + * set doesn't have the property that all bytes with the 8th + * bit clear are single characters then we are stuffed. + */ + if (!(patglobflags & GF_MULTIBYTE) || !(STOUC(*inptr) & 0x80)) + { + if (itok(*inptr)) + inchar = ztokens[*inptr++ - Pound]; + else if (*inptr == Meta) { + inptr++; + inchar = *inptr++ ^ 32; + } else { + inchar = *inptr++; + } + *x = inptr; + return (wchar_t)STOUC(inchar); + } + + while (*inptr) { + if (itok(*inptr)) + inchar = ztokens[*inptr++ - Pound]; + else if (*inptr == Meta) { + inptr++; + inchar = *inptr++ ^ 32; + } else { + inchar = *inptr++; + } + ret = mbrtowc(&wc, &inchar, 1, &shiftstate); + + if (ret == MB_INVALID) + break; + if (ret == MB_INCOMPLETE) + continue; + *x = inptr; + return wc; + } + + /* Error. */ + /* Reset the shift state for next time. */ + memset(&shiftstate, 0, sizeof(shiftstate)); + return WCHAR_INVALID(*(*x)++); +} + +#else +typedef int patint_t; + +#define PEOF EOF + +#define METACHARINC(x) ((void)((x) += (*(x) == Meta) ? 2 : 1)) +#endif + +/* + * Return unmetafied char from string (x is any char *). + * Used with MULTIBYTE_SUPPORT if the GF_MULTIBYTE is not + * in effect. + */ +#define UNMETA(x) (*(x) == Meta ? (x)[1] ^ 32 : *(x)) + +/* Add n more characters, ensuring there is enough space. */ + +enum { + PA_NOALIGN = 1, + PA_UNMETA = 2 +}; + +/**/ +static void +patadd(char *add, int ch, long n, int paflags) +{ + /* Make sure everything gets aligned unless we get PA_NOALIGN. */ + long newpatsize = patsize + n; + if (!(paflags & PA_NOALIGN)) + newpatsize = (newpatsize + sizeof(union upat) - 1) & + ~(sizeof(union upat) - 1); + if (patalloc < newpatsize) { + long newpatalloc = + 2*(newpatsize > patalloc ? newpatsize : patalloc); + patout = (char *)zrealloc((char *)patout, newpatalloc); + patcode = patout + patsize; + patalloc = newpatalloc; + } + patsize = newpatsize; + if (add) { + if (paflags & PA_UNMETA) { + /* + * Unmetafy and untokenize the string as we go. + * The Meta characters in add aren't counted in n. + */ + while (n--) { + if (itok(*add)) + *patcode++ = ztokens[*add++ - Pound]; + else if (*add == Meta) { + add++; + *patcode++ = *add++ ^ 32; + } else { + *patcode++ = *add++; + } + } + } else { + while (n--) + *patcode++ = *add++; + } + } else + *patcode++ = ch; + patcode = patout + patsize; +} + +static long rn_offs; +/* operates on pointers to union upat, returns a pointer */ +#define PATNEXT(p) ((rn_offs = P_NEXT(p)) ? \ + (P_OP(p) == P_BACK) ? \ + ((p)-rn_offs) : ((p)+rn_offs) : NULL) + +/* + * Set up zpc_special with characters that end a string segment. + * "Marker" cannot occur in the pattern we are compiling so + * is used to mark "invalid". + */ +static void +patcompcharsset(void) +{ + char *spp, *disp; + int i; + + /* Initialise enabled special characters */ + memcpy(zpc_special, zpc_chars, ZPC_COUNT); + /* Apply user disables from disable -p */ + for (i = 0, spp = zpc_special, disp = zpc_disables; + i < ZPC_COUNT; + i++, spp++, disp++) { + if (*disp) + *spp = Marker; + } + + if (!isset(EXTENDEDGLOB)) { + /* Extended glob characters are not active */ + zpc_special[ZPC_TILDE] = zpc_special[ZPC_HAT] = + zpc_special[ZPC_HASH] = Marker; + } + if (!isset(KSHGLOB)) { + /* + * Ksh glob characters are not active. + * * and ? are shared with normal globbing, but for their + * use here we are looking for a following Inpar. + */ + zpc_special[ZPC_KSH_QUEST] = zpc_special[ZPC_KSH_STAR] = + zpc_special[ZPC_KSH_PLUS] = zpc_special[ZPC_KSH_BANG] = + zpc_special[ZPC_KSH_BANG2] = zpc_special[ZPC_KSH_AT] = Marker; + } + /* + * Note that if we are using KSHGLOB, then we test for a following + * Inpar, not zpc_special[ZPC_INPAR]: the latter makes an Inpar on + * its own active. The zpc_special[ZPC_KSH_*] followed by any old Inpar + * discriminate ksh globbing. + */ + if (isset(SHGLOB)) { + /* + * Grouping and numeric ranges are not valid. + * We do allow alternation, however; it's needed for + * "case". This may not be entirely consistent. + * + * Don't disable Outpar: we may need to match the end of KSHGLOB + * parentheses and it would be difficult to tell them apart. + */ + zpc_special[ZPC_INPAR] = zpc_special[ZPC_INANG] = Marker; + } +} + +/* Called before parsing a set of file matchs to initialize flags */ + +/**/ +void +patcompstart(void) +{ + patcompcharsset(); + if (isset(CASEGLOB)) + patglobflags = 0; + else + patglobflags = GF_IGNCASE; + if (isset(MULTIBYTE)) + patglobflags |= GF_MULTIBYTE; +} + +/* + * Top level pattern compilation subroutine + * exp is a null-terminated, metafied string. + * inflags is an or of some PAT_* flags. + * endexp, if non-null, is set to a pointer to the end of the + * part of exp which was compiled. This is used when + * compiling patterns for directories which must be + * matched recursively. + */ + +/**/ +mod_export Patprog +patcompile(char *exp, int inflags, char **endexp) +{ + int flags = 0; + long len = 0; + long startoff; + Upat pscan; + char *lng, *strp = NULL; + Patprog p; + + queue_signals(); + + startoff = sizeof(struct patprog); + /* Ensure alignment of start of program string */ + startoff = (startoff + sizeof(union upat) - 1) & ~(sizeof(union upat) - 1); + + /* Allocate reasonable sized chunk if none, reduce size if too big */ + if (patalloc != P_DEF_ALLOC) + patout = (char *)zrealloc(patout, patalloc = P_DEF_ALLOC); + patcode = patout + startoff; + patsize = patcode - patout; + patstart = patparse = exp; + /* + * Note global patnpar numbers parentheses 1..9, while patnpar + * in struct is actual count of parentheses. + */ + patnpar = 1; + patflags = inflags & ~(PAT_PURES|PAT_HAS_EXCLUDP); + + if (!(patflags & PAT_FILE)) { + patcompcharsset(); + zpc_special[ZPC_SLASH] = Marker; + remnulargs(patparse); + if (isset(MULTIBYTE)) + patglobflags = GF_MULTIBYTE; + else + patglobflags = 0; + } + if (patflags & PAT_LCMATCHUC) + patglobflags |= GF_LCMATCHUC; + /* + * Have to be set now, since they get updated during compilation. + */ + ((Patprog)patout)->globflags = patglobflags; + + if (!(patflags & PAT_ANY)) { + /* Look for a really pure string, with no tokens at all. */ + if (!(patglobflags & ~GF_MULTIBYTE) +#ifdef __CYGWIN__ + /* + * If the OS treats files case-insensitively and we + * are looking at files, we don't need to use pattern + * matching to find the file. + */ + || (!(patglobflags & ~GF_IGNCASE) && (patflags & PAT_FILE)) +#endif + ) + { + /* + * Waah! I wish I understood this. + * Empty metafied strings have an initial Nularg. + * This never corresponds to a real character in + * a glob pattern or string, so skip it. + */ + if (*exp == Nularg) + exp++; + for (strp = exp; *strp && + (!(patflags & PAT_FILE) || *strp != '/') && !itok(*strp); + strp++) + ; + } + if (!strp || (*strp && *strp != '/')) { + /* No, do normal compilation. */ + strp = NULL; + if (patcompswitch(0, &flags) == 0) { + unqueue_signals(); + return NULL; + } + } else { + /* + * Yes, copy the string, and skip compilation altogether. + * Null terminate for the benefit of globbing. + * Leave metafied both for globbing and for our own + * efficiency. + */ + patparse = strp; + len = strp - exp; + patadd(exp, 0, len + 1, 0); + patout[startoff + len] = '\0'; + patflags |= PAT_PURES; + } + } + + /* end of compilation: safe to use pointers */ + p = (Patprog)patout; + p->startoff = startoff; + p->patstartch = '\0'; + p->globend = patglobflags; + p->flags = patflags; + p->mustoff = 0; + p->size = patsize; + p->patmlen = len; + p->patnpar = patnpar-1; + + if (!strp) { + pscan = (Upat)(patout + startoff); + + if (!(patflags & PAT_ANY) && P_OP(PATNEXT(pscan)) == P_END) { + /* only one top level choice */ + pscan = P_OPERAND(pscan); + + if (flags & P_PURESTR) { + /* + * The pattern can be matched with a simple strncmp/strcmp. + * Careful in case we've overwritten the node for the next ptr. + */ + char *dst = patout + startoff; + Upat next; + p->flags |= PAT_PURES; + for (; pscan; pscan = next) { + next = PATNEXT(pscan); + if (P_OP(pscan) == P_EXACTLY) { + char *opnd = P_LS_STR(pscan), *mtest; + long oplen = P_LS_LEN(pscan), ilen; + int nmeta = 0; + /* + * Unfortunately we unmetafied the string + * and we need to put any metacharacters + * back now we know it's a pure string. + * This shouldn't happen too often, it's + * just that there are some cases such + * as . and .. in files where we really + * need a pure string even if there are + * pattern characters flying around. + */ + for (mtest = opnd, ilen = oplen; ilen; + mtest++, ilen--) + if (imeta(*mtest)) + nmeta++; + if (nmeta) { + patadd(NULL, 0, nmeta, 0); + p = (Patprog)patout; + opnd = dupstring_wlen(opnd, oplen); + dst = patout + startoff; + } + + while (oplen--) { + if (imeta(*opnd)) { + *dst++ = Meta; + *dst++ = *opnd++ ^ 32; + } else { + *dst++ = *opnd++; + } + } + /* Only one string in a PAT_PURES, so now done. */ + break; + } + } + p->size = dst - patout; + /* patmlen is really strlen. We don't need a null. */ + p->patmlen = p->size - startoff; + } else { + /* starting point info */ + if (P_OP(pscan) == P_EXACTLY && !p->globflags && + P_LS_LEN(pscan)) + p->patstartch = *P_LS_STR(pscan); + /* + * Find the longest literal string in something expensive. + * This is itself not all that cheap if we have + * case-insensitive matching or approximation, so don't. + */ + if ((flags & P_HSTART) && !p->globflags) { + lng = NULL; + len = 0; + for (; pscan; pscan = PATNEXT(pscan)) + if (P_OP(pscan) == P_EXACTLY && + P_LS_LEN(pscan) >= len) { + lng = P_LS_STR(pscan); + len = P_LS_LEN(pscan); + } + if (lng) { + p->mustoff = lng - patout; + p->patmlen = len; + } + } + } + } + } + + /* + * The pattern was compiled in a fixed buffer: unless told otherwise, + * we stick the compiled pattern on the heap. This is necessary + * for files where we will often be compiling multiple segments at once. + * But if we get the ZDUP flag we always put it in zalloc()ed memory. + */ + if (patflags & PAT_ZDUP) { + Patprog newp = (Patprog)zalloc(patsize); + memcpy((char *)newp, (char *)p, patsize); + p = newp; + } else if (!(patflags & PAT_STATIC)) { + Patprog newp = (Patprog)zhalloc(patsize); + memcpy((char *)newp, (char *)p, patsize); + p = newp; + } + + if (endexp) + *endexp = patparse; + + unqueue_signals(); + return p; +} + +/* + * Main body or parenthesized subexpression in pattern + * Parenthesis (and any ksh_glob gubbins) will have been removed. + */ + +/**/ +static long +patcompswitch(int paren, int *flagp) +{ + long starter, br, ender, excsync = 0; + int parno = 0; + int flags, gfchanged = 0; + long savglobflags = (long)patglobflags; + Upat ptr; + + *flagp = 0; + + if (paren && (patglobflags & GF_BACKREF) && patnpar <= NSUBEXP) { + /* + * parenthesized: make an open node. + * We can only refer to the first nine parentheses. + * For any others, we just use P_OPEN on its own; there's + * no gain in arbitrarily limiting the number of parentheses. + */ + parno = patnpar++; + starter = patnode(P_OPEN + parno); + } else + starter = 0; + + br = patnode(P_BRANCH); + if (!patcompbranch(&flags, paren)) + return 0; + if (patglobflags != (int)savglobflags) + gfchanged++; + if (starter) + pattail(starter, br); + else + starter = br; + + *flagp |= flags & (P_HSTART|P_PURESTR); + + while (*patparse == zpc_chars[ZPC_BAR] || + (*patparse == zpc_special[ZPC_TILDE] && + (patparse[1] == '/' || + !memchr(zpc_special, patparse[1], ZPC_SEG_COUNT)))) { + int tilde = *patparse++ == zpc_special[ZPC_TILDE]; + long gfnode = 0, newbr; + + *flagp &= ~P_PURESTR; + + if (tilde) { + union upat up; + /* excsync remembers the P_EXCSYNC node before a chain of + * exclusions: all point back to this. only the + * original (non-excluded) branch gets a trailing P_EXCSYNC. + */ + if (!excsync) { + excsync = patnode(P_EXCSYNC); + patoptail(br, excsync); + } + /* + * By default, approximations are turned off in exclusions: + * we need to do this here as otherwise the code compiling + * the exclusion doesn't know if the flags have really + * changed if the error count gets restored. + */ + patglobflags &= ~0xff; + if (!(patflags & PAT_FILET) || paren) { + br = patnode(P_EXCLUDE); + } else { + /* + * At top level (paren == 0) in a file glob !(patflags + * &PAT_FILET) do the exclusion prepending the file path + * so far. We need to flag this to avoid unnecessarily + * copying the path. + */ + br = patnode(P_EXCLUDP); + patflags |= PAT_HAS_EXCLUDP; + } + up.p = NULL; + patadd((char *)&up, 0, sizeof(up), 0); + /* / is not treated as special if we are at top level */ + if (!paren && zpc_special[ZPC_SLASH] == '/') { + tilde++; + zpc_special[ZPC_SLASH] = Marker; + } + } else { + excsync = 0; + br = patnode(P_BRANCH); + /* + * The position of the following statements means globflags + * set in the main branch carry over to the exclusion. + */ + if (!paren) { + patglobflags = 0; + if (((Patprog)patout)->globflags) { + /* + * If at top level, we need to reinitialize flags to zero, + * since (#i)foo|bar only applies to foo and we stuck + * the #i into the global flags. + * We could have done it so that they only got set in the + * first branch, but it's quite convenient having any + * global flags set in the header and not buried in the + * pattern. (Or maybe it isn't and we should + * forget this bit and always stick in an explicit GFLAGS + * statement instead of using the header.) + * Also, this can't happen for file globs where there are + * no top-level |'s. + * + * No gfchanged, as nothing to follow branch at top + * level. + */ + union upat up; + gfnode = patnode(P_GFLAGS); + up.l = patglobflags; + patadd((char *)&up, 0, sizeof(union upat), 0); + } + } else { + patglobflags = (int)savglobflags; + } + } + newbr = patcompbranch(&flags, paren); + if (tilde == 2) { + /* restore special treatment of / */ + zpc_special[ZPC_SLASH] = '/'; + } + if (!newbr) + return 0; + if (gfnode) + pattail(gfnode, newbr); + if (!tilde && patglobflags != (int)savglobflags) + gfchanged++; + pattail(starter, br); + if (excsync) + patoptail(br, patnode(P_EXCEND)); + *flagp |= flags & P_HSTART; + } + + /* + * Make a closing node, hooking it to the end. + * Note that we can't optimize P_NOTHING out here, since another + * branch at that point would indicate the current choices continue, + * which they don't. + */ + ender = patnode(paren ? parno ? P_CLOSE+parno : P_NOTHING : P_END); + pattail(starter, ender); + + /* + * Hook the tails of the branches to the closing node, + * except for exclusions which terminate where they are. + */ + for (ptr = (Upat)patout + starter; ptr; ptr = PATNEXT(ptr)) + if (!P_ISEXCLUDE(ptr)) + patoptail(ptr-(Upat)patout, ender); + + /* check for proper termination */ + if ((paren && *patparse++ != Outpar) || + (!paren && *patparse && + !((patflags & PAT_FILE) && *patparse == '/'))) + return 0; + + if (paren && gfchanged) { + /* + * Restore old values of flags when leaving parentheses. + * gfchanged detects a change in any branch (except exclusions + * which are separate), since we need to emit this even if + * a later branch happened to put the flags back. + */ + pattail(ender, patnode(P_GFLAGS)); + patglobflags = (int)savglobflags; + patadd((char *)&savglobflags, 0, sizeof(long), 0); + } + + return starter; +} + +/* + * Compile something ended by Bar, Outpar, Tilde, or end of string. + * Note the BRANCH or EXCLUDE tag must already have been omitted: + * this returns the position of the operand of that. + */ + +/**/ +static long +patcompbranch(int *flagp, int paren) +{ + long chain, latest = 0, starter; + int flags = 0; + + *flagp = P_PURESTR; + + starter = chain = 0; + while (!memchr(zpc_special, *patparse, ZPC_SEG_COUNT) || + (*patparse == zpc_special[ZPC_TILDE] && patparse[1] != '/' && + memchr(zpc_special, patparse[1], ZPC_SEG_COUNT))) { + if ((*patparse == zpc_special[ZPC_INPAR] && + patparse[1] == zpc_special[ZPC_HASH]) || + (*patparse == zpc_special[ZPC_KSH_AT] && patparse[1] == Inpar && + patparse[2] == zpc_special[ZPC_HASH])) { + /* Globbing flags. */ + char *pp1 = patparse; + int oldglobflags = patglobflags, ignore; + long assert; + patparse += (*patparse == '@') ? 3 : 2; + if (!patgetglobflags(&patparse, &assert, &ignore)) + return 0; + if (!ignore) { + if (assert) { + /* + * Start/end assertion looking like flags, but + * actually handled as a normal node + */ + latest = patnode(assert); + flags = 0; + } else { + if (pp1 == patstart) { + /* Right at start of pattern, the simplest case. + * Put them into the flags and don't emit anything. + */ + ((Patprog)patout)->globflags = patglobflags; + continue; + } else if (!*patparse) { + /* Right at the end, so just leave the flags for + * the next Patprog in the chain to pick up. + */ + break; + } + /* + * Otherwise, we have to stick them in as a pattern + * matching nothing. + */ + if (oldglobflags != patglobflags) { + /* Flags changed */ + union upat up; + latest = patnode(P_GFLAGS); + up.l = patglobflags; + patadd((char *)&up, 0, sizeof(union upat), 0); + } else { + /* No effect. */ + continue; + } + } + } else if (!*patparse) + break; + else + continue; + } else if (*patparse == zpc_special[ZPC_HAT]) { + /* + * ^pat: anything but pat. For proper backtracking, + * etc., we turn this into (*~pat), except without the + * parentheses. + */ + patparse++; + latest = patcompnot(0, &flags); + } else + latest = patcomppiece(&flags, paren); + if (!latest) + return 0; + if (!starter) + starter = latest; + if (!(flags & P_PURESTR)) + *flagp &= ~P_PURESTR; + if (!chain) + *flagp |= flags & P_HSTART; + else + pattail(chain, latest); + chain = latest; + } + /* check if there was nothing in the loop, i.e. () */ + if (!chain) + starter = patnode(P_NOTHING); + + return starter; +} + +/* get glob flags, return 1 for success, 0 for failure */ + +/**/ +int +patgetglobflags(char **strp, long *assertp, int *ignore) +{ + char *nptr, *ptr = *strp; + zlong ret; + + *assertp = 0; + *ignore = 1; + /* (#X): assumes we are still positioned on the first X */ + for (; *ptr && *ptr != Outpar; ptr++) { + if (*ptr == 'q') { + /* Glob qualifiers, ignored in pattern code */ + while (*ptr && *ptr != Outpar) + ptr++; + break; + } else { + *ignore = 0; + switch (*ptr) { + case 'a': + /* Approximate matching, max no. of errors follows */ + ret = zstrtol(++ptr, &nptr, 10); + /* + * We can't have more than 254, because we need 255 to + * mark 254 errors in wbranch and exclude sync strings + * (hypothetically --- hope no-one tries it). + */ + if (ret < 0 || ret > 254 || ptr == nptr) + return 0; + patglobflags = (patglobflags & ~0xff) | (ret & 0xff); + ptr = nptr-1; + break; + + case 'l': + /* Lowercase in pattern matches lower or upper in target */ + patglobflags = (patglobflags & ~GF_IGNCASE) | GF_LCMATCHUC; + break; + + case 'i': + /* Fully case insensitive */ + patglobflags = (patglobflags & ~GF_LCMATCHUC) | GF_IGNCASE; + break; + + case 'I': + /* Restore case sensitivity */ + patglobflags &= ~(GF_LCMATCHUC|GF_IGNCASE); + break; + + case 'b': + /* Make backreferences */ + patglobflags |= GF_BACKREF; + break; + + case 'B': + /* Don't make backreferences */ + patglobflags &= ~GF_BACKREF; + break; + + case 'm': + /* Make references to complete match */ + patglobflags |= GF_MATCHREF; + break; + + case 'M': + /* Don't */ + patglobflags &= ~GF_MATCHREF; + break; + + case 's': + *assertp = P_ISSTART; + break; + + case 'e': + *assertp = P_ISEND; + break; + + case 'u': + patglobflags |= GF_MULTIBYTE; + break; + + case 'U': + patglobflags &= ~GF_MULTIBYTE; + break; + + default: + return 0; + } + } + } + if (*ptr != Outpar) + return 0; + /* Start/end assertions must appear on their own. */ + if (*assertp && (*strp)[1] != Outpar) + return 0; + *strp = ptr + 1; + return 1; +} + + +static const char *colon_stuffs[] = { + "alpha", "alnum", "ascii", "blank", "cntrl", "digit", "graph", + "lower", "print", "punct", "space", "upper", "xdigit", "IDENT", + "IFS", "IFSSPACE", "WORD", "INCOMPLETE", "INVALID", NULL +}; + +/* + * Handle the guts of a [:stuff:] character class element. + * start is the beginning of "stuff" and len is its length. + * This code is exported for the benefit of completion matching. + */ + +/**/ +mod_export int +range_type(char *start, int len) +{ + const char **csp; + + for (csp = colon_stuffs; *csp; csp++) { + if (strlen(*csp) == len && !strncmp(start, *csp, len)) + return (csp - colon_stuffs) + PP_FIRST; + } + + return PP_UNKWN; +} + + +/* + * Convert the contents of a [...] or [^...] expression (just the + * ... part) back into a string. This is used by compfiles -p/-P + * for some reason. The compiled form (a metafied string) is + * passed in rangestr. + * + * If outstr is non-NULL the compiled form is placed there. It + * must be sufficiently long. A terminating NULL is appended. + * + * Return the length required, not including the terminating NULL. + * + * TODO: this is non-multibyte for now. It will need to be defined + * appropriately with MULTIBYTE_SUPPORT when the completion matching + * code catches up. + */ + +/**/ +mod_export int +pattern_range_to_string(char *rangestr, char *outstr) +{ + int len = 0; + + while (*rangestr) { + if (imeta(STOUC(*rangestr))) { + int swtype = STOUC(*rangestr) - STOUC(Meta); + + if (swtype == 0) { + /* Ordindary metafied character */ + if (outstr) + { + *outstr++ = Meta; + *outstr++ = rangestr[1] ^ 32; + } + len += 2; + rangestr += 2; + } else if (swtype == PP_RANGE) { + /* X-Y range */ + int i; + + for (i = 0; i < 2; i++) { + if (*rangestr == Meta) { + if (outstr) { + *outstr++ = Meta; + *outstr++ = rangestr[1]; + } + len += 2; + rangestr += 2; + } else { + if (outstr) + *outstr++ = *rangestr; + len++; + rangestr++; + } + + if (i == 0) { + if (outstr) + *outstr++ = '-'; + len++; + } + } + } else if (swtype >= PP_FIRST && swtype <= PP_LAST) { + /* [:stuff:]; we need to output [: and :] */ + const char *found = colon_stuffs[swtype - PP_FIRST]; + int newlen = strlen(found); + if (outstr) { + strcpy(outstr, "[:"); + outstr += 2; + memcpy(outstr, found, newlen); + outstr += newlen; + strcpy(outstr, ":]"); + outstr += 2; + } + len += newlen + 4; + rangestr++; + } else { + /* shouldn't happen */ + DPUTS(1, "BUG: unknown PP_ code in pattern range"); + rangestr++; + } + } else { + /* ordinary character, guaranteed no Meta handling needed */ + if (outstr) + *outstr++ = *rangestr; + len++; + rangestr++; + } + } + + if (outstr) + *outstr = '\0'; + return len; +} + +/* + * compile a chunk such as a literal string or a [...] followed + * by a possible hash operator + */ + +/**/ +static long +patcomppiece(int *flagp, int paren) +{ + long starter = 0, next, op, opnd; + int flags, flags2, kshchar, len, ch, patch, nmeta; + int hash, count; + union upat up; + char *nptr, *str0, *ptr, *patprev; + zrange_t from, to; + char *charstart; + + flags = 0; + str0 = patprev = patparse; + for (;;) { + /* + * Check if we have a string. First, we need to make sure + * the string doesn't introduce a ksh-like parenthesized expression. + */ + kshchar = '\0'; + if (*patparse && patparse[1] == Inpar) { + if (*patparse == zpc_special[ZPC_KSH_PLUS]) + kshchar = STOUC('+'); + else if (*patparse == zpc_special[ZPC_KSH_BANG]) + kshchar = STOUC('!'); + else if (*patparse == zpc_special[ZPC_KSH_BANG2]) + kshchar = STOUC('!'); + else if (*patparse == zpc_special[ZPC_KSH_AT]) + kshchar = STOUC('@'); + else if (*patparse == zpc_special[ZPC_KSH_STAR]) + kshchar = STOUC('*'); + else if (*patparse == zpc_special[ZPC_KSH_QUEST]) + kshchar = STOUC('?'); + } + + /* + * If '(' is disabled as a pattern char, allow ')' as + * an ordinary string character if there are no parentheses to + * close. Don't allow it otherwise, it changes the syntax. + */ + if (zpc_special[ZPC_INPAR] != Marker || *patparse != Outpar || + paren) { + /* + * End of string (or no string at all) if ksh-type parentheses, + * or special character, unless that character is a tilde and + * the character following is an end-of-segment character. Thus + * tildes are not special if there is nothing following to + * be excluded. + * + * Don't look for X()-style kshglobs at this point; we've + * checked above for the case with parentheses and we don't + * want to match without parentheses. + */ + if (kshchar || + (memchr(zpc_special, *patparse, ZPC_NO_KSH_GLOB) && + (*patparse != zpc_special[ZPC_TILDE] || + patparse[1] == '/' || + !memchr(zpc_special, patparse[1], ZPC_SEG_COUNT)))) { + break; + } + } + + /* Remember the previous character for backtracking */ + patprev = patparse; + METACHARINC(patparse); + } + + if (patparse > str0) { + long slen = patparse - str0; + int morelen; + + /* Ordinary string: cancel kshchar lookahead */ + kshchar = '\0'; + /* + * Assume it matches a simple string until we find otherwise. + */ + flags |= P_PURESTR; + DPUTS(patparse == str0, "BUG: matched nothing in patcomppiece."); + /* more than one character matched? */ + morelen = (patprev > str0); + /* + * If we have more than one character, a following hash + * or (#c...) only applies to the last, so backtrack one character. + */ + if ((*patparse == zpc_special[ZPC_HASH] || + (*patparse == zpc_special[ZPC_INPAR] && + patparse[1] == zpc_special[ZPC_HASH] && + patparse[2] == 'c') || + (*patparse == zpc_special[ZPC_KSH_AT] && + patparse[1] == Inpar && + patparse[2] == zpc_special[ZPC_HASH] && + patparse[3] == 'c')) && morelen) + patparse = patprev; + /* + * If len is 1, we can't have an active # following, so doesn't + * matter that we don't make X in `XX#' simple. + */ + if (!morelen) + flags |= P_SIMPLE; + starter = patnode(P_EXACTLY); + + /* Get length of string without metafication. */ + nmeta = 0; + /* inherited from domatch, but why, exactly? */ + if (*str0 == Nularg) + str0++; + for (ptr = str0; ptr < patparse; ptr++) { + if (*ptr == Meta) { + nmeta++; + ptr++; + } + } + slen = (patparse - str0) - nmeta; + /* First add length, which is a long */ + patadd((char *)&slen, 0, sizeof(long), 0); + /* + * Then the string, not null terminated. + * Unmetafy and untokenize; pass the final length, + * which is what we need to allocate, i.e. not including + * a count for each Meta in the string. + */ + patadd(str0, 0, slen, PA_UNMETA); + nptr = P_LS_STR((Upat)patout + starter); + /* + * It's much simpler to turn off pure string mode for + * any case-insensitive or approximate matching; usually, + * that is correct, or they wouldn't have been turned on. + * However, we need to make sure we match a "." or ".." + * in a file name as a pure string. There's a minor bug + * that this will also apply to something like + * ..(#a1).. (i.e. the (#a1) has no effect), but if you're + * going to write funny patterns, you get no sympathy from me. + */ + if (patglobflags & +#ifdef __CYGWIN__ + /* + * As above: don't use pattern matching for files + * just because of case insensitivity if file system + * is known to be case insensitive. + * + * This is known to be necessary in at least one case: + * if "mount -c /" is in effect, so that drives appear + * directly under / instead of the usual /cygdrive, they + * aren't shown by readdir(). So it's vital we don't use + * globbing to find "/c", since that'll fail. + */ + ((patflags & PAT_FILE) ? + (0xFF|GF_LCMATCHUC) : + (0xFF|GF_LCMATCHUC|GF_IGNCASE)) +#else + (0xFF|GF_LCMATCHUC|GF_IGNCASE) +#endif + ) { + if (!(patflags & PAT_FILE)) + flags &= ~P_PURESTR; + else if (!(nptr[0] == '.' && + (slen == 1 || (nptr[1] == '.' && slen == 2)))) + flags &= ~P_PURESTR; + } + } else { + if (kshchar) + patparse++; + + patch = *patparse; + METACHARINC(patparse); + switch(patch) { + case Quest: + DPUTS(zpc_special[ZPC_QUEST] == Marker, + "Treating '?' as pattern character although disabled"); + flags |= P_SIMPLE; + starter = patnode(P_ANY); + break; + case Star: + DPUTS(zpc_special[ZPC_STAR] == Marker, + "Treating '*' as pattern character although disabled"); + /* kshchar is used as a sign that we can't have #'s. */ + kshchar = -1; + starter = patnode(P_STAR); + break; + case Inbrack: + DPUTS(zpc_special[ZPC_INBRACK] == Marker, + "Treating '[' as pattern character although disabled"); + flags |= P_SIMPLE; + if (*patparse == Hat || *patparse == Bang) { + patparse++; + starter = patnode(P_ANYBUT); + } else + starter = patnode(P_ANYOF); + /* + * []...] means match a "]" or other included characters. + * However, to be a bit helpful and for compatibility + * with other shells, don't take in that sense if + * there's no further "]". That's still imperfect, + * but it's all we can do --- we're required to + * treat [$var]*[$var]with empty var as [ ... ] + * containing "]*[". + */ + if (*patparse == Outbrack && strchr(patparse+1, Outbrack)) { + patparse++; + patadd(NULL, ']', 1, PA_NOALIGN); + } + while (*patparse && *patparse != Outbrack) { + /* Meta is not a token */ + if (*patparse == Inbrack && patparse[1] == ':' && + (nptr = strchr(patparse+2, ':')) && + nptr[1] == Outbrack) { + /* Posix range. */ + patparse += 2; + len = nptr - patparse; + ch = range_type(patparse, len); + patparse = nptr + 2; + if (ch != PP_UNKWN) + patadd(NULL, STOUC(Meta) + ch, 1, PA_NOALIGN); + continue; + } + charstart = patparse; + METACHARINC(patparse); + + if (*patparse == Dash && patparse[1] && + patparse[1] != Outbrack) { + patadd(NULL, STOUC(Meta)+PP_RANGE, 1, PA_NOALIGN); + if (itok(*charstart)) { + patadd(0, STOUC(ztokens[*charstart - Pound]), 1, + PA_NOALIGN); + } else { + patadd(charstart, 0, patparse-charstart, PA_NOALIGN); + } + charstart = ++patparse; /* skip Dash token */ + METACHARINC(patparse); + } + if (itok(*charstart)) { + patadd(0, STOUC(ztokens[*charstart - Pound]), 1, + PA_NOALIGN); + } else { + patadd(charstart, 0, patparse-charstart, PA_NOALIGN); + } + } + if (*patparse != Outbrack) + return 0; + patparse++; + /* terminate null string and fix alignment */ + patadd(NULL, 0, 1, 0); + break; + case Inpar: + DPUTS(!kshchar && zpc_special[ZPC_INPAR] == Marker, + "Treating '(' as pattern character although disabled"); + DPUTS(isset(SHGLOB) && !kshchar, + "Treating bare '(' as pattern character with SHGLOB"); + if (kshchar == '!') { + /* This is nasty, we should really either handle all + * kshglobbing below or here. But most of the + * others look like non-ksh patterns, while this one + * doesn't, so we handle it here and leave the rest. + * We treat it like an extendedglob ^, except that + * it goes into parentheses. + * + * If we did do kshglob here, we could support + * the old behaviour that things like !(foo)## + * work, but it makes the code more complicated at + * the expense of allowing the user to do things + * they shouldn't. + */ + if (!(starter = patcompnot(1, &flags2))) + return 0; + } else if (!(starter = patcompswitch(1, &flags2))) + return 0; + flags |= flags2 & P_HSTART; + break; + case Inang: + /* Numeric glob */ + DPUTS(zpc_special[ZPC_INANG] == Marker, + "Treating '<' as pattern character although disabled"); + DPUTS(isset(SHGLOB), "Treating <..> as numeric range with SHGLOB"); + len = 0; /* beginning present 1, end present 2 */ + if (idigit(*patparse)) { + from = (zrange_t) zstrtol((char *)patparse, + (char **)&nptr, 10); + patparse = nptr; + len |= 1; + } + DPUTS(!IS_DASH(*patparse), "BUG: - missing from numeric glob"); + patparse++; + if (idigit(*patparse)) { + to = (zrange_t) zstrtol((char *)patparse, + (char **)&nptr, 10); + patparse = nptr; + len |= 2; + } + if (*patparse != Outang) + return 0; + patparse++; + switch(len) { + case 3: + starter = patnode(P_NUMRNG); + patadd((char *)&from, 0, sizeof(from), 0); + patadd((char *)&to, 0, sizeof(to), 0); + break; + case 2: + starter = patnode(P_NUMTO); + patadd((char *)&to, 0, sizeof(to), 0); + break; + case 1: + starter = patnode(P_NUMFROM); + patadd((char *)&from, 0, sizeof(from), 0); + break; + case 0: + starter = patnode(P_NUMANY); + break; + } + /* This can't be simple, because it isn't. + * Mention in manual that matching digits with [...] + * is more efficient. + */ + break; + case Pound: + DPUTS(zpc_special[ZPC_HASH] == Marker, + "Treating '#' as pattern character although disabled"); + DPUTS(!isset(EXTENDEDGLOB), "BUG: # not treated as string"); + /* + * A hash here is an error; it should follow something + * repeatable. + */ + return 0; + break; + case Bnullkeep: + /* + * Marker for restoring a backslash in output: + * does not match a character. + */ + next = patcomppiece(flagp, paren); + /* + * Can't match a pure string since we need to do this + * as multiple chunks. + */ + *flagp &= ~P_PURESTR; + return next; + break; +#ifdef DEBUG + default: + dputs("BUG: character not handled in patcomppiece"); + return 0; + break; +#endif + } + } + + count = 0; + if (!(hash = (*patparse == zpc_special[ZPC_HASH])) && + !(count = ((*patparse == zpc_special[ZPC_INPAR] && + patparse[1] == zpc_special[ZPC_HASH] && + patparse[2] == 'c') || + (*patparse == zpc_special[ZPC_KSH_AT] && + patparse[1] == Inpar && + patparse[2] == zpc_special[ZPC_HASH] && + patparse[3] == 'c'))) && + (kshchar <= 0 || kshchar == '@' || kshchar == '!')) { + *flagp = flags; + return starter; + } + + /* too much at once doesn't currently work */ + if (kshchar && (hash || count)) + return 0; + + if (kshchar == '*') { + op = P_ONEHASH; + *flagp = P_HSTART; + } else if (kshchar == '+') { + op = P_TWOHASH; + *flagp = P_HSTART; + } else if (kshchar == '?') { + op = 0; + *flagp = 0; + } else if (count) { + op = P_COUNT; + patparse += 3; + *flagp = P_HSTART; + } else if (*++patparse == zpc_special[ZPC_HASH]) { + op = P_TWOHASH; + patparse++; + *flagp = P_HSTART; + } else { + op = P_ONEHASH; + *flagp = P_HSTART; + } + + /* + * Note optimizations with pointers into P_NOTHING branches: some + * should logically point to next node after current piece. + * + * Backtracking is also encoded in a slightly obscure way: the + * code emitted ensures we test the non-empty branch of complex + * patterns before the empty branch on each repetition. Hence + * each time we fail on a non-empty branch, we try the empty branch, + * which is equivalent to backtracking. + */ + if (op == P_COUNT) { + /* (#cN,M) */ + union upat countargs[P_CT_OPERAND]; + char *opp = patparse; + + countargs[0].l = P_COUNT; + countargs[P_CT_CURRENT].l = 0L; + countargs[P_CT_MIN].l = (long)zstrtol(patparse, &patparse, 10); + if (patparse == opp) { + /* missing number treated as zero */ + countargs[P_CT_MIN].l = 0L; + } + if (*patparse != ',' && *patparse != Comma) { + /* either max = min or error */ + if (*patparse != Outpar) + return 0; + countargs[P_CT_MAX].l = countargs[P_CT_MIN].l; + } else { + opp = ++patparse; + countargs[P_CT_MAX].l = (long)zstrtol(patparse, &patparse, 10); + if (*patparse != Outpar) + return 0; + if (patparse == opp) { + /* missing number treated as infinity: record as -1 */ + countargs[P_CT_MAX].l = -1L; + } + } + patparse++; + countargs[P_CT_PTR].p = NULL; + /* Mark this chain as a min/max count... */ + patinsert(P_COUNTSTART, starter, (char *)countargs, sizeof(countargs)); + /* + * The next of the operand is a loop back to the P_COUNT. This is + * how we get recursion for the count. We don't loop back to + * the P_COUNTSTART; that's used for initialising the count + * and saving and restoring the count for any enclosing use + * of the match. + */ + opnd = P_OPERAND(starter) + P_CT_OPERAND; + pattail(opnd, patnode(P_BACK)); + pattail(opnd, P_OPERAND(starter)); + /* + * The next of the counter operators is what follows the + * closure. + * This handles matching of the tail. + */ + next = patnode(P_NOTHING); + pattail(starter, next); + pattail(P_OPERAND(starter), next); + } else if ((flags & P_SIMPLE) && (op == P_ONEHASH || op == P_TWOHASH) && + P_OP((Upat)patout+starter) == P_ANY) { + /* Optimize ?# to *. Silly thing to do, since who would use + * use ?# ? But it makes the later code shorter. + */ + Upat uptr = (Upat)patout + starter; + if (op == P_TWOHASH) { + /* ?## becomes ?* */ + uptr->l = (uptr->l & ~0xff) | P_ANY; + pattail(starter, patnode(P_STAR)); + } else { + uptr->l = (uptr->l & ~0xff) | P_STAR; + } + } else if ((flags & P_SIMPLE) && op && !(patglobflags & 0xff)) { + /* Simplify, but not if we need to look for approximations. */ + patinsert(op, starter, NULL, 0); + } else if (op == P_ONEHASH) { + /* Emit x# as (x&|), where & means "self". */ + up.p = NULL; + patinsert(P_WBRANCH, starter, (char *)&up, sizeof(up)); + /* Either x */ + patoptail(starter, patnode(P_BACK)); /* and loop */ + patoptail(starter, starter); /* back */ + pattail(starter, patnode(P_BRANCH)); /* or */ + pattail(starter, patnode(P_NOTHING)); /* null. */ + } else if (op == P_TWOHASH) { + /* Emit x## as x(&|) where & means "self". */ + next = patnode(P_WBRANCH); /* Either */ + up.p = NULL; + patadd((char *)&up, 0, sizeof(up), 0); + pattail(starter, next); + pattail(patnode(P_BACK), starter); /* loop back */ + pattail(next, patnode(P_BRANCH)); /* or */ + pattail(starter, patnode(P_NOTHING)); /* null. */ + } else if (kshchar == '?') { + /* Emit ?(x) as (x|) */ + patinsert(P_BRANCH, starter, NULL, 0); /* Either x */ + pattail(starter, patnode(P_BRANCH)); /* or */ + next = patnode(P_NOTHING); /* null */ + pattail(starter, next); + patoptail(starter, next); + } + if (*patparse == zpc_special[ZPC_HASH]) + return 0; + + return starter; +} + +/* + * Turn a ^foo (paren = 0) or !(foo) (paren = 1) into *~foo with + * parentheses if necessary. As you see, that's really quite easy. + */ + +/**/ +static long +patcompnot(int paren, int *flagsp) +{ + union upat up; + long excsync, br, excl, n, starter; + int dummy; + + /* Here, we're matching a star at the start. */ + *flagsp = P_HSTART; + + starter = patnode(P_BRANCH); + br = patnode(P_STAR); + excsync = patnode(P_EXCSYNC); + pattail(br, excsync); + pattail(starter, excl = patnode(P_EXCLUDE)); + up.p = NULL; + patadd((char *)&up, 0, sizeof(up), 0); + if (!(br = (paren ? patcompswitch(1, &dummy) : patcompbranch(&dummy, 0)))) + return 0; + pattail(br, patnode(P_EXCEND)); + n = patnode(P_NOTHING); /* just so much easier */ + pattail(excsync, n); + pattail(excl, n); + + return starter; +} + +/* Emit a node */ + +/**/ +static long +patnode(long op) +{ + long starter = (Upat)patcode - (Upat)patout; + union upat up; + + up.l = op; + patadd((char *)&up, 0, sizeof(union upat), 0); + return starter; +} + +/* + * insert an operator in front of an already emitted operand: + * we relocate the operand. there had better be nothing else after. + */ + +/**/ +static void +patinsert(long op, int opnd, char *xtra, int sz) +{ + char *src, *dst, *opdst; + union upat buf, *lptr; + + buf.l = 0; + patadd((char *)&buf, 0, sizeof(buf), 0); + if (sz) + patadd(xtra, 0, sz, 0); + src = patcode - sizeof(union upat) - sz; + dst = patcode; + opdst = patout + opnd * sizeof(union upat); + while (src > opdst) + *--dst = *--src; + + /* A cast can't be an lvalue */ + lptr = (Upat)opdst; + lptr->l = op; + opdst += sizeof(union upat); + while (sz--) + *opdst++ = *xtra++; +} + +/* set the 'next' pointer at the end of a node chain */ + +/**/ +static void +pattail(long p, long val) +{ + Upat scan, temp; + long offset; + + scan = (Upat)patout + p; + for (;;) { + if (!(temp = PATNEXT(scan))) + break; + scan = temp; + } + + offset = (P_OP(scan) == P_BACK) + ? (scan - (Upat)patout) - val : val - (scan - (Upat)patout); + + scan->l |= offset << 8; +} + +/* do pattail, but on operand of first argument; nop if operandless */ + +/**/ +static void +patoptail(long p, long val) +{ + Upat ptr = (Upat)patout + p; + int op = P_OP(ptr); + if (!p || !P_ISBRANCH(ptr)) + return; + if (op == P_BRANCH) + pattail(P_OPERAND(p), val); + else + pattail(P_OPERAND(p) + 1, val); +} + + +/* + * Run a pattern. + */ +struct rpat { + char *patinstart; /* Start of input string */ + char *patinend; /* End of input string */ + char *patinput; /* String input pointer */ + char *patinpath; /* Full path for use with ~ exclusions */ + int patinlen; /* Length of last successful match. + * Includes count of Meta characters. + */ + + char *patbeginp[NSUBEXP]; /* Pointer to backref beginnings */ + char *patendp[NSUBEXP]; /* Pointer to backref ends */ + int parsfound; /* parentheses (with backrefs) found */ + + int globdots; /* Glob initial dots? */ +}; + +static struct rpat pattrystate; + +#define patinstart (pattrystate.patinstart) +#define patinend (pattrystate.patinend) +#define patinput (pattrystate.patinput) +#define patinpath (pattrystate.patinpath) +#define patinlen (pattrystate.patinlen) +#define patbeginp (pattrystate.patbeginp) +#define patendp (pattrystate.patendp) +#define parsfound (pattrystate.parsfound) +#define globdots (pattrystate.globdots) + + +/* + * Character functions operating on unmetafied strings. + */ +#ifdef MULTIBYTE_SUPPORT + +/* Get a character from the start point in a string */ +#define CHARREF(x, y) charref((x), (y), (int *)NULL) +static wchar_t +charref(char *x, char *y, int *zmb_ind) +{ + wchar_t wc; + size_t ret; + + if (!(patglobflags & GF_MULTIBYTE) || !(STOUC(*x) & 0x80)) + return (wchar_t) STOUC(*x); + + ret = mbrtowc(&wc, x, y-x, &shiftstate); + + if (ret == MB_INVALID || ret == MB_INCOMPLETE) { + /* Error. */ + /* Reset the shift state for next time. */ + memset(&shiftstate, 0, sizeof(shiftstate)); + if (zmb_ind) + *zmb_ind = (ret == MB_INVALID) ? ZMB_INVALID : ZMB_INCOMPLETE; + return WCHAR_INVALID(*x); + } + + if (zmb_ind) + *zmb_ind = ZMB_VALID; + return wc; +} + +/* Get a pointer to the next character */ +#define CHARNEXT(x, y) charnext((x), (y)) +static char * +charnext(char *x, char *y) +{ + wchar_t wc; + size_t ret; + + if (!(patglobflags & GF_MULTIBYTE) || !(STOUC(*x) & 0x80)) + return x + 1; + + ret = mbrtowc(&wc, x, y-x, &shiftstate); + + if (ret == MB_INVALID || ret == MB_INCOMPLETE) { + /* Error. Treat as single byte. */ + /* Reset the shift state for next time. */ + memset(&shiftstate, 0, sizeof(shiftstate)); + return x + 1; + } + + /* Nulls here are normal characters */ + return x + (ret ? ret : 1); +} + +/* Increment a pointer past the current character. */ +#define CHARINC(x, y) ((x) = charnext((x), (y))) + + +/* Get a character and increment */ +#define CHARREFINC(x, y, z) charrefinc(&(x), (y), (z)) +static wchar_t +charrefinc(char **x, char *y, int *z) +{ + wchar_t wc; + size_t ret; + + if (!(patglobflags & GF_MULTIBYTE) || !(STOUC(**x) & 0x80)) + return (wchar_t) STOUC(*(*x)++); + + ret = mbrtowc(&wc, *x, y-*x, &shiftstate); + + if (ret == MB_INVALID || ret == MB_INCOMPLETE) { + /* Error. Treat as single byte, but flag. */ + *z = 1; + /* Reset the shift state for next time. */ + memset(&shiftstate, 0, sizeof(shiftstate)); + return WCHAR_INVALID(*(*x)++); + } + + /* Nulls here are normal characters */ + *x += ret ? ret : 1; + + return wc; +} + + +/* + * Counter the number of characters between two pointers, smaller first + * + * This is used when setting values in parameters, so we obey + * the MULTIBYTE option (even if it's been overridden locally). + */ +#define CHARSUB(x,y) charsub(x, y) +static ptrdiff_t +charsub(char *x, char *y) +{ + ptrdiff_t res = 0; + size_t ret; + wchar_t wc; + + if (!isset(MULTIBYTE)) + return y - x; + + while (x < y) { + ret = mbrtowc(&wc, x, y-x, &shiftstate); + + if (ret == MB_INVALID || ret == MB_INCOMPLETE) { + /* Error. Treat remainder as single characters */ + return res + (y - x); + } + + /* Treat nulls as normal characters */ + if (!ret) + ret = 1; + res++; + x += ret; + } + + return res; +} + +#else /* no MULTIBYTE_SUPPORT */ + +/* Get a character from the start point in a string */ +#define CHARREF(x, y) (STOUC(*(x))) +/* Get a pointer to the next character */ +#define CHARNEXT(x, y) ((x)+1) +/* Increment a pointer past the current character. */ +#define CHARINC(x, y) ((x)++) +/* Get a character and increment */ +#define CHARREFINC(x, y, z) (STOUC(*(x)++)) +/* Counter the number of characters between two pointers, smaller first */ +#define CHARSUB(x,y) ((y) - (x)) + +#endif /* MULTIBYTE_SUPPORT */ + +/* + * The following need to be accessed in the globbing scanner for + * a multi-component file path. See horror story in glob.c. + */ +/**/ +int errsfound; /* Total error count so far */ + +/**/ +int forceerrs; /* Forced maximum error count */ + +/**/ +void +pattrystart(void) +{ + forceerrs = -1; + errsfound = 0; +} + +/* + * Fix up string length stuff. + * + * If we call patallocstr() with "force" to set things up early, it's + * done there, else it's done in pattryrefs(). The reason for the + * difference is in the latter case we may not be relying on + * patallocstr() having an effect. + */ + +/**/ +static void +patmungestring(char **string, int *stringlen, int *unmetalenin) +{ + /* + * Special signalling of empty tokenised string. + */ + if (*stringlen > 0 && **string == Nularg) { + (*string)++; + /* + * If we don't have an unmetafied length + * and need it (we may not) we'll get it later. + */ + if (*unmetalenin > 0) + (*unmetalenin)--; + if (*stringlen > 0) + (*stringlen)--; + } + + /* Ensure we have a metafied length */ + if (*stringlen < 0) + *stringlen = strlen(*string); +} + +/* + * Allocate memeory for pattern match. Note this is specific to use + * of pattern *and* trial string. + * + * Unmetafy a trial string for use in pattern matching, if needed. + * + * If it is needed, returns a heap allocated string; if not needed, + * returns NULL. + * + * prog is the pattern to be executed. + * string is the metafied trial string. + * stringlen is it's length; it will be calculated if it's negative + * (this is a simple strlen()). + * unmetalen is the unmetafied length of the string, may be -1. + * force is 1 if we always unmetafy: this is useful if we are going + * to try again with different versions of the string. If this is + * called from pattryrefs() we don't force unmetafication as it won't + * be optimal. This option should be used if the resulting + * patstralloc is going to be passed to pattrylen() / pattryrefs(). + * In patstralloc (supplied by caller, must last until last pattry is done) + * unmetalen is the unmetafied length of the string; it will be + * calculated if the input value is negative. + * unmetalenp is the umetafied length of a path segment preceeding + * the trial string needed for file mananagement; it is calculated as + * needed so does not need to be initialised. + * alloced is the memory allocated on the heap --- same as return value from + * function. + */ +/**/ +mod_export +char *patallocstr(Patprog prog, char *string, int stringlen, int unmetalen, + int force, Patstralloc patstralloc) +{ + int needfullpath; + + if (force) + patmungestring(&string, &stringlen, &unmetalen); + + /* + * For a top-level ~-exclusion, we will need the full + * path to exclude, so copy the path so far and append the + * current test string. + */ + needfullpath = (prog->flags & PAT_HAS_EXCLUDP) && pathpos; + + /* Get the length of the full string when unmetafied. */ + if (unmetalen < 0) + patstralloc->unmetalen = ztrsub(string + stringlen, string); + else + patstralloc->unmetalen = unmetalen; + if (needfullpath) { + patstralloc->unmetalenp = ztrsub(pathbuf + pathpos, pathbuf); + if (!patstralloc->unmetalenp) + needfullpath = 0; + } else + patstralloc->unmetalenp = 0; + /* Initialise cache area */ + patstralloc->progstrunmeta = NULL; + patstralloc->progstrunmetalen = 0; + + DPUTS(needfullpath && (prog->flags & (PAT_PURES|PAT_ANY)), + "rum sort of file exclusion"); + /* + * Partly for efficiency, and partly for the convenience of + * globbing, we don't unmetafy pure string patterns, and + * there's no reason to if the pattern is just a *. + */ + if (force || + (!(prog->flags & (PAT_PURES|PAT_ANY)) + && (needfullpath || patstralloc->unmetalen != stringlen))) { + /* + * We need to copy if we need to prepend the path so far + * (in which case we copy both chunks), or if we have + * Meta characters. + */ + char *dst, *ptr; + int i, icopy, ncopy; + + dst = patstralloc->alloced = + zhalloc(patstralloc->unmetalen + patstralloc->unmetalenp); + + if (needfullpath) { + /* loop twice, copy path buffer first time */ + ptr = pathbuf; + ncopy = patstralloc->unmetalenp; + } else { + /* just loop once, copy string with unmetafication */ + ptr = string; + ncopy = patstralloc->unmetalen; + } + for (icopy = 0; icopy < 2; icopy++) { + for (i = 0; i < ncopy; i++) { + if (*ptr == Meta) { + ptr++; + *dst++ = *ptr++ ^ 32; + } else { + *dst++ = *ptr++; + } + } + if (!needfullpath) + break; + /* next time append test string to path so far */ + ptr = string; + ncopy = patstralloc->unmetalen; + } + } + else + { + patstralloc->alloced = NULL; + } + + return patstralloc->alloced; +} + + +/* + * Test prog against null-terminated, metafied string. + */ + +/**/ +mod_export int +pattry(Patprog prog, char *string) +{ + return pattryrefs(prog, string, -1, -1, NULL, 0, NULL, NULL, NULL); +} + +/* + * Test prog against string of given length, no null termination + * but still metafied at this point. offset gives an offset + * to include in reported match indices + */ + +/**/ +mod_export int +pattrylen(Patprog prog, char *string, int len, int unmetalen, + Patstralloc patstralloc, int offset) +{ + return pattryrefs(prog, string, len, unmetalen, patstralloc, offset, + NULL, NULL, NULL); +} + +/* + * Test prog against string with given lengths. The input + * string is metafied; stringlen is the raw string length, and + * unmetalen the number of characters in the original string (some + * of which may now be metafied). Either value may be -1 + * to indicate a null-terminated string which will be counted. Note + * there may be a severe penalty for this if a lot of matching is done + * on one string. + * + * If patstralloc is not NULL it is used to optimise unmetafication + * of a trial string that may be passed (or any substring may be passed) to + * pattryrefs multiple times or the same pattern (N.B. so patstralloc + * depends on both prog *and* the trial string). This should only be + * done if there is no path prefix (pathpos == 0) as otherwise the path + * buffer and unmetafied string may not match. To do this, + * patallocstr() is callled (use force = 1 to ensure it is alway + * unmetafied); paststralloc points to existing storage. Memory is + * on the heap. + * + * patstralloc->alloced and patstralloc->unmetalen contain the + * unmetafied string and its length. In that case, the rules for the + * earlier arguments change: + * - string is an unmetafied string + * - stringlen is its unmetafied (i.e. actual) length + * - unmetalenin is not used. + * string and stringlen may refer to arbitrary substrings of + * patstralloc->alloced without any internal modification to patstralloc. + * + * patoffset is the position in the original string (not seen by + * the pattern module) at which we are trying to match. + * This is added in to the positions recorded in patbeginp and patendp + * when we are looking for substrings. Currently this only happens + * in the parameter substitution code. It refers to a real character + * offset, i.e. is already in the form ready for presentation to the + * general public --- this is necessary as we don't have the + * information to convert it down here. + * + * Note this is a character offset, i.e. a single possibly metafied and + * possibly multibyte character counts as 1. + * + * The last three arguments are used to report the positions for the + * backreferences. On entry, *nump should contain the maximum number + * of positions to report. In this case the match, mbegin, mend + * arrays are not altered. + * + * If nump is NULL but endp is not NULL, then *endp is set to the + * end position of the match, taking into account patinstart. + */ + +/**/ +mod_export int +pattryrefs(Patprog prog, char *string, int stringlen, int unmetalenin, + Patstralloc patstralloc, int patoffset, + int *nump, int *begp, int *endp) +{ + int i, maxnpos = 0, ret; + int origlen; + char **sp, **ep, *ptr; + char *progstr = (char *)prog + prog->startoff; + struct patstralloc patstralloc_struct; + + if (nump) { + maxnpos = *nump; + *nump = 0; + } + + if (!patstralloc) + patmungestring(&string, &stringlen, &unmetalenin); + origlen = stringlen; + + if (patstralloc) { + DPUTS(!patstralloc->alloced, + "External unmetafy didn't actually unmetafy."); + DPUTS(patstralloc->unmetalenp, + "Ooh-err: pathpos with external unmetafy. I have bad vibes."); + patinpath = NULL; + patinstart = string; + /* stringlen is unmetafied length; unmetalenin is ignored */ + } else { + patstralloc = &patstralloc_struct; + if (patallocstr(prog, string, stringlen, unmetalenin, 0, patstralloc)) { + patinstart = patstralloc->alloced + patstralloc->unmetalenp; + stringlen = patstralloc->unmetalen; + } else + patinstart = string; + if (patstralloc->unmetalenp) + patinpath = patstralloc->alloced; + else + patinpath = NULL; + } + + patflags = prog->flags; + patinend = patinstart + stringlen; + /* + * From now on we do not require NULL termination of + * the test string. There should also be no more references + * to the variable string. + */ + + if (prog->flags & (PAT_PURES|PAT_ANY)) { + /* + * Either we are testing against a pure string, + * or we can match anything at all. + */ + int pstrlen; + char *pstr; + if (patstralloc->alloced) + { + /* + * Unmetafied; we need pattern sring that's also unmetafied. + * We'll cache it in the patstralloc structure. + * Note it's on the heap. + */ + if (!patstralloc->progstrunmeta) + { + patstralloc->progstrunmeta = + dupstrpfx(progstr, (int)prog->patmlen); + unmetafy(patstralloc->progstrunmeta, + &patstralloc->progstrunmetalen); + } + pstr = patstralloc->progstrunmeta; + pstrlen = patstralloc->progstrunmetalen; + } + else + { + /* Metafied. */ + pstr = progstr; + pstrlen = (int)prog->patmlen; + } + if (prog->flags & PAT_ANY) { + /* + * Optimisation for a single "*": always matches + * (except for no_glob_dots, see below). + */ + ret = 1; + } else { + /* + * Testing a pure string. See if initial + * components match. + */ + int lendiff = stringlen - pstrlen; + if (lendiff < 0) { + /* No, the pattern string is too long. */ + ret = 0; + } else if (!memcmp(pstr, patinstart, pstrlen)) { + /* + * Initial component matches. Matches either + * if lengths are the same or we are not anchored + * to the end of the string. + */ + ret = !lendiff || (prog->flags & PAT_NOANCH); + } else { + /* No match. */ + ret = 0; + } + } + if (ret) { + /* + * For files, we won't match initial "."s unless + * glob_dots is set. + */ + if ((prog->flags & PAT_NOGLD) && *patinstart == '.') { + ret = 0; + } else { + /* + * Remember the length in case used for ${..#..} etc. + * In this case, we didn't unmetafy the pattern string + * In the orignal structure, but it might be unmetafied + * for use with an unmetafied test string. + */ + patinlen = pstrlen; + /* if matching files, must update globbing flags */ + patglobflags = prog->globend; + + if ((patglobflags & GF_MATCHREF) && + !(patflags & PAT_FILE)) { + char *str; + int mlen; + + if (patstralloc->alloced) { + /* + * Unmetafied: pstrlen contains unmetafied + * length in bytes. + */ + str = metafy(patinstart, pstrlen, META_DUP); + mlen = CHARSUB(patinstart, patinstart + pstrlen); + } else { + str = ztrduppfx(patinstart, patinlen); + /* + * Count the characters. We're not using CHARSUB() + * because the string is still metafied. + */ + MB_METACHARINIT(); + mlen = MB_METASTRLEN2END(patinstart, 0, + patinstart + patinlen); + } + + setsparam("MATCH", str); + setiparam("MBEGIN", + (zlong)(patoffset + !isset(KSHARRAYS))); + setiparam("MEND", + (zlong)(mlen + patoffset + + !isset(KSHARRAYS) - 1)); + } + } + } + } else { + /* + * Test for a `must match' string, unless we're scanning for a match + * in which case we don't need to do this each time. + */ + ret = 1; + if (!(prog->flags & PAT_SCAN) && prog->mustoff) + { + char *testptr; /* start pointer into test string */ + char *teststop; /* last point from which we can match */ + char *patptr = (char *)prog + prog->mustoff; + int patlen = prog->patmlen; + int found = 0; + + if (patlen > stringlen) { + /* Too long, can't match. */ + ret = 0; + } else { + teststop = patinend - patlen; + + for (testptr = patinstart; testptr <= teststop; testptr++) + { + if (!memcmp(testptr, patptr, patlen)) { + found = 1; + break; + } + } + + if (!found) + ret = 0; + } + } + if (!ret) + return 0; + + patglobflags = prog->globflags; + if (!(patflags & PAT_FILE)) { + forceerrs = -1; + errsfound = 0; + } + globdots = !(patflags & PAT_NOGLD); + parsfound = 0; + + patinput = patinstart; + + if (patmatch((Upat)progstr)) { + /* + * we were lazy and didn't save the globflags if an exclusion + * failed, so set it now + */ + patglobflags = prog->globend; + + /* + * Record length of successful match, including Meta + * characters. Do it here so that patmatchlen() can return + * it even if we delete the pattern strings. + */ + patinlen = patinput - patinstart; + /* + * Optimization: if we didn't find any Meta characters + * to begin with, we don't need to look for them now. + * + * For patstralloc pased in, we want the unmetafied length. + */ + if (patstralloc == &patstralloc_struct && + patstralloc->unmetalen != origlen) { + for (ptr = patinstart; ptr < patinput; ptr++) + if (imeta(*ptr)) + patinlen++; + } + + /* + * Should we clear backreferences and matches on a failed + * match? + */ + if ((patglobflags & GF_MATCHREF) && !(patflags & PAT_FILE)) { + /* + * m flag: for global match. This carries no overhead + * in the pattern matching part. + * + * Remember the test pattern is already unmetafied. + */ + char *str; + int mlen = CHARSUB(patinstart, patinput); + + str = metafy(patinstart, patinput - patinstart, META_DUP); + setsparam("MATCH", str); + setiparam("MBEGIN", (zlong)(patoffset + !isset(KSHARRAYS))); + setiparam("MEND", + (zlong)(mlen + patoffset + + !isset(KSHARRAYS) - 1)); + } + if (prog->patnpar && nump) { + /* + * b flag: for backreferences using parentheses. Reported + * directly. + */ + *nump = prog->patnpar; + + sp = patbeginp; + ep = patendp; + + for (i = 0; i < prog->patnpar && i < maxnpos; i++) { + if (parsfound & (1 << i)) { + if (begp) + *begp++ = CHARSUB(patinstart, *sp) + patoffset; + if (endp) + *endp++ = CHARSUB(patinstart, *ep) + patoffset + - 1; + } else { + if (begp) + *begp++ = -1; + if (endp) + *endp++ = -1; + } + + sp++; + ep++; + } + } else if (prog->patnpar && !(patflags & PAT_FILE)) { + /* + * b flag: for backreferences using parentheses. + */ + int palen = prog->patnpar+1; + char **matcharr, **mbeginarr, **mendarr; + char numbuf[DIGBUFSIZE]; + + matcharr = zshcalloc(palen*sizeof(char *)); + mbeginarr = zshcalloc(palen*sizeof(char *)); + mendarr = zshcalloc(palen*sizeof(char *)); + + sp = patbeginp; + ep = patendp; + + for (i = 0; i < prog->patnpar; i++) { + if (parsfound & (1 << i)) { + matcharr[i] = metafy(*sp, *ep - *sp, META_DUP); + /* + * mbegin and mend give indexes into the string + * in the standard notation, i.e. respecting + * KSHARRAYS, and with the end index giving + * the last character, not one beyond. + * For example, foo=foo; [[ $foo = (f)oo ]] gives + * (without KSHARRAYS) indexes 1 and 1, which + * corresponds to indexing as ${foo[1,1]}. + */ + sprintf(numbuf, "%ld", + (long)(CHARSUB(patinstart, *sp) + + patoffset + + !isset(KSHARRAYS))); + mbeginarr[i] = ztrdup(numbuf); + sprintf(numbuf, "%ld", + (long)(CHARSUB(patinstart, *ep) + + patoffset + + !isset(KSHARRAYS) - 1)); + mendarr[i] = ztrdup(numbuf); + } else { + /* Pattern wasn't set: either it was in an + * unmatched branch, or a hashed parenthesis + * that didn't match at all. + */ + matcharr[i] = ztrdup(""); + mbeginarr[i] = ztrdup("-1"); + mendarr[i] = ztrdup("-1"); + } + sp++; + ep++; + } + setaparam("match", matcharr); + setaparam("mbegin", mbeginarr); + setaparam("mend", mendarr); + } + + if (!nump && endp) { + /* + * We just need the overall end position. + */ + *endp = CHARSUB(patinstart, patinput) + patoffset; + } + + ret = 1; + } else + ret = 0; + } + + return ret; +} + +/* + * Return length of previous succesful match. This is + * in metafied bytes, i.e. includes a count of Meta characters, + * unless the match was done on an unmetafied string using + * a patstralloc stuct, in which case it, too is unmetafed. + * Unusual and futile attempt at modular encapsulation. + */ + +/**/ +int +patmatchlen(void) +{ + return patinlen; +} + +/* + * Match literal characters with case insensitivity test: the first + * comes from the input string, the second the current pattern. + */ +#ifdef MULTIBYTE_SUPPORT +#define ISUPPER(x) iswupper(x) +#define ISLOWER(x) iswlower(x) +#define TOUPPER(x) towupper(x) +#define TOLOWER(x) towlower(x) +#define ISDIGIT(x) iswdigit(x) +#else +#define ISUPPER(x) isupper(x) +#define ISLOWER(x) islower(x) +#define TOUPPER(x) toupper(x) +#define TOLOWER(x) tolower(x) +#define ISDIGIT(x) idigit(x) +#endif +#define CHARMATCH(chin, chpa) (chin == chpa || \ + ((patglobflags & GF_IGNCASE) ? \ + ((ISUPPER(chin) ? TOLOWER(chin) : chin) == \ + (ISUPPER(chpa) ? TOLOWER(chpa) : chpa)) : \ + (patglobflags & GF_LCMATCHUC) ? \ + (ISLOWER(chpa) && TOUPPER(chpa) == chin) : 0)) + +/* + * The same but caching an expression from the first argument, + * Requires local charmatch_cache definition. + */ +#define CHARMATCH_EXPR(expr, chpa) \ + (charmatch_cache = (expr), CHARMATCH(charmatch_cache, chpa)) + +/* + * exactpos is used to remember how far down an exact string we have + * matched, if we are doing approximation and can therefore redo from + * the same point; we never need to otherwise. + * + * exactend is a pointer to the end of the string, which isn't + * null-terminated. + */ +static char *exactpos, *exactend; + +/* + * Main matching routine. + * + * Testing the tail end of a match is usually done by recursion, but + * we try to eliminate that in favour of looping for simple cases. + */ + +/**/ +static int +patmatch(Upat prog) +{ + /* Current and next nodes */ + Upat scan = prog, next, opnd; + char *start, *save, *chrop, *chrend, *compend; + int savglobflags, op, no, min, fail = 0, saverrsfound; + zrange_t from, to, comp; + patint_t nextch; + int q = queue_signal_level(); + + /* + * To avoid overhead of saving state if there are no queued signals + * waiting, we pierce the signals.h veil and examine queue state. + */ +#define check_for_signals() do if (queue_front != queue_rear) { \ + int savpatflags = patflags, savpatglobflags = patglobflags; \ + char *savexactpos = exactpos, *savexactend = exactend; \ + struct rpat savpattrystate = pattrystate; \ + dont_queue_signals(); \ + restore_queue_signals(q); \ + exactpos = savexactpos; \ + exactend = savexactend; \ + patflags = savpatflags; \ + patglobflags = savpatglobflags; \ + pattrystate = savpattrystate; \ + } while (0) + + check_for_signals(); + + while (scan && !errflag) { + next = PATNEXT(scan); + + if (!globdots && P_NOTDOT(scan) && patinput == patinstart && + patinput < patinend && *patinput == '.') + return 0; + + switch (P_OP(scan)) { + case P_ANY: + if (patinput == patinend) + fail = 1; + else + CHARINC(patinput, patinend); + break; + case P_EXACTLY: + /* + * acts as nothing if *chrop is null: this is used by + * approx code. + */ + if (exactpos) { + chrop = exactpos; + chrend = exactend; + } else { + chrop = P_LS_STR(scan); + chrend = chrop + P_LS_LEN(scan); + } + exactpos = NULL; + while (chrop < chrend && patinput < patinend) { + char *savpatinput = patinput; + char *savchrop = chrop; + int badin = 0, badpa = 0; + /* + * Care with character matching: + * We do need to convert the character to wide + * representation if possible, because we may need + * to do case transformation. However, we should + * be careful in case one, but not the other, wasn't + * representable in the current locale---in that + * case they don't match even if the returned + * values (one properly converted, one raw) are + * the same. + */ + patint_t chin = CHARREFINC(patinput, patinend, &badin); + patint_t chpa = CHARREFINC(chrop, chrend, &badpa); + if (!CHARMATCH(chin, chpa) || badin != badpa) { + fail = 1; + patinput = savpatinput; + chrop = savchrop; + break; + } + } + if (chrop < chrend) { + exactpos = chrop; + exactend = chrend; + fail = 1; + } + break; + case P_ANYOF: + case P_ANYBUT: + if (patinput == patinend) + fail = 1; + else { +#ifdef MULTIBYTE_SUPPORT + int zmb_ind; + wchar_t cr = charref(patinput, patinend, &zmb_ind); + char *scanop = (char *)P_OPERAND(scan); + if (patglobflags & GF_MULTIBYTE) { + if (mb_patmatchrange(scanop, cr, zmb_ind, NULL, NULL) ^ + (P_OP(scan) == P_ANYOF)) + fail = 1; + else + CHARINC(patinput, patinend); + } else if (patmatchrange(scanop, (int)cr, NULL, NULL) ^ + (P_OP(scan) == P_ANYOF)) + fail = 1; + else + CHARINC(patinput, patinend); +#else + if (patmatchrange((char *)P_OPERAND(scan), + CHARREF(patinput, patinend), NULL, NULL) ^ + (P_OP(scan) == P_ANYOF)) + fail = 1; + else + CHARINC(patinput, patinend); +#endif + } + break; + case P_NUMRNG: + case P_NUMFROM: + case P_NUMTO: + /* + * To do this properly, we really have to treat numbers as + * closures: that's so things like <1-1000>33 will + * match 633 (they didn't up to 3.1.6). To avoid making this + * too inefficient, we see if there's an exact match next: + * if there is, and it's not a digit, we return 1 after + * the first attempt. + */ + op = P_OP(scan); + start = (char *)P_OPERAND(scan); + from = to = 0; + if (op != P_NUMTO) { +#ifdef ZSH_64_BIT_TYPE + /* We can't rely on pointer alignment being good enough. */ + memcpy((char *)&from, start, sizeof(zrange_t)); +#else + from = *((zrange_t *) start); +#endif + start += sizeof(zrange_t); + } + if (op != P_NUMFROM) { +#ifdef ZSH_64_BIT_TYPE + memcpy((char *)&to, start, sizeof(zrange_t)); +#else + to = *((zrange_t *) start); +#endif + } + start = compend = patinput; + comp = 0; + while (patinput < patinend && idigit(*patinput)) { + int out_of_range = 0; + int digit = *patinput - '0'; + if (comp > ZRANGE_MAX / (zlong)10) { + out_of_range = 1; + } else { + zrange_t c10 = comp ? comp * 10 : 0; + if (ZRANGE_MAX - c10 < digit) { + out_of_range = 1; + } else { + comp = c10; + comp += digit; + } + } + patinput++; + compend++; + + if (out_of_range || + (comp & ((zrange_t)1 << (sizeof(comp)*8 - +#ifdef ZRANGE_T_IS_SIGNED + 2 +#else + 1 +#endif + )))) { + /* + * Out of range (allowing for signedness, which + * we need if we are using zlongs). + * This is as far as we can go. + * If we're doing a range "from", skip all the + * remaining numbers. Otherwise, we can't + * match beyond the previous point anyway. + * Leave the pointer to the last calculated + * position (compend) where it was before. + */ + if (op == P_NUMFROM) { + while (patinput < patinend && idigit(*patinput)) + patinput++; + } + } + } + save = patinput; + no = 0; + while (patinput > start) { + /* if already too small, no power on earth can save it */ + if (comp < from && patinput <= compend) + break; + if ((op == P_NUMFROM || comp <= to) && patmatch(next)) { + return 1; + } + if (!no && P_OP(next) == P_EXACTLY && + (!P_LS_LEN(next) || + !idigit(STOUC(*P_LS_STR(next)))) && + !(patglobflags & 0xff)) + return 0; + patinput = --save; + no++; + /* + * With a range start and an unrepresentable test + * number, we just back down the test string without + * changing the number until we get to a representable + * one. + */ + if (patinput < compend) + comp /= 10; + } + patinput = start; + fail = 1; + break; + case P_NUMANY: + /* This is <->: any old set of digits, don't bother comparing */ + start = patinput; + while (patinput < patinend && idigit(*patinput)) + patinput++; + save = patinput; + no = 0; + while (patinput > start) { + if (patmatch(next)) + return 1; + if (!no && P_OP(next) == P_EXACTLY && + (!P_LS_LEN(next) || + !idigit(*P_LS_STR(next))) && + !(patglobflags & 0xff)) + return 0; + patinput = --save; + no++; + } + patinput = start; + fail = 1; + break; + case P_NOTHING: + break; + case P_BACK: + break; + case P_GFLAGS: + patglobflags = P_OPERAND(scan)->l; + break; + case P_OPEN: + case P_OPEN+1: + case P_OPEN+2: + case P_OPEN+3: + case P_OPEN+4: + case P_OPEN+5: + case P_OPEN+6: + case P_OPEN+7: + case P_OPEN+8: + case P_OPEN+9: + no = P_OP(scan) - P_OPEN; + save = patinput; + + if (patmatch(next)) { + /* + * Don't set patbeginp if some later invocation of + * the same parentheses already has. + */ + if (no && !(parsfound & (1 << (no - 1)))) { + patbeginp[no-1] = save; + parsfound |= 1 << (no - 1); + } + return 1; + } else + return 0; + break; + case P_CLOSE: + case P_CLOSE+1: + case P_CLOSE+2: + case P_CLOSE+3: + case P_CLOSE+4: + case P_CLOSE+5: + case P_CLOSE+6: + case P_CLOSE+7: + case P_CLOSE+8: + case P_CLOSE+9: + no = P_OP(scan) - P_CLOSE; + save = patinput; + + if (patmatch(next)) { + if (no && !(parsfound & (1 << (no + 15)))) { + patendp[no-1] = save; + parsfound |= 1 << (no + 15); + } + return 1; + } else + return 0; + break; + case P_EXCSYNC: + /* See the P_EXCLUDE code below for where syncptr comes from */ + { + unsigned char *syncptr; + Upat after; + after = P_OPERAND(scan); + DPUTS(!P_ISEXCLUDE(after), + "BUG: EXCSYNC not followed by EXCLUDE."); + DPUTS(!P_OPERAND(after)->p, + "BUG: EXCSYNC not handled by EXCLUDE"); + syncptr = P_OPERAND(after)->p + (patinput - patinstart); + /* + * If we already matched from here, this time we fail. + * See WBRANCH code for story about error count. + */ + if (*syncptr && errsfound + 1 >= *syncptr) + return 0; + /* + * Else record that we (possibly) matched this time. + * No harm if we don't: then the previous test will just + * short cut the attempted match that is bound to fail. + * We never try to exclude something that has already + * failed anyway. + */ + *syncptr = errsfound + 1; + } + break; + case P_EXCEND: + /* + * This is followed by a P_EXCSYNC, but only in the P_EXCLUDE + * branch. Actually, we don't bother following it: all we + * need to know is that we successfully matched so far up + * to the end of the asserted pattern; the endpoint + * in the target string is nulled out. + */ + if (!(fail = (patinput < patinend))) + return 1; + break; + case P_BRANCH: + case P_WBRANCH: + /* P_EXCLUDE shouldn't occur without a P_BRANCH */ + if (!P_ISBRANCH(next)) { + /* no choice, avoid recursion */ + DPUTS(P_OP(scan) == P_WBRANCH, + "BUG: WBRANCH with no alternative."); + next = P_OPERAND(scan); + } else { + do { + save = patinput; + savglobflags = patglobflags; + saverrsfound = errsfound; + if (P_ISEXCLUDE(next)) { + /* + * The strategy is to test the asserted pattern, + * recording via P_EXCSYNC how far the part to + * be excluded matched. We then set the + * length of the test string to that + * point and see if the exclusion as far as + * P_EXCEND also matches that string. + * We need to keep testing the asserted pattern + * by backtracking, since the first attempt + * may be excluded while a later attempt may not. + * For this we keep a pointer just after + * the P_EXCLUDE which is tested by the P_EXCSYNC + * to see if we matched there last time, in which + * case we fail. If there is nothing to backtrack + * over, that doesn't matter: we should fail anyway. + * The pointer also tells us where the asserted + * pattern matched for use by the exclusion. + * + * It's hard to allocate space for this + * beforehand since we may need to do it + * recursively. + * + * P.S. in case you were wondering, this code + * is horrible. + */ + Upat syncstrp; + char *origpatinend; + unsigned char *oldsyncstr; + char *matchpt = NULL; + int ret, savglobdots, matchederrs = 0; + int savparsfound = parsfound; + DPUTS(P_OP(scan) == P_WBRANCH, + "BUG: excluded WBRANCH"); + syncstrp = P_OPERAND(next); + /* + * Unlike WBRANCH, each test at the same exclude + * sync point (due to an external loop) is separate, + * i.e testing (foo~bar)# is no different from + * (foo~bar)(foo~bar)... from the exclusion point + * of view, so we use a different sync string. + */ + oldsyncstr = syncstrp->p; + syncstrp->p = (unsigned char *) + zshcalloc((patinend - patinstart) + 1); + origpatinend = patinend; + while ((ret = patmatch(P_OPERAND(scan)))) { + unsigned char *syncpt; + char *savpatinstart; + int savforce = forceerrs; + int savpatflags = patflags, synclen; + forceerrs = -1; + savglobdots = globdots; + matchederrs = errsfound; + matchpt = patinput; /* may not be end */ + globdots = 1; /* OK to match . first */ + /* Find the point where the scan + * matched the part to be excluded: because + * of backtracking, the one + * most recently matched will be the first. + * (Luckily, backtracking is done after all + * possibilities for approximation have been + * checked.) + */ + for (syncpt = syncstrp->p; !*syncpt; syncpt++) + ; + synclen = syncpt - syncstrp->p; + if (patinstart + synclen != patinend) { + /* + * Temporarily mark the string as + * ending at this point. + */ + DPUTS(patinstart + synclen > matchpt, + "BUG: EXCSYNC failed"); + + patinend = patinstart + synclen; + /* + * If this isn't really the end of the string, + * remember this for the (#e) assertion. + */ + patflags |= PAT_NOTEND; + } + savpatinstart = patinstart; + next = PATNEXT(scan); + while (next && P_ISEXCLUDE(next)) { + patinput = save; + /* + * turn off approximations in exclusions: + * note we keep remaining patglobflags + * set by asserted branch (or previous + * excluded branches, for consistency). + */ + patglobflags &= ~0xff; + errsfound = 0; + opnd = P_OPERAND(next) + 1; + if (P_OP(next) == P_EXCLUDP && patinpath) { + /* + * Top level exclusion with a file, + * applies to whole path so add the + * segments already matched. + * We copied these in front of the + * test pattern, so patinend doesn't + * need moving. + */ + DPUTS(patinput != patinstart, + "BUG: not at start excluding path"); + patinput = patinstart = patinpath; + } + if (patmatch(opnd)) { + ret = 0; + /* + * Another subtlety: if we exclude the + * match, any parentheses just found + * become invalidated. + */ + parsfound = savparsfound; + } + if (patinpath) { + patinput = savpatinstart + + (patinput - patinstart); + patinstart = savpatinstart; + } + if (!ret) + break; + next = PATNEXT(next); + } + /* + * Restore original end position. + */ + patinend = origpatinend; + patflags = savpatflags; + globdots = savglobdots; + forceerrs = savforce; + if (ret) + break; + patinput = save; + patglobflags = savglobflags; + errsfound = saverrsfound; + } + zfree((char *)syncstrp->p, + (patinend - patinstart) + 1); + syncstrp->p = oldsyncstr; + if (ret) { + patinput = matchpt; + errsfound = matchederrs; + return 1; + } + while ((scan = PATNEXT(scan)) && + P_ISEXCLUDE(scan)) + ; + } else { + int ret = 1, pfree = 0; + Upat ptrp = NULL; + unsigned char *ptr; + if (P_OP(scan) == P_WBRANCH) { + /* + * This is where we make sure that we are not + * repeatedly matching zero-length strings in + * a closure, which would cause an infinite loop, + * and also remove exponential behaviour in + * backtracking nested closures. + * The P_WBRANCH operator leaves a space for a + * uchar *, initialized to NULL, which is + * turned into a string the same length as the + * target string. Every time we match from a + * particular point in the target string, we + * stick a 1 at the corresponding point here. + * If we come round to the same branch again, and + * there is already a 1, then the test fails. + */ + opnd = P_OPERAND(scan); + ptrp = opnd++; + if (!ptrp->p) { + ptrp->p = (unsigned char *) + zshcalloc((patinend - patinstart) + 1); + pfree = 1; + } + ptr = ptrp->p + (patinput - patinstart); + + /* + * Without approximation, this is just a + * single bit test. With approximation, we + * need to know how many errors there were + * last time we made the test. If errsfound + * is now smaller than it was, hence we can + * make more approximations in the remaining + * code, we continue with the test. + * (This is why the max number of errors is + * 254, not 255.) + */ + if (*ptr && errsfound + 1 >= *ptr) + ret = 0; + *ptr = errsfound + 1; + } else + opnd = P_OPERAND(scan); + if (ret) + ret = patmatch(opnd); + if (pfree) { + zfree((char *)ptrp->p, + (patinend - patinstart) + 1); + ptrp->p = NULL; + } + if (ret) + return 1; + scan = PATNEXT(scan); + } + patinput = save; + patglobflags = savglobflags; + errsfound = saverrsfound; + DPUTS(P_OP(scan) == P_WBRANCH, + "BUG: WBRANCH not first choice."); + next = PATNEXT(scan); + } while (scan && P_ISBRANCH(scan)); + return 0; + } + break; + case P_STAR: + /* Handle specially for speed, although really P_ONEHASH+P_ANY */ + while (P_OP(next) == P_STAR) { + /* + * If there's another * following we can optimise it + * out. Chains of *'s can give pathologically bad + * performance. + */ + scan = next; + next = PATNEXT(scan); + } + /*FALLTHROUGH*/ + case P_ONEHASH: + case P_TWOHASH: + /* + * This is just simple cases, matching one character. + * With approximations, we still handle * this way, since + * no approximation is ever necessary, but other closures + * are handled by the more complicated branching method + */ + op = P_OP(scan); + /* Note that no counts possibly metafied characters */ + start = patinput; + { + char *lastcharstart; + /* + * Array to record the start of characters for + * backtracking. + */ + VARARR(char, charstart, patinend-patinput); + memset(charstart, 0, patinend-patinput); + + if (op == P_STAR) { + for (no = 0; patinput < patinend; + CHARINC(patinput, patinend)) + { + charstart[patinput-start] = 1; + no++; + } + /* simple optimization for reasonably common case */ + if (P_OP(next) == P_END) + return 1; + } else { + DPUTS(patglobflags & 0xff, + "BUG: wrong backtracking with approximation."); + if (!globdots && P_NOTDOT(P_OPERAND(scan)) && + patinput == patinstart && patinput < patinend && + CHARREF(patinput, patinend) == ZWC('.')) + return 0; + no = patrepeat(P_OPERAND(scan), charstart); + } + min = (op == P_TWOHASH) ? 1 : 0; + /* + * Lookahead to avoid useless matches. This is not possible + * with approximation. + */ + if (P_OP(next) == P_EXACTLY && P_LS_LEN(next) && + !(patglobflags & 0xff)) { + char *nextop = P_LS_STR(next); +#ifdef MULTIBYTE_SUPPORT + /* else second argument of CHARREF isn't used */ + int nextlen = P_LS_LEN(next); +#endif + /* + * If that P_EXACTLY is last (common in simple patterns, + * such as *.c), then it can be only be matched at one + * point in the test string, so record that. + */ + if (P_OP(PATNEXT(next)) == P_END && + !(patflags & PAT_NOANCH)) { + int ptlen = patinend - patinput; + int lenmatch = patinend - + (min ? CHARNEXT(start, patinend) : start); + /* Are we in the right range? */ + if (P_LS_LEN(next) > lenmatch || + P_LS_LEN(next) < ptlen) + return 0; + /* Yes, just position appropriately and test. */ + patinput += ptlen - P_LS_LEN(next); + /* + * Here we will need to be careful that patinput is not + * in the middle of a multibyte character. + */ + /* Continue loop with P_EXACTLY test. */ + break; + } + nextch = CHARREF(nextop, nextop + nextlen); + } else + nextch = PEOF; + savglobflags = patglobflags; + saverrsfound = errsfound; + lastcharstart = charstart + (patinput - start); + if (no >= min) { + for (;;) { + patint_t charmatch_cache; + if (nextch == PEOF || + (patinput < patinend && + CHARMATCH_EXPR(CHARREF(patinput, patinend), + nextch))) { + if (patmatch(next)) + return 1; + } + if (--no < min) + break; + /* find start of previous full character */ + while (!*--lastcharstart) + DPUTS(lastcharstart < charstart, + "lastcharstart invalid"); + patinput = start + (lastcharstart-charstart); + patglobflags = savglobflags; + errsfound = saverrsfound; + } + } + } + /* + * As with branches, the patmatch(next) stuff for * + * handles approximation, so we don't need to try + * anything here. + */ + return 0; + case P_ISSTART: + if (patinput != patinstart || (patflags & PAT_NOTSTART)) + fail = 1; + break; + case P_ISEND: + if (patinput < patinend || (patflags & PAT_NOTEND)) + fail = 1; + break; + case P_COUNTSTART: + { + /* + * Save and restore the current count and the + * start pointer in case the pattern has been + * executed by a previous repetition of a + * closure. + */ + long *curptr = &P_OPERAND(scan)[P_CT_CURRENT].l; + long savecount = *curptr; + unsigned char *saveptr = scan[P_CT_PTR].p; + int ret; + + *curptr = 0L; + ret = patmatch(P_OPERAND(scan)); + *curptr = savecount; + scan[P_CT_PTR].p = saveptr; + return ret; + } + case P_COUNT: + { + /* (#cN,M): execution is relatively straightforward */ + long cur = scan[P_CT_CURRENT].l; + long min = scan[P_CT_MIN].l; + long max = scan[P_CT_MAX].l; + + if (cur && cur >= min && + (unsigned char *)patinput == scan[P_CT_PTR].p) { + /* + * Not at the first attempt to match so + * the previous attempt managed zero length. + * We can do this indefinitely so there's + * no point in going on. Simply try to + * match the remainder of the pattern. + */ + return patmatch(next); + } + scan[P_CT_PTR].p = (unsigned char *)patinput; + + if (max < 0 || cur < max) { + char *patinput_thistime = patinput; + scan[P_CT_CURRENT].l = cur + 1; + if (patmatch(scan + P_CT_OPERAND)) + return 1; + scan[P_CT_CURRENT].l = cur; + patinput = patinput_thistime; + } + if (cur < min) + return 0; + return patmatch(next); + } + case P_END: + if (!(fail = (patinput < patinend && !(patflags & PAT_NOANCH)))) + return 1; + break; +#ifdef DEBUG + default: + dputs("BUG: bad operand in patmatch."); + return 0; + break; +#endif + } + + if (fail) { + if (errsfound < (patglobflags & 0xff) && + (forceerrs == -1 || errsfound < forceerrs)) { + /* + * Approximation code. There are four possibilities + * + * 1. omit character from input string + * 2. transpose characters in input and pattern strings + * 3. omit character in both input and pattern strings + * 4. omit character from pattern string. + * + * which we try in that order. + * + * Of these, 2, 3 and 4 require an exact match string + * (P_EXACTLY) while 1, 2 and 3 require that we not + * have reached the end of the input string. + * + * Note in each case after making the approximation we + * need to retry the *same* pattern; this is what + * requires exactpos, a slightly doleful way of + * communicating with the exact character matcher. + */ + char *savexact = exactpos; + save = patinput; + savglobflags = patglobflags; + saverrsfound = ++errsfound; + fail = 0; + + DPUTS(P_OP(scan) != P_EXACTLY && exactpos, + "BUG: non-exact match has set exactpos"); + + /* Try omitting a character from the input string */ + if (patinput < patinend) { + CHARINC(patinput, patinend); + /* If we are not on an exact match, then this is + * our last gasp effort, so we can optimize out + * the recursive call. + */ + if (P_OP(scan) != P_EXACTLY) + continue; + if (patmatch(scan)) + return 1; + } + + if (P_OP(scan) == P_EXACTLY) { + char *nextexact = savexact; + DPUTS(!savexact, + "BUG: exact match has not set exactpos"); + CHARINC(nextexact, exactend); + + if (save < patinend) { + char *nextin = save; + CHARINC(nextin, patinend); + patglobflags = savglobflags; + errsfound = saverrsfound; + exactpos = savexact; + + /* + * Try swapping two characters in patinput and + * exactpos + */ + if (save < patinend && nextin < patinend && + nextexact < exactend) { + patint_t cin0 = CHARREF(save, patinend); + patint_t cpa0 = CHARREF(exactpos, exactend); + patint_t cin1 = CHARREF(nextin, patinend); + patint_t cpa1 = CHARREF(nextexact, exactend); + + if (CHARMATCH(cin0, cpa1) && + CHARMATCH(cin1, cpa0)) { + patinput = nextin; + CHARINC(patinput, patinend); + exactpos = nextexact; + CHARINC(exactpos, exactend); + if (patmatch(scan)) + return 1; + + patglobflags = savglobflags; + errsfound = saverrsfound; + } + } + + /* + * Try moving up both strings. + */ + patinput = nextin; + exactpos = nextexact; + if (patmatch(scan)) + return 1; + + patinput = save; + patglobflags = savglobflags; + errsfound = saverrsfound; + exactpos = savexact; + } + + DPUTS(exactpos == exactend, "approximating too far"); + /* + * Try moving up the exact match pattern. + * This must be the last attempt, so just loop + * instead of calling recursively. + */ + CHARINC(exactpos, exactend); + continue; + } + } + exactpos = NULL; + return 0; + } + + scan = next; + + /* Allow handlers to run once per loop */ + check_for_signals(); + } + + return 0; +} + + +/**/ +#ifdef MULTIBYTE_SUPPORT + +/* + * See if character ch matches a pattern range specification. + * The null-terminated specification is in range; the test + * character is in ch. + * + * zmb is one of the enum defined above charref(), for indicating + * incomplete or invalid multibyte characters. + * + * indptr is used by completion matching, which is why this + * function is exported. If indptr is not NULL we set *indptr + * to the index of the character in the range string, adjusted + * in the case of "A-B" ranges such that A would count as its + * normal index (say IA), B would count as IA + (B-A), and any + * character within the range as appropriate. We're not strictly + * guaranteed this fits within a wint_t, but if this is Unicode + * in 32 bits we have a fair amount of distance left over. + * + * mtp is used in the same circumstances. *mtp returns the match type: + * 0 for a standard character, else the PP_ index. It's not + * useful if the match failed. + */ + +/**/ +mod_export int +mb_patmatchrange(char *range, wchar_t ch, int zmb_ind, wint_t *indptr, int *mtp) +{ + wchar_t r1, r2; + + if (indptr) + *indptr = 0; + /* + * Careful here: unlike other strings, range is a NULL-terminated, + * metafied string, because we need to treat the Posix and hyphenated + * ranges specially. + */ + while (*range) { + if (imeta(STOUC(*range))) { + int swtype = STOUC(*range++) - STOUC(Meta); + if (mtp) + *mtp = swtype; + switch (swtype) { + case 0: + /* ordinary metafied character */ + range--; + if (metacharinc(&range) == ch) + return 1; + break; + case PP_ALPHA: + if (iswalpha(ch)) + return 1; + break; + case PP_ALNUM: + if (iswalnum(ch)) + return 1; + break; + case PP_ASCII: + if ((ch & ~0x7f) == 0) + return 1; + break; + case PP_BLANK: +#if !defined(HAVE_ISWBLANK) && !defined(iswblank) +/* + * iswblank() is GNU and C99. There's a remote chance that some + * systems still don't support it (but would support the other ones + * if MULTIBYTE_SUPPORT is enabled). + */ +#define iswblank(c) (c == L' ' || c == L'\t') +#endif + if (iswblank(ch)) + return 1; + break; + case PP_CNTRL: + if (iswcntrl(ch)) + return 1; + break; + case PP_DIGIT: + if (iswdigit(ch)) + return 1; + break; + case PP_GRAPH: + if (iswgraph(ch)) + return 1; + break; + case PP_LOWER: + if (iswlower(ch)) + return 1; + break; + case PP_PRINT: + if (WC_ISPRINT(ch)) + return 1; + break; + case PP_PUNCT: + if (iswpunct(ch)) + return 1; + break; + case PP_SPACE: + if (iswspace(ch)) + return 1; + break; + case PP_UPPER: + if (iswupper(ch)) + return 1; + break; + case PP_XDIGIT: + if (iswxdigit(ch)) + return 1; + break; + case PP_IDENT: + if (wcsitype(ch, IIDENT)) + return 1; + break; + case PP_IFS: + if (wcsitype(ch, ISEP)) + return 1; + break; + case PP_IFSSPACE: + /* must be ASCII space character */ + if (ch < 128 && iwsep((int)ch)) + return 1; + break; + case PP_WORD: + if (wcsitype(ch, IWORD)) + return 1; + break; + case PP_RANGE: + r1 = metacharinc(&range); + r2 = metacharinc(&range); + if (r1 <= ch && ch <= r2) { + if (indptr) + *indptr += ch - r1; + return 1; + } + /* Careful not to screw up counting with bogus range */ + if (indptr && r1 < r2) { + /* + * This gets incremented again below to get + * us past the range end. This is correct. + */ + *indptr += r2 - r1; + } + break; + case PP_INCOMPLETE: + if (zmb_ind == ZMB_INCOMPLETE) + return 1; + break; + case PP_INVALID: + if (zmb_ind == ZMB_INVALID) + return 1; + break; + case PP_UNKWN: + DPUTS(1, "BUG: unknown posix range passed through.\n"); + break; + default: + DPUTS(1, "BUG: unknown metacharacter in range."); + break; + } + } else if (metacharinc(&range) == ch) { + if (mtp) + *mtp = 0; + return 1; + } + if (indptr) + (*indptr)++; + } + return 0; +} + + +/* + * This is effectively the reverse of mb_patmatchrange(). + * Given a range descriptor of the same form, and an index into it, + * try to determine the character that is matched. If the index + * points to a [:...:] generic style match, set chr to WEOF and + * return the type in mtp instead. Return 1 if successful, 0 if + * there was no corresponding index. Note all pointer arguments + * must be non-null. + */ + +/**/ +mod_export int +mb_patmatchindex(char *range, wint_t ind, wint_t *chr, int *mtp) +{ + wchar_t r1, r2, rchr; + wint_t rdiff; + + *chr = WEOF; + *mtp = 0; + + while (*range) { + if (imeta(STOUC(*range))) { + int swtype = STOUC(*range++) - STOUC(Meta); + switch (swtype) { + case 0: + range--; + rchr = metacharinc(&range); + if (!ind) { + *chr = (wint_t) rchr; + return 1; + } + break; + + case PP_ALPHA: + case PP_ALNUM: + case PP_ASCII: + case PP_BLANK: + case PP_CNTRL: + case PP_DIGIT: + case PP_GRAPH: + case PP_LOWER: + case PP_PRINT: + case PP_PUNCT: + case PP_SPACE: + case PP_UPPER: + case PP_XDIGIT: + case PP_IDENT: + case PP_IFS: + case PP_IFSSPACE: + case PP_WORD: + case PP_INCOMPLETE: + case PP_INVALID: + if (!ind) { + *mtp = swtype; + return 1; + } + break; + + case PP_RANGE: + r1 = metacharinc(&range); + r2 = metacharinc(&range); + rdiff = (wint_t)r2 - (wint_t)r1; + if (rdiff >= ind) { + *chr = (wint_t)r1 + ind; + return 1; + } + /* note the extra decrement to ind below */ + ind -= rdiff; + break; + case PP_UNKWN: + DPUTS(1, "BUG: unknown posix range passed through.\n"); + break; + default: + DPUTS(1, "BUG: unknown metacharacter in range."); + break; + } + } else { + rchr = metacharinc(&range); + if (!ind) { + *chr = (wint_t)rchr; + return 1; + } + } + if (!ind--) + break; + } + + /* No corresponding index. */ + return 0; +} + +/**/ +#endif /* MULTIBYTE_SUPPORT */ + +/* + * Identical function to mb_patmatchrange() above for single-byte + * characters. + */ + +/**/ +mod_export int +patmatchrange(char *range, int ch, int *indptr, int *mtp) +{ + int r1, r2; + + if (indptr) + *indptr = 0; + /* + * Careful here: unlike other strings, range is a NULL-terminated, + * metafied string, because we need to treat the Posix and hyphenated + * ranges specially. + */ + for (; *range; range++) { + if (imeta(STOUC(*range))) { + int swtype = STOUC(*range) - STOUC(Meta); + if (mtp) + *mtp = swtype; + switch (swtype) { + case 0: + if (STOUC(*++range ^ 32) == ch) + return 1; + break; + case PP_ALPHA: + if (isalpha(ch)) + return 1; + break; + case PP_ALNUM: + if (isalnum(ch)) + return 1; + break; + case PP_ASCII: + if ((ch & ~0x7f) == 0) + return 1; + break; + case PP_BLANK: +#if !defined(HAVE_ISBLANK) && !defined(isblank) +/* + * isblank() is GNU and C99. There's a remote chance that some + * systems still don't support it. + */ +#define isblank(c) (c == ' ' || c == '\t') +#endif + if (isblank(ch)) + return 1; + break; + case PP_CNTRL: + if (iscntrl(ch)) + return 1; + break; + case PP_DIGIT: + if (isdigit(ch)) + return 1; + break; + case PP_GRAPH: + if (isgraph(ch)) + return 1; + break; + case PP_LOWER: + if (islower(ch)) + return 1; + break; + case PP_PRINT: + if (ZISPRINT(ch)) + return 1; + break; + case PP_PUNCT: + if (ispunct(ch)) + return 1; + break; + case PP_SPACE: + if (isspace(ch)) + return 1; + break; + case PP_UPPER: + if (isupper(ch)) + return 1; + break; + case PP_XDIGIT: + if (isxdigit(ch)) + return 1; + break; + case PP_IDENT: + if (iident(ch)) + return 1; + break; + case PP_IFS: + if (isep(ch)) + return 1; + break; + case PP_IFSSPACE: + if (iwsep(ch)) + return 1; + break; + case PP_WORD: + if (iword(ch)) + return 1; + break; + case PP_RANGE: + range++; + r1 = STOUC(UNMETA(range)); + METACHARINC(range); + r2 = STOUC(UNMETA(range)); + if (*range == Meta) + range++; + if (r1 <= ch && ch <= r2) { + if (indptr) + *indptr += ch - r1; + return 1; + } + if (indptr && r1 < r2) + *indptr += r2 - r1; + break; + case PP_INCOMPLETE: + case PP_INVALID: + /* Never true if not in multibyte mode */ + break; + case PP_UNKWN: + DPUTS(1, "BUG: unknown posix range passed through.\n"); + break; + default: + DPUTS(1, "BUG: unknown metacharacter in range."); + break; + } + } else if (STOUC(*range) == ch) { + if (mtp) + *mtp = 0; + return 1; + } + if (indptr) + (*indptr)++; + } + return 0; +} + + +/**/ +#ifndef MULTIBYTE_SUPPORT + +/* + * Identical function to mb_patmatchindex() above for single-byte + * characters. Here -1 represents a character that needs a special type. + * + * Unlike patmatchrange, we only need this in ZLE, which always + * uses MULTIBYTE_SUPPORT if compiled in; hence we don't use + * this function in that case. + */ + +/**/ +mod_export int +patmatchindex(char *range, int ind, int *chr, int *mtp) +{ + int r1, r2, rdiff, rchr; + + *chr = -1; + *mtp = 0; + + for (; *range; range++) { + if (imeta(STOUC(*range))) { + int swtype = STOUC(*range) - STOUC(Meta); + switch (swtype) { + case 0: + /* ordinary metafied character */ + rchr = STOUC(*++range) ^ 32; + if (!ind) { + *chr = rchr; + return 1; + } + break; + + case PP_ALPHA: + case PP_ALNUM: + case PP_ASCII: + case PP_BLANK: + case PP_CNTRL: + case PP_DIGIT: + case PP_GRAPH: + case PP_LOWER: + case PP_PRINT: + case PP_PUNCT: + case PP_SPACE: + case PP_UPPER: + case PP_XDIGIT: + case PP_IDENT: + case PP_IFS: + case PP_IFSSPACE: + case PP_WORD: + case PP_INCOMPLETE: + case PP_INVALID: + if (!ind) { + *mtp = swtype; + return 1; + } + break; + + case PP_RANGE: + range++; + r1 = STOUC(UNMETA(range)); + METACHARINC(range); + r2 = STOUC(UNMETA(range)); + if (*range == Meta) + range++; + rdiff = r2 - r1; + if (rdiff >= ind) { + *chr = r1 + ind; + return 1; + } + /* note the extra decrement to ind below */ + ind -= rdiff; + break; + case PP_UNKWN: + DPUTS(1, "BUG: unknown posix range passed through.\n"); + break; + default: + DPUTS(1, "BUG: unknown metacharacter in range."); + break; + } + } else { + if (!ind) { + *chr = STOUC(*range); + return 1; + } + } + if (!ind--) + break; + } + + /* No corresponding index. */ + return 0; +} + +/**/ +#endif /* MULTIBYTE_SUPPORT */ + +/* + * Repeatedly match something simple and say how many times. + * charstart is an array parallel to that starting at patinput + * and records the start of (possibly multibyte) characters + * to aid in later backtracking. + */ + +/**/ +static int patrepeat(Upat p, char *charstart) +{ + int count = 0; + patint_t tch, charmatch_cache; + char *scan, *opnd; + + scan = patinput; + opnd = (char *)P_OPERAND(p); + + switch(P_OP(p)) { +#ifdef DEBUG + case P_ANY: + dputs("BUG: ?# did not get optimized to *"); + return 0; + break; +#endif + case P_EXACTLY: + DPUTS(P_LS_LEN(p) != 1, "closure following more than one character"); + tch = CHARREF(P_LS_STR(p), P_LS_STR(p) + P_LS_LEN(p)); + while (scan < patinend && + CHARMATCH_EXPR(CHARREF(scan, patinend), tch)) { + charstart[scan-patinput] = 1; + count++; + CHARINC(scan, patinend); + } + break; + case P_ANYOF: + case P_ANYBUT: + while (scan < patinend) { +#ifdef MULTIBYTE_SUPPORT + int zmb_ind; + wchar_t cr = charref(scan, patinend, &zmb_ind); + if (patglobflags & GF_MULTIBYTE) { + if (mb_patmatchrange(opnd, cr, zmb_ind, NULL, NULL) ^ + (P_OP(p) == P_ANYOF)) + break; + } else if (patmatchrange(opnd, (int)cr, NULL, NULL) ^ + (P_OP(p) == P_ANYOF)) + break; +#else + if (patmatchrange(opnd, CHARREF(scan, patinend), NULL, NULL) ^ + (P_OP(p) == P_ANYOF)) + break; +#endif + charstart[scan-patinput] = 1; + count++; + CHARINC(scan, patinend); + } + break; +#ifdef DEBUG + default: + dputs("BUG: something very strange is happening in patrepeat"); + return 0; + break; +#endif + } + + patinput = scan; + return count; +} + +/* Free a patprog. */ + +/**/ +mod_export void +freepatprog(Patprog prog) +{ + if (prog && prog != dummy_patprog1 && prog != dummy_patprog2) + zfree(prog, prog->size); +} + +/* Disable or reenable a pattern character */ + +/**/ +int +pat_enables(const char *cmd, char **patp, int enable) +{ + int ret = 0; + const char **stringp; + char *disp; + + if (!*patp) { + int done = 0; + for (stringp = zpc_strings, disp = zpc_disables; + stringp < zpc_strings + ZPC_COUNT; + stringp++, disp++) { + if (!*stringp) + continue; + if (enable ? *disp : !*disp) + continue; + if (done) + putc(' ', stdout); + printf("'%s'", *stringp); + done = 1; + } + if (done) + putc('\n', stdout); + return 0; + } + + for (; *patp; patp++) { + for (stringp = zpc_strings, disp = zpc_disables; + stringp < zpc_strings + ZPC_COUNT; + stringp++, disp++) { + if (*stringp && !strcmp(*stringp, *patp)) { + *disp = (char)!enable; + break; + } + } + if (stringp == zpc_strings + ZPC_COUNT) { + zerrnam(cmd, "invalid pattern: %s", *patp); + ret = 1; + } + } + + return ret; +} + +/* + * Save the current state of pattern disables, returning the saved value. + */ + +/**/ +unsigned int +savepatterndisables(void) +{ + unsigned int disables, bit; + char *disp; + + disables = 0; + for (bit = 1, disp = zpc_disables; + disp < zpc_disables + ZPC_COUNT; + bit <<= 1, disp++) { + if (*disp) + disables |= bit; + } + return disables; +} + +/* + * Function scope saving pattern enables. + */ + +/**/ +void +startpatternscope(void) +{ + Zpc_disables_save newdis; + + newdis = (Zpc_disables_save)zalloc(sizeof(*newdis)); + newdis->next = zpc_disables_stack; + newdis->disables = savepatterndisables(); + + zpc_disables_stack = newdis; +} + +/* + * Restore completely the state of pattern disables. + */ + +/**/ +void +restorepatterndisables(unsigned int disables) +{ + char *disp; + unsigned int bit; + + for (bit = 1, disp = zpc_disables; + disp < zpc_disables + ZPC_COUNT; + bit <<= 1, disp++) { + if (disables & bit) + *disp = 1; + else + *disp = 0; + } +} + +/* + * Function scope to restore pattern enables if localpatterns is turned on. + */ + +/**/ +void +endpatternscope(void) +{ + Zpc_disables_save olddis; + + olddis = zpc_disables_stack; + zpc_disables_stack = olddis->next; + + if (isset(LOCALPATTERNS)) + restorepatterndisables(olddis->disables); + + zfree(olddis, sizeof(*olddis)); +} + +/* Reinitialise pattern disables */ + +/**/ +void +clearpatterndisables(void) +{ + memset(zpc_disables, 0, ZPC_COUNT); +} + + +/* Check to see if str is eligible for filename generation. */ + +/**/ +mod_export int +haswilds(char *str) +{ + char *start; + + /* `[' and `]' are legal even if bad patterns are usually not. */ + if ((*str == Inbrack || *str == Outbrack) && !str[1]) + return 0; + + /* If % is immediately followed by ?, then that ? is * + * not treated as a wildcard. This is so you don't have * + * to escape job references such as %?foo. */ + if (str[0] == '%' && str[1] == Quest) + str[1] = '?'; + + /* + * Note that at this point zpc_special has not been set up. + */ + start = str; + for (; *str; str++) { + switch (*str) { + case Inpar: + if ((!isset(SHGLOB) && !zpc_disables[ZPC_INPAR]) || + (str > start && isset(KSHGLOB) && + ((str[-1] == Quest && !zpc_disables[ZPC_KSH_QUEST]) || + (str[-1] == Star && !zpc_disables[ZPC_KSH_STAR]) || + (str[-1] == '+' && !zpc_disables[ZPC_KSH_PLUS]) || + (str[-1] == Bang && !zpc_disables[ZPC_KSH_BANG]) || + (str[-1] == '!' && !zpc_disables[ZPC_KSH_BANG2]) || + (str[-1] == '@' && !zpc_disables[ZPC_KSH_AT])))) + return 1; + break; + + case Bar: + if (!zpc_disables[ZPC_BAR]) + return 1; + break; + + case Star: + if (!zpc_disables[ZPC_STAR]) + return 1; + break; + + case Inbrack: + if (!zpc_disables[ZPC_INBRACK]) + return 1; + break; + + case Inang: + if (!zpc_disables[ZPC_INANG]) + return 1; + break; + + case Quest: + if (!zpc_disables[ZPC_QUEST]) + return 1; + break; + + case Pound: + if (isset(EXTENDEDGLOB) && !zpc_disables[ZPC_HASH]) + return 1; + break; + + case Hat: + if (isset(EXTENDEDGLOB) && !zpc_disables[ZPC_HAT]) + return 1; + break; + } + } + return 0; +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/prompt.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/prompt.c new file mode 100644 index 00000000..959ed8e3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/prompt.c @@ -0,0 +1,2046 @@ +/* + * prompt.c - construct zsh prompts + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "prompt.pro" + +/* text attribute mask */ + +/**/ +mod_export unsigned txtattrmask; + +/* the command stack for use with %_ in prompts */ + +/**/ +unsigned char *cmdstack; +/**/ +int cmdsp; + +/* parser states, for %_ */ + +static char *cmdnames[CS_COUNT] = { + "for", "while", "repeat", "select", + "until", "if", "then", "else", + "elif", "math", "cond", "cmdor", + "cmdand", "pipe", "errpipe", "foreach", + "case", "function", "subsh", "cursh", + "array", "quote", "dquote", "bquote", + "cmdsubst", "mathsubst", "elif-then", "heredoc", + "heredocd", "brace", "braceparam", "always", +}; + + +struct buf_vars; + +struct buf_vars { +/* Previous set of prompt variables on the stack. */ + + struct buf_vars *last; + +/* The buffer into which an expanded and metafied prompt is being written, * + * and its size. */ + + char *buf; + int bufspc; + +/* bp is the pointer to the current position in the buffer, where the next * + * character will be added. */ + + char *bp; + +/* Position of the start of the current line in the buffer */ + + char *bufline; + +/* bp1 is an auxiliary pointer into the buffer, which when non-NULL is * + * moved whenever the buffer is reallocated. It is used when data is * + * being temporarily held in the buffer. */ + + char *bp1; + +/* The format string, for %-expansion. */ + + char *fm; + +/* Non-zero if truncating the current segment of the buffer. */ + + int truncwidth; + +/* Current level of nesting of %{ / %} sequences. */ + + int dontcount; + +/* Level of %{ / %} surrounding a truncation segment. */ + + int trunccount; + +/* Strings to use for %r and %R (for the spelling prompt). */ + + char *rstring, *Rstring; +}; + +typedef struct buf_vars *Buf_vars; + +/* The currently active prompt output variables */ +static Buf_vars bv; + +/* + * Expand path p; maximum is npath segments where 0 means the whole path. + * If tilde is 1, try and find a named directory to use. + */ + +static void +promptpath(char *p, int npath, int tilde) +{ + char *modp = p; + Nameddir nd; + + if (tilde && ((nd = finddir(p)))) + modp = tricat("~", nd->node.nam, p + strlen(nd->dir)); + + if (npath) { + char *sptr; + if (npath > 0) { + for (sptr = modp + strlen(modp); sptr > modp; sptr--) { + if (*sptr == '/' && !--npath) { + sptr++; + break; + } + } + if (*sptr == '/' && sptr[1] && sptr != modp) + sptr++; + stradd(sptr); + } else { + char cbu; + for (sptr = modp+1; *sptr; sptr++) + if (*sptr == '/' && !++npath) + break; + cbu = *sptr; + *sptr = 0; + stradd(modp); + *sptr = cbu; + } + } else + stradd(modp); + + if (p != modp) + zsfree(modp); +} + +/* + * Perform prompt expansion on a string, putting the result in a + * permanently-allocated string. If ns is non-zero, this string + * may have embedded Inpar and Outpar, which indicate a toggling + * between spacing and non-spacing parts of the prompt, and + * Nularg, which (in a non-spacing sequence) indicates a + * `glitch' space. + * + * txtchangep gives an integer controlling the attributes of + * the prompt. This is for use in zle to maintain the attributes + * consistenly. Other parts of the shell should not need to use it. + */ + +/**/ +mod_export char * +promptexpand(char *s, int ns, char *rs, char *Rs, unsigned int *txtchangep) +{ + struct buf_vars new_vars; + + if(!s) + return ztrdup(""); + + if ((termflags & TERM_UNKNOWN) && (unset(INTERACTIVE))) + init_term(); + + if (isset(PROMPTSUBST)) { + int olderr = errflag; + int oldval = lastval; + + s = dupstring(s); + if (!parsestr(&s)) + singsub(&s); + /* + * We don't need the special Nularg hack here and we're + * going to be using Nularg for other things. + */ + if (*s == Nularg && s[1] == '\0') + *s = '\0'; + + /* + * Ignore errors and status change in prompt substitution. + * However, keep any user interrupt error that occurred. + */ + errflag = olderr | (errflag & ERRFLAG_INT); + lastval = oldval; + } + + memset(&new_vars, 0, sizeof(new_vars)); + new_vars.last = bv; + bv = &new_vars; + + new_vars.rstring = rs; + new_vars.Rstring = Rs; + new_vars.fm = s; + new_vars.bufspc = 256; + new_vars.bp = new_vars.bufline = new_vars.buf = zshcalloc(new_vars.bufspc); + new_vars.bp1 = NULL; + new_vars.truncwidth = 0; + + putpromptchar(1, '\0', txtchangep); + addbufspc(2); + if (new_vars.dontcount) + *new_vars.bp++ = Outpar; + *new_vars.bp = '\0'; + if (!ns) { + /* If zero, Inpar, Outpar and Nularg should be removed. */ + for (new_vars.bp = new_vars.buf; *new_vars.bp; ) { + if (*new_vars.bp == Meta) + new_vars.bp += 2; + else if (*new_vars.bp == Inpar || *new_vars.bp == Outpar || + *new_vars.bp == Nularg) + chuck(new_vars.bp); + else + new_vars.bp++; + } + } + + bv = new_vars.last; + + return new_vars.buf; +} + +/* Parse the argument for %F and %K */ +static int +parsecolorchar(int arg, int is_fg) +{ + if (bv->fm[1] == '{') { + char *ep; + bv->fm += 2; /* skip over F{ */ + if ((ep = strchr(bv->fm, '}'))) { + char oc = *ep, *col, *coll; + *ep = '\0'; + /* expand the contents of the argument so you can use + * %v for example */ + coll = col = promptexpand(bv->fm, 0, NULL, NULL, NULL); + *ep = oc; + arg = match_colour((const char **)&coll, is_fg, 0); + free(col); + bv->fm = ep; + } else { + arg = match_colour((const char **)&bv->fm, is_fg, 0); + if (*bv->fm != '}') + bv->fm--; + } + } else + arg = match_colour(NULL, 1, arg); + return arg; +} + +/* Perform %- and !-expansion as required on a section of the prompt. The * + * section is ended by an instance of endchar. If doprint is 0, the valid * + * % sequences are merely skipped over, and nothing is stored. */ + +/**/ +static int +putpromptchar(int doprint, int endchar, unsigned int *txtchangep) +{ + char *ss, *hostnam; + int t0, arg, test, sep, j, numjobs, len; + struct tm *tm; + struct timespec ts; + time_t timet; + Nameddir nd; + + for (; *bv->fm && *bv->fm != endchar; bv->fm++) { + arg = 0; + if (*bv->fm == '%' && isset(PROMPTPERCENT)) { + int minus = 0; + bv->fm++; + if (*bv->fm == '-') { + minus = 1; + bv->fm++; + } + if (idigit(*bv->fm)) { + arg = zstrtol(bv->fm, &bv->fm, 10); + if (minus) + arg *= -1; + } else if (minus) + arg = -1; + if (*bv->fm == '(') { + int tc, otruncwidth; + + if (idigit(*++bv->fm)) { + arg = zstrtol(bv->fm, &bv->fm, 10); + } else if (arg < 0) { + /* negative numbers don't make sense here */ + arg *= -1; + } + test = 0; + ss = pwd; + switch (tc = *bv->fm) { + case 'c': + case '.': + case '~': + if ((nd = finddir(ss))) { + arg--; + ss += strlen(nd->dir); + } /*FALLTHROUGH*/ + case '/': + case 'C': + /* `/' gives 0, `/any' gives 1, etc. */ + if (*ss && *ss++ == '/' && *ss) + arg--; + for (; *ss; ss++) + if (*ss == '/') + arg--; + if (arg <= 0) + test = 1; + break; + case 't': + case 'T': + case 'd': + case 'D': + case 'w': + timet = time(NULL); + tm = localtime(&timet); + switch (tc) { + case 't': + test = (arg == tm->tm_min); + break; + case 'T': + test = (arg == tm->tm_hour); + break; + case 'd': + test = (arg == tm->tm_mday); + break; + case 'D': + test = (arg == tm->tm_mon); + break; + case 'w': + test = (arg == tm->tm_wday); + break; + } + break; + case '?': + if (lastval == arg) + test = 1; + break; + case '#': + if (geteuid() == (uid_t)arg) + test = 1; + break; + case 'g': + if (getegid() == (gid_t)arg) + test = 1; + break; + case 'j': + for (numjobs = 0, j = 1; j <= maxjob; j++) + if (jobtab[j].stat && jobtab[j].procs && + !(jobtab[j].stat & STAT_NOPRINT)) numjobs++; + if (numjobs >= arg) + test = 1; + break; + case 'l': + *bv->bp = '\0'; + countprompt(bv->bufline, &t0, 0, 0); + if (minus) + t0 = zterm_columns - t0; + if (t0 >= arg) + test = 1; + break; + case 'e': + { + Funcstack fsptr = funcstack; + test = arg; + while (fsptr && test > 0) { + test--; + fsptr = fsptr->prev; + } + test = !test; + } + break; + case 'L': + if (shlvl >= arg) + test = 1; + break; + case 'S': + if (time(NULL) - shtimer.tv_sec >= arg) + test = 1; + break; + case 'v': + if (arrlen_ge(psvar, arg)) + test = 1; + break; + case 'V': + if (psvar && *psvar && arrlen_ge(psvar, arg)) { + if (*psvar[(arg ? arg : 1) - 1]) + test = 1; + } + break; + case '_': + test = (cmdsp >= arg); + break; + case '!': + test = privasserted(); + break; + default: + test = -1; + break; + } + if (!*bv->fm || !(sep = *++bv->fm)) + return 0; + bv->fm++; + /* Don't do the current truncation until we get back */ + otruncwidth = bv->truncwidth; + bv->truncwidth = 0; + if (!putpromptchar(test == 1 && doprint, sep, + txtchangep) || !*++bv->fm || + !putpromptchar(test == 0 && doprint, ')', + txtchangep)) { + bv->truncwidth = otruncwidth; + return 0; + } + bv->truncwidth = otruncwidth; + continue; + } + if (!doprint) + switch(*bv->fm) { + case '[': + while(idigit(*++bv->fm)); + while(*++bv->fm != ']'); + continue; + case '<': + while(*++bv->fm != '<'); + continue; + case '>': + while(*++bv->fm != '>'); + continue; + case 'D': + if(bv->fm[1]=='{') + while(*++bv->fm != '}'); + continue; + default: + continue; + } + switch (*bv->fm) { + case '~': + promptpath(pwd, arg, 1); + break; + case 'd': + case '/': + promptpath(pwd, arg, 0); + break; + case 'c': + case '.': + promptpath(pwd, arg ? arg : 1, 1); + break; + case 'C': + promptpath(pwd, arg ? arg : 1, 0); + break; + case 'N': + promptpath(scriptname ? scriptname : argzero, arg, 0); + break; + case 'h': + case '!': + addbufspc(DIGBUFSIZE); + convbase(bv->bp, curhist, 10); + bv->bp += strlen(bv->bp); + break; + case 'j': + for (numjobs = 0, j = 1; j <= maxjob; j++) + if (jobtab[j].stat && jobtab[j].procs && + !(jobtab[j].stat & STAT_NOPRINT)) numjobs++; + addbufspc(DIGBUFSIZE); + sprintf(bv->bp, "%d", numjobs); + bv->bp += strlen(bv->bp); + break; + case 'M': + queue_signals(); + if ((hostnam = getsparam("HOST"))) + stradd(hostnam); + unqueue_signals(); + break; + case 'm': + if (!arg) + arg++; + queue_signals(); + if (!(hostnam = getsparam("HOST"))) { + unqueue_signals(); + break; + } + if (arg < 0) { + for (ss = hostnam + strlen(hostnam); ss > hostnam; ss--) + if (ss[-1] == '.' && !++arg) + break; + stradd(ss); + } else { + for (ss = hostnam; *ss; ss++) + if (*ss == '.' && !--arg) + break; + stradd(*ss ? dupstrpfx(hostnam, ss - hostnam) : hostnam); + } + unqueue_signals(); + break; + case 'S': + txtchangeset(txtchangep, TXTSTANDOUT, TXTNOSTANDOUT); + txtset(TXTSTANDOUT); + tsetcap(TCSTANDOUTBEG, TSC_PROMPT); + break; + case 's': + txtchangeset(txtchangep, TXTNOSTANDOUT, TXTSTANDOUT); + txtunset(TXTSTANDOUT); + tsetcap(TCSTANDOUTEND, TSC_PROMPT|TSC_DIRTY); + break; + case 'B': + txtchangeset(txtchangep, TXTBOLDFACE, TXTNOBOLDFACE); + txtset(TXTBOLDFACE); + tsetcap(TCBOLDFACEBEG, TSC_PROMPT|TSC_DIRTY); + break; + case 'b': + txtchangeset(txtchangep, TXTNOBOLDFACE, TXTBOLDFACE); + txtunset(TXTBOLDFACE); + tsetcap(TCALLATTRSOFF, TSC_PROMPT|TSC_DIRTY); + break; + case 'U': + txtchangeset(txtchangep, TXTUNDERLINE, TXTNOUNDERLINE); + txtset(TXTUNDERLINE); + tsetcap(TCUNDERLINEBEG, TSC_PROMPT); + break; + case 'u': + txtchangeset(txtchangep, TXTNOUNDERLINE, TXTUNDERLINE); + txtunset(TXTUNDERLINE); + tsetcap(TCUNDERLINEEND, TSC_PROMPT|TSC_DIRTY); + break; + case 'F': + arg = parsecolorchar(arg, 1); + if (arg >= 0 && !(arg & TXTNOFGCOLOUR)) { + txtchangeset(txtchangep, arg & TXT_ATTR_FG_ON_MASK, + TXTNOFGCOLOUR | TXT_ATTR_FG_COL_MASK); + txtunset(TXT_ATTR_FG_COL_MASK); + txtset(arg & TXT_ATTR_FG_ON_MASK); + set_colour_attribute(arg, COL_SEQ_FG, TSC_PROMPT); + break; + } + /* else FALLTHROUGH */ + case 'f': + txtchangeset(txtchangep, TXTNOFGCOLOUR, TXT_ATTR_FG_ON_MASK); + txtunset(TXT_ATTR_FG_ON_MASK); + set_colour_attribute(TXTNOFGCOLOUR, COL_SEQ_FG, TSC_PROMPT); + break; + case 'K': + arg = parsecolorchar(arg, 0); + if (arg >= 0 && !(arg & TXTNOBGCOLOUR)) { + txtchangeset(txtchangep, arg & TXT_ATTR_BG_ON_MASK, + TXTNOBGCOLOUR | TXT_ATTR_BG_COL_MASK); + txtunset(TXT_ATTR_BG_COL_MASK); + txtset(arg & TXT_ATTR_BG_ON_MASK); + set_colour_attribute(arg, COL_SEQ_BG, TSC_PROMPT); + break; + } + /* else FALLTHROUGH */ + case 'k': + txtchangeset(txtchangep, TXTNOBGCOLOUR, TXT_ATTR_BG_ON_MASK); + txtunset(TXT_ATTR_BG_ON_MASK); + set_colour_attribute(TXTNOBGCOLOUR, COL_SEQ_BG, TSC_PROMPT); + break; + case '[': + if (idigit(*++bv->fm)) + arg = zstrtol(bv->fm, &bv->fm, 10); + if (!prompttrunc(arg, ']', doprint, endchar, txtchangep)) + return *bv->fm; + break; + case '<': + case '>': + /* Test (minus) here so -0 means "at the right margin" */ + if (minus) { + *bv->bp = '\0'; + countprompt(bv->bufline, &t0, 0, 0); + arg = zterm_columns - t0 + arg; + if (arg <= 0) + arg = 1; + } + if (!prompttrunc(arg, *bv->fm, doprint, endchar, txtchangep)) + return *bv->fm; + break; + case '{': /*}*/ + if (!bv->dontcount++) { + addbufspc(1); + *bv->bp++ = Inpar; + } + if (arg <= 0) + break; + /* else */ + /* FALLTHROUGH */ + case 'G': + if (arg > 0) { + addbufspc(arg); + while (arg--) + *bv->bp++ = Nularg; + } else { + addbufspc(1); + *bv->bp++ = Nularg; + } + break; + case /*{*/ '}': + if (bv->trunccount && bv->trunccount >= bv->dontcount) + return *bv->fm; + if (bv->dontcount && !--bv->dontcount) { + addbufspc(1); + *bv->bp++ = Outpar; + } + break; + case 't': + case '@': + case 'T': + case '*': + case 'w': + case 'W': + case 'D': + { + char *tmfmt, *dd, *tmbuf = NULL; + + switch (*bv->fm) { + case 'T': + tmfmt = "%K:%M"; + break; + case '*': + tmfmt = "%K:%M:%S"; + break; + case 'w': + tmfmt = "%a %f"; + break; + case 'W': + tmfmt = "%m/%d/%y"; + break; + case 'D': + if (bv->fm[1] == '{' /*}*/) { + for (ss = bv->fm + 2; *ss && *ss != /*{*/ '}'; ss++) + if(*ss == '\\' && ss[1]) + ss++; + dd = tmfmt = tmbuf = zalloc(ss - bv->fm); + for (ss = bv->fm + 2; *ss && *ss != /*{*/ '}'; + ss++) { + if(*ss == '\\' && ss[1]) + ss++; + *dd++ = *ss; + } + *dd = 0; + bv->fm = ss - !*ss; + if (!*tmfmt) { + free(tmbuf); + continue; + } + } else + tmfmt = "%y-%m-%d"; + break; + default: + tmfmt = "%l:%M%p"; + break; + } + zgettime(&ts); + tm = localtime(&ts.tv_sec); + /* + * Hack because strftime won't say how + * much space it actually needs. Try to add it + * a few times until it works. Some formats don't + * actually have a length, so we could go on for + * ever. + */ + for(j = 0, t0 = strlen(tmfmt)*8; j < 3; j++, t0*=2) { + addbufspc(t0); + if ((len = ztrftime(bv->bp, t0, tmfmt, tm, ts.tv_nsec)) + >= 0) + break; + } + /* There is enough room for this because addbufspc(t0) + * allocates room for t0 * 2 bytes. */ + if (len >= 0) + metafy(bv->bp, len, META_NOALLOC); + bv->bp += strlen(bv->bp); + zsfree(tmbuf); + break; + } + case 'n': + stradd(get_username()); + break; + case 'l': + if (*ttystrname) { + ss = (strncmp(ttystrname, "/dev/tty", 8) ? + ttystrname + 5 : ttystrname + 8); + stradd(ss); + } else + stradd("()"); + break; + case 'y': + if (*ttystrname) { + ss = (strncmp(ttystrname, "/dev/", 5) ? + ttystrname : ttystrname + 5); + stradd(ss); + } else + stradd("()"); + break; + case 'L': + addbufspc(DIGBUFSIZE); +#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD) + sprintf(bv->bp, "%lld", shlvl); +#else + sprintf(bv->bp, "%ld", (long)shlvl); +#endif + bv->bp += strlen(bv->bp); + break; + case '?': + addbufspc(DIGBUFSIZE); +#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD) + sprintf(bv->bp, "%lld", lastval); +#else + sprintf(bv->bp, "%ld", (long)lastval); +#endif + bv->bp += strlen(bv->bp); + break; + case '%': + case ')': + addbufspc(1); + *bv->bp++ = *bv->fm; + break; + case '#': + addbufspc(1); + *bv->bp++ = privasserted() ? '#' : '%'; + break; + case 'v': + if (!arg) + arg = 1; + else if (arg < 0) + arg += arrlen(psvar) + 1; + if (arg > 0 && arrlen_ge(psvar, arg)) + stradd(psvar[arg - 1]); + break; + case 'E': + tsetcap(TCCLEAREOL, TSC_PROMPT); + break; + case '^': + if (cmdsp) { + if (arg >= 0) { + if (arg > cmdsp || arg == 0) + arg = cmdsp; + for (t0 = cmdsp - 1; arg--; t0--) { + stradd(cmdnames[cmdstack[t0]]); + if (arg) { + addbufspc(1); + *bv->bp++=' '; + } + } + } else { + arg = -arg; + if (arg > cmdsp) + arg = cmdsp; + for (t0 = arg - 1; arg--; t0--) { + stradd(cmdnames[cmdstack[t0]]); + if (arg) { + addbufspc(1); + *bv->bp++=' '; + } + } + } + } + break; + case '_': + if (cmdsp) { + if (arg >= 0) { + if (arg > cmdsp || arg == 0) + arg = cmdsp; + for (t0 = cmdsp - arg; arg--; t0++) { + stradd(cmdnames[cmdstack[t0]]); + if (arg) { + addbufspc(1); + *bv->bp++=' '; + } + } + } else { + arg = -arg; + if (arg > cmdsp) + arg = cmdsp; + for (t0 = 0; arg--; t0++) { + stradd(cmdnames[cmdstack[t0]]); + if (arg) { + addbufspc(1); + *bv->bp++=' '; + } + } + } + } + break; + case 'r': + if(bv->rstring) + stradd(bv->rstring); + break; + case 'R': + if(bv->Rstring) + stradd(bv->Rstring); + break; + case 'e': + { + int depth = 0; + Funcstack fsptr = funcstack; + while (fsptr) { + depth++; + fsptr = fsptr->prev; + } + addbufspc(DIGBUFSIZE); + sprintf(bv->bp, "%d", depth); + bv->bp += strlen(bv->bp); + break; + } + case 'I': + if (funcstack && funcstack->tp != FS_SOURCE && + !IN_EVAL_TRAP()) { + /* + * We're in a function or an eval with + * EVALLINENO. Calculate the line number in + * the file. + */ + zlong flineno = lineno + funcstack->flineno; + /* take account of eval line nos. starting at 1 */ + if (funcstack->tp == FS_EVAL) + lineno--; + addbufspc(DIGBUFSIZE); +#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD) + sprintf(bv->bp, "%lld", flineno); +#else + sprintf(bv->bp, "%ld", (long)flineno); +#endif + bv->bp += strlen(bv->bp); + break; + } + /* else we're in a file and lineno is already correct */ + /* FALLTHROUGH */ + case 'i': + addbufspc(DIGBUFSIZE); +#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD) + sprintf(bv->bp, "%lld", lineno); +#else + sprintf(bv->bp, "%ld", (long)lineno); +#endif + bv->bp += strlen(bv->bp); + break; + case 'x': + if (funcstack && funcstack->tp != FS_SOURCE && + !IN_EVAL_TRAP()) + promptpath(funcstack->filename ? funcstack->filename : "", + arg, 0); + else + promptpath(scriptfilename ? scriptfilename : argzero, + arg, 0); + break; + case '\0': + return 0; + case Meta: + bv->fm++; + break; + } + } else if(*bv->fm == '!' && isset(PROMPTBANG)) { + if(doprint) { + if(bv->fm[1] == '!') { + bv->fm++; + addbufspc(1); + pputc('!'); + } else { + addbufspc(DIGBUFSIZE); + convbase(bv->bp, curhist, 10); + bv->bp += strlen(bv->bp); + } + } + } else { + char c = *bv->fm == Meta ? *++bv->fm ^ 32 : *bv->fm; + + if (doprint) { + addbufspc(1); + pputc(c); + } + } + } + + return *bv->fm; +} + +/* pputc adds a character to the buffer, metafying. There must * + * already be space. */ + +/**/ +static void +pputc(char c) +{ + if (imeta(c)) { + *bv->bp++ = Meta; + c ^= 32; + } + *bv->bp++ = c; + if (c == '\n' && !bv->dontcount) + bv->bufline = bv->bp; +} + +/* Make sure there is room for `need' more characters in the buffer. */ + +/**/ +static void +addbufspc(int need) +{ + need *= 2; /* for metafication */ + if((bv->bp - bv->buf) + need > bv->bufspc) { + int bo = bv->bp - bv->buf; + int bo1 = bv->bp1 ? bv->bp1 - bv->buf : -1; + ptrdiff_t bufline_off = bv->bufline ? bv->bufline - bv->buf : -1; + + if(need & 255) + need = (need | 255) + 1; + bv->buf = realloc(bv->buf, bv->bufspc += need); + memset(bv->buf + bv->bufspc - need, 0, need); + bv->bp = bv->buf + bo; + if(bo1 != -1) + bv->bp1 = bv->buf + bo1; + if (bufline_off != -1) + bv->bufline = bv->buf + bufline_off; + } +} + +/* stradd() adds a metafied string to the prompt, * + * in a visible representation. */ + +/**/ +void +stradd(char *d) +{ +#ifdef MULTIBYTE_SUPPORT + char *ums, *ups; + int upslen, eol = 0; + mbstate_t mbs; + + memset(&mbs, 0, sizeof mbs); + ums = ztrdup(d); + ups = unmetafy(ums, &upslen); + + /* + * We now have a raw string of possibly multibyte characters. + * Read each character one by one. + */ + while (upslen > 0) { + wchar_t cc; + char *pc; + size_t cnt = eol ? MB_INVALID : mbrtowc(&cc, ups, upslen, &mbs); + + switch (cnt) { + case MB_INCOMPLETE: + eol = 1; + /* FALL THROUGH */ + case MB_INVALID: + /* Bad character. Take the next byte on its own. */ + pc = nicechar(*ups); + cnt = 1; + memset(&mbs, 0, sizeof mbs); + break; + case 0: + cnt = 1; + /* FALL THROUGH */ + default: + /* Take full wide character in one go */ + mb_charinit(); + pc = wcs_nicechar(cc, NULL, NULL); + break; + } + /* Keep output as metafied string. */ + addbufspc(strlen(pc)); + + upslen -= cnt; + ups += cnt; + + /* Put printed representation into the buffer */ + while (*pc) + *bv->bp++ = *pc++; + } + + free(ums); +#else + char *ps, *pc; + addbufspc(niceztrlen(d)); + /* This loop puts the nice representation of the string into the + * prompt buffer. */ + for (ps = d; *ps; ps++) { + for (pc = nicechar(*ps == Meta ? *++ps^32 : *ps); *pc; pc++) + *bv->bp++ = *pc; + } +#endif +} + +/* tsetcap(), among other things, can write a termcap string into the buffer. */ + +/**/ +mod_export void +tsetcap(int cap, int flags) +{ + if (tccan(cap) && !isset(SINGLELINEZLE) && + !(termflags & (TERM_NOUP|TERM_BAD|TERM_UNKNOWN))) { + switch (flags & TSC_OUTPUT_MASK) { + case TSC_RAW: + tputs(tcstr[cap], 1, putraw); + break; + case 0: + default: + tputs(tcstr[cap], 1, putshout); + break; + case TSC_PROMPT: + if (!bv->dontcount) { + addbufspc(1); + *bv->bp++ = Inpar; + } + tputs(tcstr[cap], 1, putstr); + if (!bv->dontcount) { + int glitch = 0; + + if (cap == TCSTANDOUTBEG || cap == TCSTANDOUTEND) + glitch = tgetnum("sg"); + else if (cap == TCUNDERLINEBEG || cap == TCUNDERLINEEND) + glitch = tgetnum("ug"); + if(glitch < 0) + glitch = 0; + addbufspc(glitch + 1); + while(glitch--) + *bv->bp++ = Nularg; + *bv->bp++ = Outpar; + } + break; + } + + if (flags & TSC_DIRTY) { + flags &= ~TSC_DIRTY; + if (txtisset(TXTBOLDFACE) && cap != TCBOLDFACEBEG) + tsetcap(TCBOLDFACEBEG, flags); + if (txtisset(TXTSTANDOUT)) + tsetcap(TCSTANDOUTBEG, flags); + if (txtisset(TXTUNDERLINE)) + tsetcap(TCUNDERLINEBEG, flags); + if (txtisset(TXTFGCOLOUR)) + set_colour_attribute(txtattrmask, COL_SEQ_FG, TSC_PROMPT); + if (txtisset(TXTBGCOLOUR)) + set_colour_attribute(txtattrmask, COL_SEQ_BG, TSC_PROMPT); + } + } +} + +/**/ +int +putstr(int d) +{ + addbufspc(1); + pputc(d); + return 0; +} + +/* + * Count height etc. of a prompt string returned by promptexpand(). + * This depends on the current terminal width, and tabs and + * newlines require nontrivial processing. + * Passing `overf' as -1 means to ignore columns (absolute width). + * + * If multibyte is enabled, take account of multibyte characters + * by locating them and finding out their screen width. + */ + +/**/ +mod_export void +countprompt(char *str, int *wp, int *hp, int overf) +{ + int w = 0, h = 1; + int s = 1; +#ifdef MULTIBYTE_SUPPORT + int wcw, multi = 0; + char inchar; + mbstate_t mbs; + wchar_t wc; + + memset(&mbs, 0, sizeof(mbs)); +#endif + + for (; *str; str++) { + if (w > zterm_columns && overf >= 0) { + w = 0; + h++; + } + /* + * Input string should be metafied, so tokens in it should + * be real tokens, even if there are multibyte characters. + */ + if (*str == Inpar) + s = 0; + else if (*str == Outpar) + s = 1; + else if (*str == Nularg) + w++; + else if (s) { + if (*str == Meta) { +#ifdef MULTIBYTE_SUPPORT + inchar = *++str ^ 32; +#else + str++; +#endif + } else { +#ifdef MULTIBYTE_SUPPORT + /* + * Don't look for tab or newline in the middle + * of a multibyte character. Otherwise, we are + * relying on the character set being an extension + * of ASCII so it's safe to test a single byte. + */ + if (!multi) { +#endif + if (*str == '\t') { + w = (w | 7) + 1; + continue; + } else if (*str == '\n') { + w = 0; + h++; + continue; + } +#ifdef MULTIBYTE_SUPPORT + } + + inchar = *str; +#endif + } + +#ifdef MULTIBYTE_SUPPORT + switch (mbrtowc(&wc, &inchar, 1, &mbs)) { + case MB_INCOMPLETE: + /* Character is incomplete -- keep looking. */ + multi = 1; + break; + case MB_INVALID: + memset(&mbs, 0, sizeof mbs); + /* Invalid character: assume single width. */ + multi = 0; + w++; + break; + case 0: + multi = 0; + break; + default: + /* + * If the character isn't printable, WCWIDTH() returns + * -1. We assume width 1. + */ + wcw = WCWIDTH(wc); + if (wcw >= 0) + w += wcw; + else + w++; + multi = 0; + break; + } +#else + w++; +#endif + } + } + /* + * multi may still be set if we were in the middle of the character. + * This isn't easy to handle generally; just assume there's no + * output. + */ + if(w >= zterm_columns && overf >= 0) { + if (!overf || w > zterm_columns) { + w = 0; + h++; + } + } + if(wp) + *wp = w; + if(hp) + *hp = h; +} + +/**/ +static int +prompttrunc(int arg, int truncchar, int doprint, int endchar, + unsigned int *txtchangep) +{ + if (arg > 0) { + char ch = *bv->fm, *ptr, *truncstr; + int truncatleft = ch == '<'; + int w = bv->bp - bv->buf; + + /* + * If there is already a truncation active, return so that + * can be finished, backing up so that the new truncation + * can be started afterwards. + */ + if (bv->truncwidth) { + while (*--bv->fm != '%') + ; + bv->fm--; + return 0; + } + + bv->truncwidth = arg; + if (*bv->fm != ']') + bv->fm++; + while (*bv->fm && *bv->fm != truncchar) { + if (*bv->fm == '\\' && bv->fm[1]) + ++bv->fm; + addbufspc(1); + *bv->bp++ = *bv->fm++; + } + if (!*bv->fm) + return 0; + if (bv->bp - bv->buf == w && truncchar == ']') { + addbufspc(1); + *bv->bp++ = '<'; + } + ptr = bv->buf + w; /* addbufspc() may have realloc()'d bv->buf */ + /* + * Now: + * bv->buf is the start of the output prompt buffer + * ptr is the start of the truncation string + * bv->bp is the end of the truncation string + */ + truncstr = ztrduppfx(ptr, bv->bp - ptr); + + bv->bp = ptr; + w = bv->bp - bv->buf; + bv->fm++; + bv->trunccount = bv->dontcount; + putpromptchar(doprint, endchar, txtchangep); + bv->trunccount = 0; + ptr = bv->buf + w; /* putpromptchar() may have realloc()'d */ + *bv->bp = '\0'; + /* + * Now: + * ptr is the start of the truncation string and also + * where we need to start putting any truncated output + * bv->bp is the end of the string we have just added, which + * may need truncating. + */ + + /* + * w below is screen width if multibyte support is enabled + * (note that above it was a raw string pointer difference). + * It's the full width of the string we may need to truncate. + * + * bv->truncwidth has come from the user, so we interpret this + * as a screen width, too. + */ + countprompt(ptr, &w, 0, -1); + if (w > bv->truncwidth) { + /* + * We need to truncate. t points to the truncation string + * -- which is inserted literally, without nice + * representation. twidth is its printing width, and maxwidth + * is the amount of the main string that we want to keep. + * Note that if the truncation string is longer than the + * truncation length (twidth > bv->truncwidth), the truncation + * string is used in full. + */ + char *t = truncstr; + int fullen = bv->bp - ptr; + int twidth, maxwidth; + int ntrunc = strlen(t); + + twidth = MB_METASTRWIDTH(t); + if (twidth < bv->truncwidth) { + maxwidth = bv->truncwidth - twidth; + /* + * It's not safe to assume there are no invisible substrings + * just because the width is less than the full string + * length since there may be multibyte characters. + */ + addbufspc(ntrunc+1); + /* may have realloc'd */ + ptr = bv->bp - fullen; + + if (truncatleft) { + /* + * To truncate at the left, selectively copy + * maxwidth bytes from the main prompt, preceded + * by the truncation string in full. + * + * We're overwriting the string containing the + * text to be truncated, so copy it. We've + * just ensured there's sufficient space at the + * end of the prompt string. + * + * Pointer into text to be truncated. + */ + char *fulltextptr, *fulltext; + int remw; +#ifdef MULTIBYTE_SUPPORT + mbstate_t mbs; + memset(&mbs, 0, sizeof mbs); +#endif + + fulltextptr = fulltext = ptr + ntrunc; + memmove(fulltext, ptr, fullen); + fulltext[fullen] = '\0'; + + /* Copy the truncstr into place. */ + while (*t) + *ptr++ = *t++; + + /* + * Find the point in the text at which we should + * start copying, i.e. when the remaining width + * is less than or equal to the maximum width. + */ + remw = w; + while (remw > maxwidth && *fulltextptr) { + if (*fulltextptr == Inpar) { + /* + * Text marked as invisible: copy + * regardless, since we don't know what + * this does. It only affects the width + * if there are Nularg's present. + * However, even in that case we + * can't break the sequence down, so + * we still loop over the entire group. + */ + for (;;) { + *ptr++ = *fulltextptr; + if (*fulltextptr == '\0' || + *fulltextptr++ == Outpar) + break; + if (fulltextptr[-1] == Nularg) + remw--; + } + } else { +#ifdef MULTIBYTE_SUPPORT + /* + * Normal text: build up a multibyte character. + */ + char inchar; + wchar_t cc; + int wcw; + + /* + * careful: string is still metafied (we + * need that because we don't know a + * priori when to stop and the resulting + * string must be metafied). + */ + if (*fulltextptr == Meta) + inchar = *++fulltextptr ^ 32; + else + inchar = *fulltextptr; + fulltextptr++; + switch (mbrtowc(&cc, &inchar, 1, &mbs)) { + case MB_INCOMPLETE: + /* Incomplete multibyte character. */ + break; + case MB_INVALID: + /* Reset invalid state. */ + memset(&mbs, 0, sizeof mbs); + /* FALL THROUGH */ + case 0: + /* Assume a single-byte character. */ + remw--; + break; + default: + wcw = WCWIDTH(cc); + if (wcw >= 0) + remw -= wcw; + else + remw--; + break; + } +#else + /* Single byte character */ + if (*fulltextptr == Meta) + fulltextptr++; + fulltextptr++; + remw--; +#endif + } + } + + /* + * Now simply copy the rest of the text. Still + * metafied, so this is easy. + */ + while (*fulltextptr) + *ptr++ = *fulltextptr++; + /* Mark the end of copying */ + bv->bp = ptr; + } else { + /* + * Truncating at the right is easier: just leave + * enough characters until we have reached the + * maximum width. + */ + char *skiptext = ptr; +#ifdef MULTIBYTE_SUPPORT + mbstate_t mbs; + memset(&mbs, 0, sizeof mbs); +#endif + + while (maxwidth > 0 && *skiptext) { + if (*skiptext == Inpar) { + /* see comment on left truncation above */ + for (;;) { + if (*skiptext == '\0' || + *skiptext++ == Outpar) + break; + if (skiptext[-1] == Nularg) + maxwidth--; + } + } else { +#ifdef MULTIBYTE_SUPPORT + char inchar; + wchar_t cc; + int wcw; + + if (*skiptext == Meta) + inchar = *++skiptext ^ 32; + else + inchar = *skiptext; + skiptext++; + switch (mbrtowc(&cc, &inchar, 1, &mbs)) { + case MB_INCOMPLETE: + /* Incomplete character. */ + break; + case MB_INVALID: + /* Reset invalid state. */ + memset(&mbs, 0, sizeof mbs); + /* FALL THROUGH */ + case 0: + /* Assume a single-byte character. */ + maxwidth--; + break; + default: + wcw = WCWIDTH(cc); + if (wcw >= 0) + maxwidth -= wcw; + else + maxwidth--; + break; + } +#else + if (*skiptext == Meta) + skiptext++; + skiptext++; + maxwidth--; +#endif + } + } + /* + * We don't need the visible text from now on, + * but we'd better copy any invisible bits. + * History dictates that these go after the + * truncation string. This is sensible since + * they may, for example, turn off an effect which + * should apply to all text at this point. + * + * Copy the truncstr. + */ + ptr = skiptext; + while (*t) + *ptr++ = *t++; + bv->bp = ptr; + if (*skiptext) { + /* Move remaining text so we don't overwrite it */ + memmove(bv->bp, skiptext, strlen(skiptext)+1); + skiptext = bv->bp; + + /* + * Copy anything we want, updating bv->bp + */ + while (*skiptext) { + if (*skiptext == Inpar) { + for (;;) { + *bv->bp++ = *skiptext; + if (*skiptext == Outpar || + *skiptext == '\0') + break; + skiptext++; + } + } + else + skiptext++; + } + } + } + } else { + /* Just copy truncstr; no other text appears. */ + while (*t) + *ptr++ = *t++; + bv->bp = ptr; + } + *bv->bp = '\0'; + } + zsfree(truncstr); + bv->truncwidth = 0; + /* + * We may have returned early from the previous putpromptchar * + * because we found another truncation following this one. * + * In that case we need to do the rest now. * + */ + if (!*bv->fm) + return 0; + if (*bv->fm != endchar) { + bv->fm++; + /* + * With bv->truncwidth set to zero, we always reach endchar * + * (or the terminating NULL) this time round. * + */ + if (!putpromptchar(doprint, endchar, txtchangep)) + return 0; + } + /* Now we have to trick it into matching endchar again */ + bv->fm--; + } else { + if (*bv->fm != endchar) + bv->fm++; + while(*bv->fm && *bv->fm != truncchar) { + if (*bv->fm == '\\' && bv->fm[1]) + bv->fm++; + bv->fm++; + } + if (bv->truncwidth || !*bv->fm) + return 0; + } + return 1; +} + +/**/ +void +cmdpush(int cmdtok) +{ + if (cmdsp >= 0 && cmdsp < CMDSTACKSZ) + cmdstack[cmdsp++] = (unsigned char)cmdtok; +} + +/**/ +void +cmdpop(void) +{ + if (cmdsp <= 0) { + DPUTS(1, "BUG: cmdstack empty"); + fflush(stderr); + } else + cmdsp--; +} + + +/***************************************************************************** + * Utilities dealing with colour and other forms of highlighting. + * + * These are shared by prompts and by zle, so it's easiest to have them + * in the main shell. + *****************************************************************************/ + +/* Defines standard ANSI colour names in index order */ +static const char *ansi_colours[] = { + "black", "red", "green", "yellow", "blue", "magenta", "cyan", "white", + "default", NULL +}; + +/* Defines the available types of highlighting */ +struct highlight { + const char *name; + int mask_on; + int mask_off; +}; + +static const struct highlight highlights[] = { + { "none", 0, TXT_ATTR_ON_MASK }, + { "bold", TXTBOLDFACE, 0 }, + { "standout", TXTSTANDOUT, 0 }, + { "underline", TXTUNDERLINE, 0 }, + { NULL, 0, 0 } +}; + +/* + * Return index of ANSI colour for which *teststrp is an abbreviation. + * Any non-alphabetic character ends the abbreviation. + * 8 is the special value for default (note this is *not* the + * right sequence for default which is typically 9). + * -1 is failure. + */ + +static int +match_named_colour(const char **teststrp) +{ + const char *teststr = *teststrp, *end, **cptr; + int len; + + for (end = teststr; ialpha(*end); end++) + ; + len = end - teststr; + *teststrp = end; + + for (cptr = ansi_colours; *cptr; cptr++) { + if (!strncmp(teststr, *cptr, len)) + return cptr - ansi_colours; + } + + return -1; +} + +/* + * Match just the colour part of a highlight specification. + * If teststrp is NULL, use the already parsed numeric colour. + * Return the attributes to set in the attribute variable. + * Return -1 for out of range. Does not check the character + * following the colour specification. + */ + +/**/ +mod_export int +match_colour(const char **teststrp, int is_fg, int colour) +{ + int shft, on, named = 0, tc; + + if (teststrp) { + if ((named = ialpha(**teststrp))) { + colour = match_named_colour(teststrp); + if (colour == 8) { + /* default */ + return is_fg ? TXTNOFGCOLOUR : TXTNOBGCOLOUR; + } + } + else + colour = (int)zstrtol(*teststrp, (char **)teststrp, 10); + } + if (colour < 0 || colour >= 256) + return -1; + if (is_fg) { + shft = TXT_ATTR_FG_COL_SHIFT; + on = TXTFGCOLOUR; + tc = TCFGCOLOUR; + } else { + shft = TXT_ATTR_BG_COL_SHIFT; + on = TXTBGCOLOUR; + tc = TCBGCOLOUR; + } + /* + * Try termcap for numbered characters if posible. + * Don't for named characters, since our best bet + * of getting the names right is with ANSI sequences. + */ + if (!named && tccan(tc)) { + if (tccolours >= 0 && colour >= tccolours) { + /* + * Out of range of termcap colours. + * Can we assume ANSI colours work? + */ + if (colour > 7) + return -1; /* No. */ + } else { + /* + * We can handle termcap colours and the number + * is in range, so use termcap. + */ + on |= is_fg ? TXT_ATTR_FG_TERMCAP : + TXT_ATTR_BG_TERMCAP; + } + } + return on | (colour << shft); +} + +/* + * Match a set of highlights in the given teststr. + * Set *on_var to reflect the values found. + */ + +/**/ +mod_export void +match_highlight(const char *teststr, int *on_var) +{ + int found = 1; + + *on_var = 0; + while (found && *teststr) { + const struct highlight *hl; + + found = 0; + if (strpfx("fg=", teststr) || strpfx("bg=", teststr)) { + int is_fg = (teststr[0] == 'f'), atr; + + teststr += 3; + atr = match_colour(&teststr, is_fg, 0); + if (*teststr == ',') + teststr++; + else if (*teststr) + break; + found = 1; + /* skip out of range colours but keep scanning attributes */ + if (atr >= 0) + *on_var |= atr; + } else { + for (hl = highlights; hl->name; hl++) { + if (strpfx(hl->name, teststr)) { + const char *val = teststr + strlen(hl->name); + + if (*val == ',') + val++; + else if (*val) + break; + + *on_var |= hl->mask_on; + *on_var &= ~hl->mask_off; + teststr = val; + found = 1; + } + } + } + } +} + +/* + * Count or output a string for colour information: used + * by output_highlight(). + */ + +static int +output_colour(int colour, int fg_bg, int use_tc, char *buf) +{ + int atrlen = 3, len; + char *ptr = buf; + if (buf) { + strcpy(ptr, fg_bg == COL_SEQ_FG ? "fg=" : "bg="); + ptr += 3; + } + /* colour should only be > 7 if using termcap but let's be safe */ + if (use_tc || colour > 7) { + char digbuf[DIGBUFSIZE]; + sprintf(digbuf, "%d", colour); + len = strlen(digbuf); + atrlen += len; + if (buf) + strcpy(ptr, digbuf); + } else { + len = strlen(ansi_colours[colour]); + atrlen += len; + if (buf) + strcpy(ptr, ansi_colours[colour]); + } + + return atrlen; +} + +/* + * Count the length needed for outputting highlighting information + * as a string based on the bits for the attributes. + * + * If buf is not NULL, output the strings into the buffer, too. + * As conventional with strings, the allocated length should be + * at least the returned value plus 1 for the NUL byte. + */ + +/**/ +mod_export int +output_highlight(int atr, char *buf) +{ + const struct highlight *hp; + int atrlen = 0, len; + char *ptr = buf; + + if (atr & TXTFGCOLOUR) { + len = output_colour(txtchangeget(atr, TXT_ATTR_FG_COL), + COL_SEQ_FG, + (atr & TXT_ATTR_FG_TERMCAP), + ptr); + atrlen += len; + if (buf) + ptr += len; + } + if (atr & TXTBGCOLOUR) { + if (atrlen) { + atrlen++; + if (buf) { + strcpy(ptr, ","); + ptr++; + } + } + len = output_colour(txtchangeget(atr, TXT_ATTR_BG_COL), + COL_SEQ_BG, + (atr & TXT_ATTR_BG_TERMCAP), + ptr); + atrlen += len; + if (buf) + ptr += len; + } + for (hp = highlights; hp->name; hp++) { + if (hp->mask_on & atr) { + if (atrlen) { + atrlen++; + if (buf) { + strcpy(ptr, ","); + ptr++; + } + } + len = strlen(hp->name); + atrlen += len; + if (buf) { + strcpy(ptr, hp->name); + ptr += len; + } + } + } + + if (atrlen == 0) { + if (buf) + strcpy(ptr, "none"); + return 4; + } + return atrlen; +} + +/* Structure and array for holding special colour terminal sequences */ + +/* Start of escape sequence for foreground colour */ +#define TC_COL_FG_START "\033[3" +/* End of escape sequence for foreground colour */ +#define TC_COL_FG_END "m" +/* Code to reset foreground colour */ +#define TC_COL_FG_DEFAULT "9" + +/* Start of escape sequence for background colour */ +#define TC_COL_BG_START "\033[4" +/* End of escape sequence for background colour */ +#define TC_COL_BG_END "m" +/* Code to reset background colour */ +#define TC_COL_BG_DEFAULT "9" + +struct colour_sequences { + char *start; /* Escape sequence start */ + char *end; /* Escape sequence terminator */ + char *def; /* Code to reset default colour */ +}; +static struct colour_sequences fg_bg_sequences[2]; + +/* + * We need a buffer for colour sequence composition. It may + * vary depending on the sequences set. However, it's inefficient + * allocating it separately every time we send a colour sequence, + * so do it once per refresh. + */ +static char *colseq_buf; + +/* + * Count how often this has been allocated, for recursive usage. + */ +static int colseq_buf_allocs; + +/**/ +void +set_default_colour_sequences(void) +{ + fg_bg_sequences[COL_SEQ_FG].start = ztrdup(TC_COL_FG_START); + fg_bg_sequences[COL_SEQ_FG].end = ztrdup(TC_COL_FG_END); + fg_bg_sequences[COL_SEQ_FG].def = ztrdup(TC_COL_FG_DEFAULT); + + fg_bg_sequences[COL_SEQ_BG].start = ztrdup(TC_COL_BG_START); + fg_bg_sequences[COL_SEQ_BG].end = ztrdup(TC_COL_BG_END); + fg_bg_sequences[COL_SEQ_BG].def = ztrdup(TC_COL_BG_DEFAULT); +} + +static void +set_colour_code(char *str, char **var) +{ + char *keyseq; + int len; + + zsfree(*var); + keyseq = getkeystring(str, &len, GETKEYS_BINDKEY, NULL); + *var = metafy(keyseq, len, META_DUP); +} + +/* Allocate buffer for colour code composition */ + +/**/ +mod_export void +allocate_colour_buffer(void) +{ + char **atrs; + int lenfg, lenbg, len; + + if (colseq_buf_allocs++) + return; + + atrs = getaparam("zle_highlight"); + if (atrs) { + for (; *atrs; atrs++) { + if (strpfx("fg_start_code:", *atrs)) { + set_colour_code(*atrs + 14, &fg_bg_sequences[COL_SEQ_FG].start); + } else if (strpfx("fg_default_code:", *atrs)) { + set_colour_code(*atrs + 16, &fg_bg_sequences[COL_SEQ_FG].def); + } else if (strpfx("fg_end_code:", *atrs)) { + set_colour_code(*atrs + 12, &fg_bg_sequences[COL_SEQ_FG].end); + } else if (strpfx("bg_start_code:", *atrs)) { + set_colour_code(*atrs + 14, &fg_bg_sequences[COL_SEQ_BG].start); + } else if (strpfx("bg_default_code:", *atrs)) { + set_colour_code(*atrs + 16, &fg_bg_sequences[COL_SEQ_BG].def); + } else if (strpfx("bg_end_code:", *atrs)) { + set_colour_code(*atrs + 12, &fg_bg_sequences[COL_SEQ_BG].end); + } + } + } + + lenfg = strlen(fg_bg_sequences[COL_SEQ_FG].def); + /* always need 1 character for non-default code */ + if (lenfg < 1) + lenfg = 1; + lenfg += strlen(fg_bg_sequences[COL_SEQ_FG].start) + + strlen(fg_bg_sequences[COL_SEQ_FG].end); + + lenbg = strlen(fg_bg_sequences[COL_SEQ_BG].def); + /* always need 1 character for non-default code */ + if (lenbg < 1) + lenbg = 1; + lenbg += strlen(fg_bg_sequences[COL_SEQ_BG].start) + + strlen(fg_bg_sequences[COL_SEQ_BG].end); + + len = lenfg > lenbg ? lenfg : lenbg; + colseq_buf = (char *)zalloc(len+1); +} + +/* Free the colour buffer previously allocated. */ + +/**/ +mod_export void +free_colour_buffer(void) +{ + if (--colseq_buf_allocs) + return; + + DPUTS(!colseq_buf, "Freeing colour sequence buffer without alloc"); + /* Free buffer for colour code composition */ + free(colseq_buf); + colseq_buf = NULL; +} + +/* + * Handle outputting of a colour for prompts or zle. + * colour is the numeric colour, 0 to 255 (or less if termcap + * says fewer are supported). + * fg_bg indicates if we're changing the foreground or background. + * tc indicates the termcap code to use, if appropriate. + * def indicates if we're resetting the default colour. + * use_termcap indicates if we should use termcap to output colours. + * flags is either 0 or TSC_PROMPT. + */ + +/**/ +mod_export void +set_colour_attribute(int atr, int fg_bg, int flags) +{ + char *ptr; + int do_free, is_prompt = (flags & TSC_PROMPT) ? 1 : 0; + int colour, tc, def, use_termcap; + + if (fg_bg == COL_SEQ_FG) { + colour = txtchangeget(atr, TXT_ATTR_FG_COL); + tc = TCFGCOLOUR; + def = txtchangeisset(atr, TXTNOFGCOLOUR); + use_termcap = txtchangeisset(atr, TXT_ATTR_FG_TERMCAP); + } else { + colour = txtchangeget(atr, TXT_ATTR_BG_COL); + tc = TCBGCOLOUR; + def = txtchangeisset(atr, TXTNOBGCOLOUR); + use_termcap = txtchangeisset(atr, TXT_ATTR_BG_TERMCAP); + } + + /* + * If we're not restoring the default, and either have a + * colour value that is too large for ANSI, or have been told + * to use the termcap sequence, try to use the termcap sequence. + * + * We have already sanitised the values we allow from the + * highlighting variables, so much of this shouldn't be + * necessary at this point, but we might as well be safe. + */ + if (!def && (colour > 7 || use_termcap)) { + /* + * We can if it's available, and either we couldn't get + * the maximum number of colours, or the colour is in range. + */ + if (tccan(tc) && (tccolours < 0 || colour < tccolours)) + { + if (is_prompt) + { + if (!bv->dontcount) { + addbufspc(1); + *bv->bp++ = Inpar; + } + tputs(tgoto(tcstr[tc], colour, colour), 1, putstr); + if (!bv->dontcount) { + addbufspc(1); + *bv->bp++ = Outpar; + } + } else { + tputs(tgoto(tcstr[tc], colour, colour), 1, putshout); + } + /* That worked. */ + return; + } + /* + * Nope, that didn't work. + * If 0 to 7, assume standard ANSI works, otherwise it won't. + */ + if (colour > 7) + return; + } + + if ((do_free = (colseq_buf == NULL))) { + /* This can happen when moving the cursor in trashzle() */ + allocate_colour_buffer(); + } + + strcpy(colseq_buf, fg_bg_sequences[fg_bg].start); + + ptr = colseq_buf + strlen(colseq_buf); + if (def) { + strcpy(ptr, fg_bg_sequences[fg_bg].def); + while (*ptr) + ptr++; + } else + *ptr++ = colour + '0'; + strcpy(ptr, fg_bg_sequences[fg_bg].end); + + if (is_prompt) { + if (!bv->dontcount) { + addbufspc(1); + *bv->bp++ = Inpar; + } + tputs(colseq_buf, 1, putstr); + if (!bv->dontcount) { + addbufspc(1); + *bv->bp++ = Outpar; + } + } else + tputs(colseq_buf, 1, putshout); + + if (do_free) + free_colour_buffer(); +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/prototypes.h b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/prototypes.h new file mode 100644 index 00000000..e3db4f5e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/prototypes.h @@ -0,0 +1,134 @@ +/* + * prototypes.h - prototypes header file + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#ifndef HAVE_STDLIB_H +char *malloc _((size_t)); +char *realloc _((void *, size_t)); +char *calloc _((size_t, size_t)); +#endif + +#if !(defined(USES_TERMCAP_H) || defined(USES_TERM_H)) +/* + * These prototypes are only used where we don't have the + * headers. In some cases they need tweaking. + * TBD: we'd much prefer to get hold of the header where + * these are defined. + */ +#ifdef _AIX +#define TC_CONST const +#else +#define TC_CONST +#endif +extern int tgetent _((char *bp, TC_CONST char *name)); +extern int tgetnum _((char *id)); +extern int tgetflag _((char *id)); +extern char *tgetstr _((char *id, char **area)); +extern int tputs _((TC_CONST char *cp, int affcnt, int (*outc) (int))); +#undef TC_CONST +#endif + +/* + * Some systems that do have termcap headers nonetheless don't + * declare tgoto, so we detect if that is missing separately. + */ +#ifdef TGOTO_PROTO_MISSING +char *tgoto(const char *cap, int col, int row); +#endif + +/* MISSING PROTOTYPES FOR VARIOUS OPERATING SYSTEMS */ + +#if defined(__hpux) && defined(_HPUX_SOURCE) && !defined(_XPG4_EXTENDED) +# define SELECT_ARG_2_T int * +#else +# define SELECT_ARG_2_T fd_set * +#endif + +#ifdef __osf__ +char *mktemp _((char *)); +#endif + +#if defined(__osf__) && defined(__alpha) && defined(__GNUC__) +/* Digital cc does not need these prototypes, gcc does need them */ +# ifndef HAVE_IOCTL_PROTO +int ioctl _((int d, unsigned long request, void *argp)); +# endif +# ifndef HAVE_MKNOD_PROTO +int mknod _((const char *pathname, int mode, dev_t device)); +# endif +int nice _((int increment)); +int select _((int nfds, fd_set * readfds, fd_set * writefds, fd_set * exceptfds, struct timeval *timeout)); +#endif + +#if defined(DGUX) && defined(__STDC__) +/* Just plain missing. */ +extern int getrlimit _((int resource, struct rlimit *rlp)); +extern int setrlimit _((int resource, const struct rlimit *rlp)); +extern int getrusage _((int who, struct rusage *rusage)); +extern int gettimeofday _((struct timeval *tv, struct timezone *tz)); +extern int wait3 _((union wait *wait_status, int options, struct rusage *rusage)); +extern int getdomainname _((char *name, int maxlength)); +extern int select _((int nfds, fd_set * readfds, fd_set * writefds, fd_set * exceptfds, struct timeval *timeout)); +#endif /* DGUX and __STDC__ */ + +#ifdef __NeXT__ +extern pid_t getppid(void); +#endif + +#if defined(__sun__) && !defined(__SVR4) /* SunOS */ +extern char *strerror _((int errnum)); +#endif + +/**************************************************/ +/*** prototypes for functions built in compat.c ***/ +#ifndef HAVE_STRSTR +extern char *strstr _((const char *s, const char *t)); +#endif + +#ifndef HAVE_GETHOSTNAME +extern int gethostname _((char *name, size_t namelen)); +#endif + +#ifndef HAVE_GETTIMEOFDAY +extern int gettimeofday _((struct timeval *tv, struct timezone *tz)); +#endif + +#ifndef HAVE_DIFFTIME +extern double difftime _((time_t t2, time_t t1)); +#endif + +#ifndef HAVE_STRERROR +extern char *strerror _((int errnum)); +#endif + +/*** end of prototypes for functions in compat.c ***/ +/***************************************************/ + +#ifndef HAVE_MEMMOVE +extern void bcopy _((const void *, void *, size_t)); +#endif diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/signals.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/signals.c new file mode 100644 index 00000000..20c6fdf4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/signals.c @@ -0,0 +1,1479 @@ +/* + * signals.c - signals handling code + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "signals.pro" + +/* Array describing the state of each signal: an element contains * + * 0 for the default action or some ZSIG_* flags ored together. */ + +/**/ +mod_export int sigtrapped[VSIGCOUNT]; + +/* + * Trap programme lists for each signal. + * + * If (sigtrapped[sig] & ZSIG_FUNC) is set, this isn't used. + * The corresponding shell function is used instead. + * + * Otherwise, if sigtrapped[sig] is not zero, this is NULL when a signal + * is to be ignored, and if not NULL contains the programme list to be + * eval'd. + */ + +/**/ +mod_export Eprog siglists[VSIGCOUNT]; + +/* Total count of trapped signals */ + +/**/ +mod_export int nsigtrapped; + +/* Running an exit trap? */ + +/**/ +int in_exit_trap; + +/* + * Flag that exit trap has been set in POSIX mode. + * The setter's expectation is therefore that it is run + * on programme exit, not function exit. + */ + +/**/ +static int exit_trap_posix; + +/* Variables used by signal queueing */ + +/**/ +mod_export int queueing_enabled, queue_front, queue_rear; +/**/ +mod_export int signal_queue[MAX_QUEUE_SIZE]; +/**/ +mod_export sigset_t signal_mask_queue[MAX_QUEUE_SIZE]; +#ifdef DEBUG +/**/ +mod_export int queue_in; +#endif + +/* Variables used by trap queueing */ + +/**/ +mod_export int trap_queueing_enabled, trap_queue_front, trap_queue_rear; +/**/ +mod_export int trap_queue[MAX_QUEUE_SIZE]; + +/* This is only used on machines that don't understand signal sets. * + * On SYSV machines this will represent the signals that are blocked * + * (held) using sighold. On machines which can't block signals at * + * all, we will simulate this by ignoring them and remembering them * + * in this variable. */ +#if !defined(POSIX_SIGNALS) && !defined(BSD_SIGNALS) +static sigset_t blocked_set; +#endif + +#ifdef POSIX_SIGNALS +# define signal_jmp_buf sigjmp_buf +# define signal_setjmp(b) sigsetjmp((b),1) +# define signal_longjmp(b,n) siglongjmp((b),(n)) +#else +# define signal_jmp_buf jmp_buf +# define signal_setjmp(b) setjmp(b) +# define signal_longjmp(b,n) longjmp((b),(n)) +#endif + +#ifdef NO_SIGNAL_BLOCKING +# define signal_process(sig) signal_ignore(sig) +# define signal_reset(sig) install_handler(sig) +#else +# define signal_process(sig) ; +# define signal_reset(sig) ; +#endif + +/* Install signal handler for given signal. * + * If possible, we want to make sure that interrupted * + * system calls are not restarted. */ + +/**/ +mod_export void +install_handler(int sig) +{ +#ifdef POSIX_SIGNALS + struct sigaction act; + + act.sa_handler = (SIGNAL_HANDTYPE) zhandler; + sigemptyset(&act.sa_mask); /* only block sig while in handler */ + act.sa_flags = 0; +# ifdef SA_INTERRUPT /* SunOS 4.x */ + if (interact) + act.sa_flags |= SA_INTERRUPT; /* make sure system calls are not restarted */ +# endif + sigaction(sig, &act, (struct sigaction *)NULL); +#else +# ifdef BSD_SIGNALS + struct sigvec vec; + + vec.sv_handler = (SIGNAL_HANDTYPE) zhandler; + vec.sv_mask = sigmask(sig); /* mask out this signal while in handler */ +# ifdef SV_INTERRUPT + vec.sv_flags = SV_INTERRUPT; /* make sure system calls are not restarted */ +# endif + sigvec(sig, &vec, (struct sigvec *)NULL); +# else +# ifdef SYSV_SIGNALS + /* we want sigset rather than signal because it will * + * block sig while in handler. signal usually doesn't */ + sigset(sig, zhandler); +# else /* NO_SIGNAL_BLOCKING (bummer) */ + signal(sig, zhandler); + +# endif /* SYSV_SIGNALS */ +# endif /* BSD_SIGNALS */ +#endif /* POSIX_SIGNALS */ +} + +/* enable ^C interrupts */ + +/**/ +mod_export void +intr(void) +{ + if (interact) + install_handler(SIGINT); +} + +/* disable ^C interrupts */ + +#if 0 /**/ +void +nointr(void) +{ + if (interact) + signal_ignore(SIGINT); +} +#endif + +/* temporarily block ^C interrupts */ + +/**/ +mod_export void +holdintr(void) +{ + if (interact) + signal_block(signal_mask(SIGINT)); +} + +/* release ^C interrupts */ + +/**/ +mod_export void +noholdintr(void) +{ + if (interact) + signal_unblock(signal_mask(SIGINT)); +} + +/* create a signal mask containing * + * only the given signal */ + +/**/ +mod_export sigset_t +signal_mask(int sig) +{ + sigset_t set; + + sigemptyset(&set); + if (sig) + sigaddset(&set, sig); + return set; +} + +/* Block the signals in the given signal * + * set. Return the old signal set. */ + +/**/ +#ifndef BSD_SIGNALS + +/**/ +mod_export sigset_t +signal_block(sigset_t set) +{ + sigset_t oset; + +#ifdef POSIX_SIGNALS + sigprocmask(SIG_BLOCK, &set, &oset); + +#else +# ifdef SYSV_SIGNALS + int i; + + oset = blocked_set; + for (i = 1; i <= NSIG; ++i) { + if (sigismember(&set, i) && !sigismember(&blocked_set, i)) { + sigaddset(&blocked_set, i); + sighold(i); + } + } +# else /* NO_SIGNAL_BLOCKING */ +/* We will just ignore signals if the system doesn't have * + * the ability to block them. */ + int i; + + oset = blocked_set; + for (i = 1; i <= NSIG; ++i) { + if (sigismember(&set, i) && !sigismember(&blocked_set, i)) { + sigaddset(&blocked_set, i); + signal_ignore(i); + } + } +# endif /* SYSV_SIGNALS */ +#endif /* POSIX_SIGNALS */ + + return oset; +} + +/**/ +#endif /* BSD_SIGNALS */ + +/* Unblock the signals in the given signal * + * set. Return the old signal set. */ + +/**/ +mod_export sigset_t +signal_unblock(sigset_t set) +{ + sigset_t oset; + +#ifdef POSIX_SIGNALS + sigprocmask(SIG_UNBLOCK, &set, &oset); +#else +# ifdef BSD_SIGNALS + sigfillset(&oset); + oset = sigsetmask(oset); + sigsetmask(oset & ~set); +# else +# ifdef SYSV_SIGNALS + int i; + + oset = blocked_set; + for (i = 1; i <= NSIG; ++i) { + if (sigismember(&set, i) && sigismember(&blocked_set, i)) { + sigdelset(&blocked_set, i); + sigrelse(i); + } + } +# else /* NO_SIGNAL_BLOCKING */ +/* On systems that can't block signals, we are just ignoring them. So * + * to unblock signals, we just reenable the signal handler for them. */ + int i; + + oset = blocked_set; + for (i = 1; i <= NSIG; ++i) { + if (sigismember(&set, i) && sigismember(&blocked_set, i)) { + sigdelset(&blocked_set, i); + install_handler(i); + } + } +# endif /* SYSV_SIGNALS */ +# endif /* BSD_SIGNALS */ +#endif /* POSIX_SIGNALS */ + + return oset; +} + +/* set the process signal mask to * + * be the given signal mask */ + +/**/ +mod_export sigset_t +signal_setmask(sigset_t set) +{ + sigset_t oset; + +#ifdef POSIX_SIGNALS + sigprocmask(SIG_SETMASK, &set, &oset); +#else +# ifdef BSD_SIGNALS + oset = sigsetmask(set); +# else +# ifdef SYSV_SIGNALS + int i; + + oset = blocked_set; + for (i = 1; i <= NSIG; ++i) { + if (sigismember(&set, i) && !sigismember(&blocked_set, i)) { + sigaddset(&blocked_set, i); + sighold(i); + } else if (!sigismember(&set, i) && sigismember(&blocked_set, i)) { + sigdelset(&blocked_set, i); + sigrelse(i); + } + } +# else /* NO_SIGNAL_BLOCKING */ + int i; + + oset = blocked_set; + for (i = 1; i < NSIG; ++i) { + if (sigismember(&set, i) && !sigismember(&blocked_set, i)) { + sigaddset(&blocked_set, i); + signal_ignore(i); + } else if (!sigismember(&set, i) && sigismember(&blocked_set, i)) { + sigdelset(&blocked_set, i); + install_handler(i); + } + } +# endif /* SYSV_SIGNALS */ +# endif /* BSD_SIGNALS */ +#endif /* POSIX_SIGNALS */ + + return oset; +} + +#if defined(NO_SIGNAL_BLOCKING) +static int suspend_longjmp = 0; +static signal_jmp_buf suspend_jmp_buf; +#endif + +/**/ +int +signal_suspend(UNUSED(int sig), int wait_cmd) +{ + int ret; + +#if defined(POSIX_SIGNALS) || defined(BSD_SIGNALS) + sigset_t set; +# if defined(POSIX_SIGNALS) && defined(BROKEN_POSIX_SIGSUSPEND) + sigset_t oset; +# endif + + sigemptyset(&set); + + /* SIGINT from the terminal driver needs to interrupt "wait" + * and to cause traps to fire, but otherwise should not be + * handled by the shell until after any foreground job has + * a chance to decide whether to exit on that signal. + */ + if (!(wait_cmd || isset(TRAPSASYNC) || + (sigtrapped[SIGINT] & ~ZSIG_IGNORED))) + sigaddset(&set, SIGINT); +#endif /* POSIX_SIGNALS || BSD_SIGNALS */ + +#ifdef POSIX_SIGNALS +# ifdef BROKEN_POSIX_SIGSUSPEND + sigprocmask(SIG_SETMASK, &set, &oset); + ret = pause(); + sigprocmask(SIG_SETMASK, &oset, NULL); +# else /* not BROKEN_POSIX_SIGSUSPEND */ + ret = sigsuspend(&set); +# endif /* BROKEN_POSIX_SIGSUSPEND */ +#else /* not POSIX_SIGNALS */ +# ifdef BSD_SIGNALS + ret = sigpause(set); +# else +# ifdef SYSV_SIGNALS + ret = sigpause(sig); + +# else /* NO_SIGNAL_BLOCKING */ + /* need to use signal_longjmp to make this race-free * + * between the child_unblock() and pause() */ + if (signal_setjmp(suspend_jmp_buf) == 0) { + suspend_longjmp = 1; /* we want to signal_longjmp after catching signal */ + child_unblock(); /* do we need to do wait_cmd stuff as well? */ + ret = pause(); + } + suspend_longjmp = 0; /* turn off using signal_longjmp since we are past * + * the pause() function. */ +# endif /* SYSV_SIGNALS */ +# endif /* BSD_SIGNALS */ +#endif /* POSIX_SIGNALS */ + + return ret; +} + +/* last signal we handled: race prone, or what? */ +/**/ +int last_signal; + +/* + * Wait for any processes that have changed state. + * + * The main use for this is in the SIGCHLD handler. However, + * we also use it to pick up status changes of jobs when + * updating jobs. + */ +/**/ +void +wait_for_processes(void) +{ + /* keep WAITING until no more child processes to reap */ + for (;;) { + /* save the errno, since WAIT may change it */ + int old_errno = errno; + int status; + Job jn; + Process pn; + pid_t pid; + pid_t *procsubpid = &cmdoutpid; + int *procsubval = &cmdoutval; + int cont = 0; + struct execstack *es = exstack; + + /* + * Reap the child process. + * If we want usage information, we need to use wait3. + */ +#if defined(HAVE_WAIT3) || defined(HAVE_WAITPID) +# ifdef WCONTINUED +# define WAITFLAGS (WNOHANG|WUNTRACED|WCONTINUED) +# else +# define WAITFLAGS (WNOHANG|WUNTRACED) +# endif +#endif +#ifdef HAVE_WAIT3 +# ifdef HAVE_GETRUSAGE + struct rusage ru; + + pid = wait3((void *)&status, WAITFLAGS, &ru); +# else + pid = wait3((void *)&status, WAITFLAGS, NULL); +# endif +#else +# ifdef HAVE_WAITPID + pid = waitpid(-1, &status, WAITFLAGS); +# else + pid = wait(&status); +# endif +#endif + + if (!pid) /* no more children to reap */ + break; + + /* check if child returned was from process substitution */ + for (;;) { + if (pid == *procsubpid) { + *procsubpid = 0; + if (WIFSIGNALED(status)) + *procsubval = (0200 | WTERMSIG(status)); + else + *procsubval = WEXITSTATUS(status); + use_cmdoutval = 1; + get_usage(); + cont = 1; + break; + } + if (!es) + break; + procsubpid = &es->cmdoutpid; + procsubval = &es->cmdoutval; + es = es->next; + } + if (cont) + continue; + + /* check for WAIT error */ + if (pid == -1) { + if (errno != ECHILD) + zerr("wait failed: %e", errno); + /* WAIT changed errno, so restore the original */ + errno = old_errno; + break; + } + + /* This is necessary to be sure queueing_enabled > 0 when + * we enter printjob() from update_job(), so that we don't + * decrement to zero in should_report_time() and improperly + * run other handlers in the middle of processing this one */ + queue_signals(); + + /* + * Find the process and job containing this pid and + * update it. + */ + if (findproc(pid, &jn, &pn, 0)) { + if (((jn->stat & STAT_BUILTIN) || + (list_pipe && + (thisjob == -1 || + (jobtab[thisjob].stat & STAT_BUILTIN)))) && + WIFSTOPPED(status) && WSTOPSIG(status) == SIGTSTP) { + killjb(jn, SIGCONT); + zwarn("job can't be suspended"); + } else { +#if defined(HAVE_WAIT3) && defined(HAVE_GETRUSAGE) + struct timezone dummy_tz; + gettimeofday(&pn->endtime, &dummy_tz); +#ifdef WIFCONTINUED + if (WIFCONTINUED(status)) + pn->status = SP_RUNNING; + else +#endif + pn->status = status; + pn->ti = ru; +#else + update_process(pn, status); +#endif + if (WIFEXITED(status) && + pn->pid == jn->gleader && + killpg(pn->pid, 0) == -1) { + jn->gleader = 0; + if (!(jn->stat & STAT_NOSTTY)) { + /* + * This PID was in control of the terminal; + * reclaim terminal now it has exited. + * It's still possible some future forked + * process of this job will become group + * leader, however. + */ + attachtty(mypgrp); + } + } + } + update_job(jn); + } else if (findproc(pid, &jn, &pn, 1)) { + pn->status = status; + update_job(jn); + } else { + /* If not found, update the shell record of time spent by + * children in sub processes anyway: otherwise, this + * will get added on to the next found process that + * terminates. + */ + get_usage(); + } + /* + * Accumulate a list of older jobs. We only do this for + * background jobs, which is something in the job table + * that's not marked as in the current shell or as shell builtin + * and is not equal to the current foreground job. + */ + if (jn && !(jn->stat & (STAT_CURSH|STAT_BUILTIN)) && + jn - jobtab != thisjob) { + int val = (WIFSIGNALED(status) ? + 0200 | WTERMSIG(status) : + (WIFSTOPPED(status) ? + 0200 | WEXITSTATUS(status) : + WEXITSTATUS(status))); + addbgstatus(pid, val); + } + + unqueue_signals(); + } +} + +/* the signal handler */ + +/**/ +mod_export void +zhandler(int sig) +{ + sigset_t newmask, oldmask; + +#if defined(NO_SIGNAL_BLOCKING) + int do_jump; + signal_jmp_buf jump_to; +#endif + + last_signal = sig; + signal_process(sig); + + sigfillset(&newmask); + /* Block all signals temporarily */ + oldmask = signal_block(newmask); + +#if defined(NO_SIGNAL_BLOCKING) + /* do we need to longjmp to signal_suspend */ + do_jump = suspend_longjmp; + /* In case a SIGCHLD somehow arrives */ + suspend_longjmp = 0; + + /* Traps can cause nested signal_suspend() */ + if (sig == SIGCHLD) { + if (do_jump) { + /* Copy suspend_jmp_buf */ + jump_to = suspend_jmp_buf; + } + } +#endif + + /* Are we queueing signals now? */ + if (queueing_enabled) { + int temp_rear = ++queue_rear % MAX_QUEUE_SIZE; + + DPUTS(temp_rear == queue_front, "BUG: signal queue full"); + /* Make sure it's not full (extremely unlikely) */ + if (temp_rear != queue_front) { + /* ok, not full, so add to queue */ + queue_rear = temp_rear; + /* save signal caught */ + signal_queue[queue_rear] = sig; + /* save current signal mask */ + signal_mask_queue[queue_rear] = oldmask; + } + signal_reset(sig); + return; + } + + /* Reset signal mask, signal traps ok now */ + signal_setmask(oldmask); + + switch (sig) { + case SIGCHLD: + wait_for_processes(); + break; + + case SIGPIPE: + if (!handletrap(SIGPIPE)) { + if (!interact) + _exit(SIGPIPE); + else if (!isatty(SHTTY)) { + stopmsg = 1; + zexit(SIGPIPE, 1); + } + } + break; + + case SIGHUP: + if (!handletrap(SIGHUP)) { + stopmsg = 1; + zexit(SIGHUP, 1); + } + break; + + case SIGINT: + if (!handletrap(SIGINT)) { + if ((isset(PRIVILEGED) || isset(RESTRICTED)) && + isset(INTERACTIVE) && (noerrexit & NOERREXIT_SIGNAL)) + zexit(SIGINT, 1); + if (list_pipe || chline || simple_pline) { + breaks = loops; + errflag |= ERRFLAG_INT; + inerrflush(); + check_cursh_sig(SIGINT); + } + lastval = 128 + SIGINT; + } + break; + +#ifdef SIGWINCH + case SIGWINCH: + adjustwinsize(1); /* check window size and adjust */ + (void) handletrap(SIGWINCH); + break; +#endif + + case SIGALRM: + if (!handletrap(SIGALRM)) { + int idle = ttyidlegetfn(NULL); + int tmout = getiparam("TMOUT"); + if (idle >= 0 && idle < tmout) + alarm(tmout - idle); + else { + /* + * We want to exit now. + * Cancel all errors, including a user interrupt + * which is now redundant. + */ + errflag = noerrs = 0; + zwarn("timeout"); + stopmsg = 1; + zexit(SIGALRM, 1); + } + } + break; + + default: + (void) handletrap(sig); + break; + } /* end of switch(sig) */ + + signal_reset(sig); + +/* This is used to make signal_suspend() race-free */ +#if defined(NO_SIGNAL_BLOCKING) + if (do_jump) + signal_longjmp(jump_to, 1); +#endif + +} /* handler */ + + +/* SIGHUP any jobs left running */ + +/**/ +void +killrunjobs(int from_signal) +{ + int i, killed = 0; + + if (unset(HUP)) + return; + for (i = 1; i <= maxjob; i++) + if ((from_signal || i != thisjob) && (jobtab[i].stat & STAT_LOCKED) && + !(jobtab[i].stat & STAT_NOPRINT) && + !(jobtab[i].stat & STAT_STOPPED)) { + if (jobtab[i].gleader != getpid() && + killpg(jobtab[i].gleader, SIGHUP) != -1) + killed++; + } + if (killed) + zwarn("warning: %d jobs SIGHUPed", killed); +} + + +/* send a signal to a job (simply involves kill if monitoring is on) */ + +/**/ +int +killjb(Job jn, int sig) +{ + Process pn; + int err = 0; + + if (jobbing) { + if (jn->stat & STAT_SUPERJOB) { + if (sig == SIGCONT) { + for (pn = jobtab[jn->other].procs; pn; pn = pn->next) + if (killpg(pn->pid, sig) == -1) + if (kill(pn->pid, sig) == -1 && errno != ESRCH) + err = -1; + + /* + * Note this does not kill the last process, + * which is assumed to be the one controlling the + * subjob, i.e. the forked zsh that was originally + * list_pipe_pid... + */ + for (pn = jn->procs; pn->next; pn = pn->next) + if (kill(pn->pid, sig) == -1 && errno != ESRCH) + err = -1; + + /* + * ...we only continue that once the external processes + * currently associated with the subjob are finished. + */ + if (!jobtab[jn->other].procs && pn) + if (kill(pn->pid, sig) == -1 && errno != ESRCH) + err = -1; + + return err; + } + if (killpg(jobtab[jn->other].gleader, sig) == -1 && errno != ESRCH) + err = -1; + + if (killpg(jn->gleader, sig) == -1 && errno != ESRCH) + err = -1; + + return err; + } + else + return killpg(jn->gleader, sig); + } + for (pn = jn->procs; pn; pn = pn->next) { + /* + * Do not kill this job's process if it's already dead as its + * pid could have been reused by the system. + * As the PID doesn't exist don't return an error. + */ + if (pn->status == SP_RUNNING || WIFSTOPPED(pn->status)) { + /* + * kill -0 on a job is pointless. We still call kill() for each process + * in case the user cares about it but we ignore its outcome. + */ + if ((err = kill(pn->pid, sig)) == -1 && errno != ESRCH && sig != 0) + return -1; + } + } + return err; +} + +/* + * List for saving traps. We don't usually have that many traps + * at once, so just use a linked list. + */ +struct savetrap { + int sig, flags, local, posix; + void *list; +}; + +static LinkList savetraps; +static int dontsavetrap; + +/* + * Save the current trap by copying it. This does nothing to + * the existing value of sigtrapped or siglists. + */ + +static void +dosavetrap(int sig, int level) +{ + struct savetrap *st; + st = (struct savetrap *)zalloc(sizeof(*st)); + st->sig = sig; + st->local = level; + st->posix = (sig == SIGEXIT) ? exit_trap_posix : 0; + if ((st->flags = sigtrapped[sig]) & ZSIG_FUNC) { + /* + * Get the old function: this assumes we haven't added + * the new one yet. + */ + Shfunc shf, newshf = NULL; + if ((shf = (Shfunc)gettrapnode(sig, 1))) { + /* Copy the node for saving */ + newshf = (Shfunc) zshcalloc(sizeof(*newshf)); + newshf->node.nam = ztrdup(shf->node.nam); + newshf->node.flags = shf->node.flags; + newshf->funcdef = dupeprog(shf->funcdef, 0); + if (shf->node.flags & PM_LOADDIR) { + dircache_set(&newshf->filename, shf->filename); + } else { + newshf->filename = ztrdup(shf->filename); + } + if (shf->sticky) { + newshf->sticky = sticky_emulation_dup(shf->sticky, 0); + } else + newshf->sticky = 0; + if (shf->node.flags & PM_UNDEFINED) + newshf->funcdef->shf = newshf; + } +#ifdef DEBUG + else dputs("BUG: no function present with function trap flag set."); +#endif + DPUTS(siglists[sig], "BUG: function signal has eval list, too."); + st->list = newshf; + } else if (sigtrapped[sig]) { + st->list = siglists[sig] ? dupeprog(siglists[sig], 0) : NULL; + } else { + DPUTS(siglists[sig], "BUG: siglists not null for untrapped signal"); + st->list = NULL; + } + if (!savetraps) + savetraps = znewlinklist(); + /* + * Put this at the front of the list + */ + zinsertlinknode(savetraps, (LinkNode)savetraps, st); +} + + +/* + * Set a trap: note this does not handle manipulation of + * the function table for TRAPNAL functions. + * + * sig is the signal number. + * + * l is the list to be eval'd for a trap defined with the "trap" + * builtin and should be NULL for a function trap. + * + * flags includes any additional flags to be or'd into sigtrapped[sig], + * in particular ZSIG_FUNC; the basic flags will be assigned within + * settrap. + */ + +/**/ +mod_export int +settrap(int sig, Eprog l, int flags) +{ + if (sig == -1) + return 1; + if (jobbing && (sig == SIGTTOU || sig == SIGTSTP || sig == SIGTTIN)) { + zerr("can't trap SIG%s in interactive shells", sigs[sig]); + return 1; + } + + /* + * Call unsettrap() unconditionally, to make sure trap is saved + * if necessary. + */ + queue_signals(); + unsettrap(sig); + + DPUTS((flags & ZSIG_FUNC) && l, + "BUG: trap function has passed eval list, too"); + siglists[sig] = l; + if (!(flags & ZSIG_FUNC) && empty_eprog(l)) { + sigtrapped[sig] = ZSIG_IGNORED; + if (sig && sig <= SIGCOUNT && +#ifdef SIGWINCH + sig != SIGWINCH && +#endif + sig != SIGCHLD) + signal_ignore(sig); + } else { + nsigtrapped++; + sigtrapped[sig] = ZSIG_TRAPPED; + if (sig && sig <= SIGCOUNT && +#ifdef SIGWINCH + sig != SIGWINCH && +#endif + sig != SIGCHLD) + install_handler(sig); + } + sigtrapped[sig] |= flags; + /* + * Note that introducing the locallevel does not affect whether + * sigtrapped[sig] is zero or not, i.e. a test without a mask + * works just the same. + */ + if (sig == SIGEXIT) { + /* Make POSIX behaviour of EXIT trap sticky */ + exit_trap_posix = isset(POSIXTRAPS); + /* POSIX exit traps are not local. */ + if (!exit_trap_posix) + sigtrapped[sig] |= (locallevel << ZSIG_SHIFT); + } + else + sigtrapped[sig] |= (locallevel << ZSIG_SHIFT); + unqueue_signals(); + return 0; +} + +/**/ +void +unsettrap(int sig) +{ + HashNode hn; + + queue_signals(); + hn = removetrap(sig); + if (hn) + shfunctab->freenode(hn); + unqueue_signals(); +} + +/**/ +HashNode +removetrap(int sig) +{ + int trapped; + + if (sig == -1 || + (jobbing && (sig == SIGTTOU || sig == SIGTSTP || sig == SIGTTIN))) + return NULL; + + queue_signals(); + trapped = sigtrapped[sig]; + /* + * Note that we save the trap here even if there isn't an existing + * one, to aid in removing this one. However, if there's + * already one at the current locallevel we just overwrite it. + * + * Note we save EXIT traps based on the *current* setting of + * POSIXTRAPS --- so if there is POSIX EXIT trap set but + * we are in native mode it can be saved, replaced by a function + * trap, and then restored. + */ + if (!dontsavetrap && + (sig == SIGEXIT ? !isset(POSIXTRAPS) : isset(LOCALTRAPS)) && + locallevel && + (!trapped || locallevel > (sigtrapped[sig] >> ZSIG_SHIFT))) + dosavetrap(sig, locallevel); + + if (!trapped) { + unqueue_signals(); + return NULL; + } + if (sigtrapped[sig] & ZSIG_TRAPPED) + nsigtrapped--; + sigtrapped[sig] = 0; + if (sig == SIGINT && interact) { + /* PWS 1995/05/16: added test for interactive, also noholdintr() * + * as subshells ignoring SIGINT have it blocked from delivery */ + intr(); + noholdintr(); + } else if (sig == SIGHUP) + install_handler(sig); + else if (sig == SIGPIPE && interact && !forklevel) + install_handler(sig); + else if (sig && sig <= SIGCOUNT && +#ifdef SIGWINCH + sig != SIGWINCH && +#endif + sig != SIGCHLD) + signal_default(sig); + if (sig == SIGEXIT) + exit_trap_posix = 0; + + /* + * At this point we free the appropriate structs. If we don't + * want that to happen then either the function should already have been + * removed from shfunctab, or the entry in siglists should have been set + * to NULL. This is no longer necessary for saving traps as that + * copies the structures, so here we are remove the originals. + * That causes a little inefficiency, but a good deal more reliability. + */ + if (trapped & ZSIG_FUNC) { + HashNode node = gettrapnode(sig, 1); + + /* + * As in dosavetrap(), don't call removeshfuncnode() because + * that calls back into unsettrap(); + */ + if (node) + removehashnode(shfunctab, node->nam); + unqueue_signals(); + + return node; + } else if (siglists[sig]) { + freeeprog(siglists[sig]); + siglists[sig] = NULL; + } + unqueue_signals(); + + return NULL; +} + +/**/ +void +starttrapscope(void) +{ + /* No special SIGEXIT behaviour inside another trap. */ + if (intrap) + return; + + /* + * SIGEXIT needs to be restored at the current locallevel, + * so give it the next higher one. dosavetrap() is called + * automatically where necessary. + */ + if (sigtrapped[SIGEXIT] && !exit_trap_posix) { + locallevel++; + unsettrap(SIGEXIT); + locallevel--; + } +} + +/* + * Reset traps after the end of a function: must be called after + * endparamscope() so that the locallevel has been decremented. + */ + +/**/ +void +endtrapscope(void) +{ + LinkNode ln; + struct savetrap *st; + int exittr = 0; + void *exitfn = NULL; + + /* + * Remember the exit trap, but don't run it until + * after all the other traps have been put back. + * Don't do this inside another trap. + */ + if (!intrap && + !exit_trap_posix && (exittr = sigtrapped[SIGEXIT])) { + if (exittr & ZSIG_FUNC) { + exitfn = removehashnode(shfunctab, "TRAPEXIT"); + } else { + exitfn = siglists[SIGEXIT]; + siglists[SIGEXIT] = NULL; + } + if (sigtrapped[SIGEXIT] & ZSIG_TRAPPED) + nsigtrapped--; + sigtrapped[SIGEXIT] = 0; + } + + if (savetraps) { + while ((ln = firstnode(savetraps)) && + (st = (struct savetrap *) ln->dat) && + st->local > locallevel) { + int sig = st->sig; + + remnode(savetraps, ln); + + if (st->flags && (st->list != NULL)) { + /* prevent settrap from saving this */ + dontsavetrap++; + if (st->flags & ZSIG_FUNC) + settrap(sig, NULL, ZSIG_FUNC); + else + settrap(sig, (Eprog) st->list, 0); + if (sig == SIGEXIT) + exit_trap_posix = st->posix; + dontsavetrap--; + /* + * counting of nsigtrapped should presumably be handled + * in settrap... + */ + DPUTS((sigtrapped[sig] ^ st->flags) & ZSIG_TRAPPED, + "BUG: settrap didn't restore correct ZSIG_TRAPPED"); + if ((sigtrapped[sig] = st->flags) & ZSIG_FUNC) + shfunctab->addnode(shfunctab, ((Shfunc)st->list)->node.nam, + (Shfunc) st->list); + } else if (sigtrapped[sig]) { + /* + * Don't restore the old state if someone has set a + * POSIX-style exit trap --- allow this to propagate. + */ + if (sig != SIGEXIT || !exit_trap_posix) + unsettrap(sig); + } + + zfree(st, sizeof(*st)); + } + } + + if (exittr) { + /* + * We already made sure this wasn't set as a POSIX exit trap. + * We respect the user's intention when the trap in question + * was set. + */ + dotrapargs(SIGEXIT, &exittr, exitfn); + if (exittr & ZSIG_FUNC) + shfunctab->freenode((HashNode)exitfn); + else + freeeprog(exitfn); + } + DPUTS(!locallevel && savetraps && firstnode(savetraps), + "BUG: still saved traps outside all function scope"); +} + + +/* + * Decide whether a trap needs handling. + * If so, see if the trap should be run now or queued. + * Return 1 if the trap has been or will be handled. + * This only needs to be called in place of dotrap() in the + * signal handler, since it's only while waiting for children + * to exit that we queue traps. + */ +/**/ +static int +handletrap(int sig) +{ + if (!sigtrapped[sig]) + return 0; + + if (trap_queueing_enabled) + { + /* Code borrowed from signal queueing */ + int temp_rear = ++trap_queue_rear % MAX_QUEUE_SIZE; + + DPUTS(temp_rear == trap_queue_front, "BUG: trap queue full"); + /* If queue is not full... */ + if (temp_rear != trap_queue_front) { + trap_queue_rear = temp_rear; + trap_queue[trap_queue_rear] = sig; + } + return 1; + } + + dotrap(sig); + + if (sig == SIGALRM) + { + int tmout; + /* + * Reset the alarm. + * It seems slightly more natural to do this when the + * trap is run, rather than when it's queued, since + * the user doesn't see the latter. + */ + if ((tmout = getiparam("TMOUT"))) + alarm(tmout); + } + + return 1; +} + + +/* + * Queue traps if they shouldn't be run asynchronously, i.e. + * we're not in the wait builtin and TRAPSASYNC isn't set, when + * waiting for children to exit. + * + * Note that unlike signal queuing this should only be called + * in single matching pairs and can't be nested. It is + * only needed when waiting for a job or process to finish. + * + * There is presumably a race setting this up: we shouldn't be running + * traps between forking a foreground process and this point, either. + */ +/**/ +void +queue_traps(int wait_cmd) +{ + if (!isset(TRAPSASYNC) && !wait_cmd) { + /* + * Traps need to be handled synchronously, so + * enable queueing. + */ + trap_queueing_enabled = 1; + } +} + + +/* + * Disable trap queuing and run the traps. + */ +/**/ +void +unqueue_traps(void) +{ + trap_queueing_enabled = 0; + while (trap_queue_front != trap_queue_rear) { + trap_queue_front = (trap_queue_front + 1) % MAX_QUEUE_SIZE; + (void) handletrap(trap_queue[trap_queue_front]); + } +} + + +/* Execute a trap function for a given signal, possibly + * with non-standard sigtrapped & siglists values + */ + +/* Are we already executing a trap? */ +/**/ +int intrap; + +/* Is the current trap a function? */ + +/**/ +int trapisfunc; + +/* + * If the current trap is not a function, at what function depth + * did the trap get called? + */ +/**/ +int traplocallevel; + +/* + * sig is the signal number. + * *sigtr is the value to be taken as the field in sigtrapped (since + * that may have changed by this point if we are exiting). + * sigfn is an Eprog with a non-function eval list, or a Shfunc + * with a function trap. It may be NULL with an ignored signal. + */ + +/**/ +static void +dotrapargs(int sig, int *sigtr, void *sigfn) +{ + LinkList args; + char *name, num[4]; + int obreaks = breaks; + int oretflag = retflag; + int olastval = lastval; + int isfunc; + int traperr, new_trap_state, new_trap_return; + + /* if signal is being ignored or the trap function * + * is NULL, then return * + * * + * Also return if errflag is set. In fact, the code in the * + * function will test for this, but this way we keep status flags * + * intact without working too hard. Special cases (e.g. calling * + * a trap for SIGINT after the error flag was set) are handled * + * by the calling code. (PWS 1995/06/08). * + * * + * This test is now replicated in dotrap(). */ + if ((*sigtr & ZSIG_IGNORED) || !sigfn || errflag) + return; + + /* + * Never execute special (synchronous) traps inside other traps. + * This can cause unexpected code execution when more than one + * of these is set. + * + * The down side is that it's harder to debug traps. I don't think + * that's a big issue. + */ + if (intrap) { + switch (sig) { + case SIGEXIT: + case SIGDEBUG: + case SIGZERR: + return; + } + } + + queue_signals(); /* Any time we manage memory or global state */ + + intrap++; + *sigtr |= ZSIG_IGNORED; + + zcontext_save(); + /* execsave will save the old trap_return and trap_state */ + execsave(); + breaks = retflag = 0; + traplocallevel = locallevel; + runhookdef(BEFORETRAPHOOK, NULL); + if (*sigtr & ZSIG_FUNC) { + int osc = sfcontext, old_incompfunc = incompfunc; + HashNode hn = gettrapnode(sig, 0); + + args = znewlinklist(); + /* + * In case of multiple names, try to get + * a hint of the name in use from the function table. + * In special cases, e.g. EXIT traps, the function + * has already been removed. Then it's OK to + * use the standard name. + */ + if (hn) { + name = ztrdup(hn->nam); + } else { + name = (char *) zalloc(5 + strlen(sigs[sig])); + sprintf(name, "TRAP%s", sigs[sig]); + } + zaddlinknode(args, name); + sprintf(num, "%d", sig); + zaddlinknode(args, num); + + trap_return = -1; /* incremented by doshfunc */ + trap_state = TRAP_STATE_PRIMED; + trapisfunc = isfunc = 1; + + sfcontext = SFC_SIGNAL; + incompfunc = 0; + doshfunc((Shfunc)sigfn, args, 1); /* manages signal queueing */ + sfcontext = osc; + incompfunc= old_incompfunc; + freelinklist(args, (FreeFunc) NULL); + zsfree(name); + } else { + trap_return = -2; /* not incremented, used at current level */ + trap_state = TRAP_STATE_PRIMED; + trapisfunc = isfunc = 0; + + execode((Eprog)sigfn, 1, 0, "trap"); /* manages signal queueing */ + } + runhookdef(AFTERTRAPHOOK, NULL); + + traperr = errflag; + + /* Grab values before they are restored */ + new_trap_state = trap_state; + new_trap_return = trap_return; + + execrestore(); + zcontext_restore(); + + if (new_trap_state == TRAP_STATE_FORCE_RETURN && + /* zero return from function isn't special */ + !(isfunc && new_trap_return == 0)) { + if (isfunc) { + breaks = loops; + /* + * For SIGINT we behave the same as the default behaviour + * i.e. we set the error bit indicating an interrupt. + * We do this with SIGQUIT, too, even though we don't + * handle SIGQUIT by default. That's to try to make + * it behave a bit more like its normal behaviour when + * the trap handler has told us that's what it wants. + */ + if (sig == SIGINT || sig == SIGQUIT) + errflag |= ERRFLAG_INT; + else + errflag |= ERRFLAG_ERROR; + } + lastval = new_trap_return; + /* return triggered */ + retflag = 1; + } else { + if (traperr && !EMULATION(EMULATE_SH)) + lastval = 1; + else { + /* + * With no explicit forced return, we keep the + * lastval from before the trap ran. + */ + lastval = olastval; + } + if (try_tryflag) { + if (traperr) + errflag |= ERRFLAG_ERROR; + else + errflag &= ~ERRFLAG_ERROR; + } + breaks += obreaks; + /* return not triggered: restore old flag */ + retflag = oretflag; + if (breaks > loops) + breaks = loops; + } + + /* + * If zle was running while the trap was executed, see if we + * need to restore the display. + */ + if (zleactive && resetneeded) + zleentry(ZLE_CMD_REFRESH); + + if (*sigtr != ZSIG_IGNORED) + *sigtr &= ~ZSIG_IGNORED; + intrap--; + + unqueue_signals(); +} + +/* Standard call to execute a trap for a given signal. */ + +/**/ +void +dotrap(int sig) +{ + void *funcprog; + int q = queue_signal_level(); + + if (sigtrapped[sig] & ZSIG_FUNC) { + HashNode hn = gettrapnode(sig, 0); + if (hn) + funcprog = hn; + else { +#ifdef DEBUG + dputs("BUG: running function trap which has escaped."); +#endif + funcprog = NULL; + } + } else + funcprog = siglists[sig]; + + /* + * Copied from dotrapargs(). + * (In fact, the gain from duplicating this appears to be virtually + * zero. Not sure why it's here.) + */ + if ((sigtrapped[sig] & ZSIG_IGNORED) || !funcprog || errflag) + return; + + dont_queue_signals(); + + if (sig == SIGEXIT) + ++in_exit_trap; + + dotrapargs(sig, sigtrapped+sig, funcprog); + + if (sig == SIGEXIT) + --in_exit_trap; + + restore_queue_signals(q); +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/signals.h b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/signals.h new file mode 100644 index 00000000..41ac88cc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/signals.h @@ -0,0 +1,142 @@ +/* + * signals.h - header file for signals handling code + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#define SIGNAL_HANDTYPE void (*)_((int)) + +#ifndef HAVE_KILLPG +# define killpg(pgrp,sig) kill(-(pgrp),sig) +#endif + +#define SIGZERR (SIGCOUNT+1) +#define SIGDEBUG (SIGCOUNT+2) +#define VSIGCOUNT (SIGCOUNT+3) +#define SIGEXIT 0 + +#ifdef SV_BSDSIG +# define SV_INTERRUPT SV_BSDSIG +#endif + +/* If not a POSIX machine, then we create our * + * own POSIX style signal sets functions. */ +#ifndef POSIX_SIGNALS +# define sigemptyset(s) (*(s) = 0) +# if NSIG == 32 +# define sigfillset(s) (*(s) = ~(sigset_t)0, 0) +# else +# define sigfillset(s) (*(s) = (1 << NSIG) - 1, 0) +# endif +# define sigaddset(s,n) (*(s) |= (1 << ((n) - 1)), 0) +# define sigdelset(s,n) (*(s) &= ~(1 << ((n) - 1)), 0) +# define sigismember(s,n) ((*(s) & (1 << ((n) - 1))) != 0) +#endif /* ifndef POSIX_SIGNALS */ + +#define child_block() signal_block(sigchld_mask) +#define child_unblock() signal_unblock(sigchld_mask) + +#ifdef SIGWINCH +# define winch_block() signal_block(signal_mask(SIGWINCH)) +# define winch_unblock() signal_unblock(signal_mask(SIGWINCH)) +#else +# define winch_block() 0 +# define winch_unblock() 0 +#endif + +/* ignore a signal */ +#define signal_ignore(S) signal(S, SIG_IGN) + +/* return a signal to it default action */ +#define signal_default(S) signal(S, SIG_DFL) + +/* Use a circular queue to save signals caught during * + * critical sections of code. You call queue_signals to * + * start queueing, and unqueue_signals to process the * + * queue and stop queueing. Since the kernel doesn't * + * queue signals, it is probably overkill for zsh to do * + * this, but it shouldn't hurt anything to do it anyway. */ + +#define MAX_QUEUE_SIZE 128 + +#define run_queued_signals() do { \ + while (queue_front != queue_rear) { /* while signals in queue */ \ + sigset_t oset; \ + queue_front = (queue_front + 1) % MAX_QUEUE_SIZE; \ + oset = signal_setmask(signal_mask_queue[queue_front]); \ + zhandler(signal_queue[queue_front]); /* handle queued signal */ \ + signal_setmask(oset); \ + } \ +} while (0) + +#ifdef DEBUG + +#define queue_signals() (queue_in++, queueing_enabled++) + +#define unqueue_signals() do { \ + DPUTS(!queueing_enabled, "BUG: unqueue_signals called but not queueing"); \ + --queue_in; \ + if (!--queueing_enabled) run_queued_signals(); \ +} while (0) + +#define dont_queue_signals() do { \ + queue_in = queueing_enabled; \ + queueing_enabled = 0; \ + run_queued_signals(); \ +} while (0) + +#define restore_queue_signals(q) do { \ + DPUTS2(queueing_enabled && queue_in != q, \ + "BUG: q = %d != queue_in = %d", q, queue_in); \ + queue_in = (queueing_enabled = (q)); \ +} while (0) + +#else /* !DEBUG */ + +#define queue_signals() (queueing_enabled++) + +#define unqueue_signals() do { \ + if (!--queueing_enabled) run_queued_signals(); \ +} while (0) + +#define dont_queue_signals() do { \ + queueing_enabled = 0; \ + run_queued_signals(); \ +} while (0) + +#define restore_queue_signals(q) (queueing_enabled = (q)) + +#endif /* DEBUG */ + +#define queue_signal_level() queueing_enabled + +#ifdef BSD_SIGNALS +#define signal_block(S) sigblock(S) +#else +extern sigset_t signal_block _((sigset_t)); +#endif /* BSD_SIGNALS */ + +extern sigset_t signal_unblock _((sigset_t)); diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/signames1.awk b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/signames1.awk new file mode 100644 index 00000000..27d21ac7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/signames1.awk @@ -0,0 +1,19 @@ +# This is an awk script which finds out what the possibilities for +# the signal names are, and dumps them out so that cpp can turn them +# into numbers. Since we don't need to decide here what the +# real signals are, we can afford to be generous about definitions, +# in case the definitions are in terms of other definitions. +# However, we need to avoid definitions with parentheses, which will +# mess up the syntax. +BEGIN { printf "#include \n\n" } + +/^[\t ]*#[\t ]*define[\t _]*SIG[A-Z][A-Z0-9]*[\t ][\t ]*[^(\t ]/ { + sigindex = index($0, "SIG") + sigtail = substr($0, sigindex, 80) + split(sigtail, tmp) + signam = substr(tmp[1], 4, 20) + if (substr($0, sigindex-1, 1) == "_") + printf("XXNAMES XXSIG%s _SIG%s\n", signam, signam) + else + printf("XXNAMES XXSIG%s SIG%s\n", signam, signam) +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/signames2.awk b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/signames2.awk new file mode 100644 index 00000000..4d15681d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/signames2.awk @@ -0,0 +1,106 @@ +# +# {g,n}awk script to generate signames.c +# This version relies on the previous output of the preprocessor +# on sigtmp.c, sigtmp.out, which is in turn generated by signames1.awk. +# +# NB: On SunOS 4.1.3 - user-functions don't work properly, also \" problems +# Without 0 + hacks some nawks compare numbers as strings +# +/^[\t ]*XXNAMES XXSIG[A-Z][A-Z0-9]*[\t ][\t ]*[1-9][0-9]*/ { + sigindex = index($0, "SIG") + sigtail = substr($0, sigindex, 80) + split(sigtail, tmp) + signam = substr(tmp[1], 4, 20) + signum = tmp[2] + if (signam == "CHLD" && sig[signum] == "CLD") sig[signum] = "" + if (signam == "POLL" && sig[signum] == "IO") sig[signum] = "" + if (sig[signum] == "") { + sig[signum] = signam + if (0 + max < 0 + signum && signum < 60) + max = signum + if (signam == "ABRT") { msg[signum] = "abort" } + if (signam == "ALRM") { msg[signum] = "alarm" } + if (signam == "BUS") { msg[signum] = "bus error" } + if (signam == "CHLD") { msg[signum] = "death of child" } + if (signam == "CLD") { msg[signum] = "death of child" } + if (signam == "CONT") { msg[signum] = "continued" } + if (signam == "EMT") { msg[signum] = "EMT instruction" } + if (signam == "FPE") { msg[signum] = "floating point exception" } + if (signam == "HUP") { msg[signum] = "hangup" } + if (signam == "ILL") { msg[signum] = "illegal hardware instruction" } + if (signam == "INFO") { msg[signum] = "status request from keyboard" } + if (signam == "INT") { msg[signum] = "interrupt" } + if (signam == "IO") { msg[signum] = "i/o ready" } + if (signam == "IOT") { msg[signum] = "IOT instruction" } + if (signam == "KILL") { msg[signum] = "killed" } + if (signam == "LOST") { msg[signum] = "resource lost" } + if (signam == "PIPE") { msg[signum] = "broken pipe" } + if (signam == "POLL") { msg[signum] = "pollable event occurred" } + if (signam == "PROF") { msg[signum] = "profile signal" } + if (signam == "PWR") { msg[signum] = "power fail" } + if (signam == "QUIT") { msg[signum] = "quit" } + if (signam == "SEGV") { msg[signum] = "segmentation fault" } + if (signam == "SYS") { msg[signum] = "invalid system call" } + if (signam == "TERM") { msg[signum] = "terminated" } + if (signam == "TRAP") { msg[signum] = "trace trap" } + if (signam == "URG") { msg[signum] = "urgent condition" } + if (signam == "USR1") { msg[signum] = "user-defined signal 1" } + if (signam == "USR2") { msg[signum] = "user-defined signal 2" } + if (signam == "VTALRM") { msg[signum] = "virtual time alarm" } + if (signam == "WINCH") { msg[signum] = "window size changed" } + if (signam == "XCPU") { msg[signum] = "cpu limit exceeded" } + if (signam == "XFSZ") { msg[signum] = "file size limit exceeded" } + } +} + +END { + ps = "%s" + ifdstr = sprintf("# ifdef USE_SUSPENDED\n\t%csuspended%s%c,\n%s else\n\t%cstopped%s%c,\n# endif\n", 34, ps, 34, "#", 34, ps, 34) + + printf "/** signames.c **/\n" + printf "/** architecture-customized signames.c for zsh **/\n" + printf "\n" + printf "#define SIGCOUNT\t%d\n", max + printf "\n" + printf "#include %czsh.mdh%c\n", 34, 34 + printf "\n" + printf "/**/\n" + printf "#define sigmsg(sig) ((sig) <= SIGCOUNT ? sig_msg[sig]" + printf " : %c%s%c)", 34, "unknown signal", 34 + printf "\n" + printf "/**/\n" + printf "mod_export char *sig_msg[SIGCOUNT+2] = {\n" + printf "\t%c%s%c,\n", 34, "done", 34 + + for (i = 1; i <= 0 + max; i++) + if (msg[i] == "") { + if (sig[i] == "") + printf("\t%c%c,\n", 34, 34) + else if (sig[i] == "STOP") + printf ifdstr, " (signal)", " (signal)" + else if (sig[i] == "TSTP") + printf ifdstr, "", "" + else if (sig[i] == "TTIN") + printf ifdstr, " (tty input)", " (tty input)" + else if (sig[i] == "TTOU") + printf ifdstr, " (tty output)", " (tty output)" + else + printf("\t%cSIG%s%c,\n", 34, sig[i], 34) + } else + printf("\t%c%s%c,\n", 34, msg[i], 34) + print "\tNULL" + print "};" + print "" + print "/**/" + printf "char *sigs[SIGCOUNT+4] = {\n" + printf("\t%cEXIT%c,\n", 34, 34) + for (i = 1; i <= 0 + max; i++) + if (sig[i] == "") + printf("\t%c%d%c,\n", 34, i, 34) + else + printf("\t%c%s%c,\n", 34, sig[i], 34) + printf("\t%cZERR%c,\n", 34, 34) + printf("\t%cDEBUG%c,\n", 34, 34) + print "\tNULL" + print "};" +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/string.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/string.c new file mode 100644 index 00000000..9e14ef94 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/string.c @@ -0,0 +1,213 @@ +/* + * string.c - string manipulation + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 2000 Peter Stephenson + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Peter Stephenson or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Peter Stephenson and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Peter Stephenson and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Peter Stephenson and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + */ + +#include "zsh.mdh" + +/**/ +mod_export char * +dupstring(const char *s) +{ + char *t; + + if (!s) + return NULL; + t = (char *) zhalloc(strlen((char *)s) + 1); + strcpy(t, s); + return t; +} + +/* Duplicate string on heap when length is known */ + +/**/ +mod_export char * +dupstring_wlen(const char *s, unsigned len) +{ + char *t; + + if (!s) + return NULL; + t = (char *) zhalloc(len + 1); + memcpy(t, s, len); + t[len] = '\0'; + return t; +} + +/* Duplicate string on heap, returning length of string */ + +/**/ +mod_export char * +dupstring_glen(const char *s, unsigned *len_ret) +{ + char *t; + + if (!s) + return NULL; + t = (char *) zhalloc((*len_ret = strlen((char *)s)) + 1); + strcpy(t, s); + return t; +} + +/**/ +mod_export char * +ztrdup(const char *s) +{ + char *t; + + if (!s) + return NULL; + t = (char *)zalloc(strlen((char *)s) + 1); + strcpy(t, s); + return t; +} + +/**/ +#ifdef MULTIBYTE_SUPPORT +/**/ +mod_export wchar_t * +wcs_ztrdup(const wchar_t *s) +{ + wchar_t *t; + + if (!s) + return NULL; + t = (wchar_t *)zalloc(sizeof(wchar_t) * (wcslen((wchar_t *)s) + 1)); + wcscpy(t, s); + return t; +} +/**/ +#endif /* MULTIBYTE_SUPPORT */ + + +/* concatenate s1, s2, and s3 in dynamically allocated buffer */ + +/**/ +mod_export char * +tricat(char const *s1, char const *s2, char const *s3) +{ + /* This version always uses permanently-allocated space. */ + char *ptr; + size_t l1 = strlen(s1); + size_t l2 = strlen(s2); + + ptr = (char *)zalloc(l1 + l2 + strlen(s3) + 1); + strcpy(ptr, s1); + strcpy(ptr + l1, s2); + strcpy(ptr + l1 + l2, s3); + return ptr; +} + +/**/ +mod_export char * +zhtricat(char const *s1, char const *s2, char const *s3) +{ + char *ptr; + size_t l1 = strlen(s1); + size_t l2 = strlen(s2); + + ptr = (char *)zhalloc(l1 + l2 + strlen(s3) + 1); + strcpy(ptr, s1); + strcpy(ptr + l1, s2); + strcpy(ptr + l1 + l2, s3); + return ptr; +} + +/* concatenate s1 and s2 in dynamically allocated buffer */ + +/**/ +mod_export char * +dyncat(const char *s1, const char *s2) +{ + /* This version always uses space from the current heap. */ + char *ptr; + size_t l1 = strlen(s1); + + ptr = (char *)zhalloc(l1 + strlen(s2) + 1); + strcpy(ptr, s1); + strcpy(ptr + l1, s2); + return ptr; +} + +/**/ +mod_export char * +bicat(const char *s1, const char *s2) +{ + /* This version always uses permanently-allocated space. */ + char *ptr; + size_t l1 = strlen(s1); + + ptr = (char *)zalloc(l1 + strlen(s2) + 1); + strcpy(ptr, s1); + strcpy(ptr + l1, s2); + return ptr; +} + +/* like dupstring(), but with a specified length */ + +/**/ +mod_export char * +dupstrpfx(const char *s, int len) +{ + char *r = zhalloc(len + 1); + + memcpy(r, s, len); + r[len] = '\0'; + return r; +} + +/**/ +mod_export char * +ztrduppfx(const char *s, int len) +{ + /* This version always uses permanently-allocated space. */ + char *r = zalloc(len + 1); + + memcpy(r, s, len); + r[len] = '\0'; + return r; +} + +/* Append a string to an allocated string, reallocating to make room. */ + +/**/ +mod_export char * +appstr(char *base, char const *append) +{ + return strcat(realloc(base, strlen(base) + strlen(append) + 1), append); +} + +/* Return a pointer to the last character of a string, + unless the string is empty. */ + +/**/ +mod_export char * +strend(char *str) +{ + if (*str == '\0') + return str; + return str + strlen (str) - 1; +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/utils.c b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/utils.c new file mode 100644 index 00000000..075d2724 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/utils.c @@ -0,0 +1,7520 @@ +/* + * utils.c - miscellaneous utilities + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#include "zsh.mdh" +#include "utils.pro" + +/* name of script being sourced */ + +/**/ +mod_export char *scriptname; /* is sometimes a function name */ + +/* filename of script or other file containing code source e.g. autoload */ + +/**/ +mod_export char *scriptfilename; + +/* != 0 if we are in a new style completion function */ + +/**/ +mod_export int incompfunc; + +#ifdef MULTIBYTE_SUPPORT +struct widechar_array { + wchar_t *chars; + size_t len; +}; +typedef struct widechar_array *Widechar_array; + +/* + * The wordchars variable turned into a wide character array. + * This is much more convenient for testing. + */ +static struct widechar_array wordchars_wide; + +/* + * The same for the separators (IFS) array. + */ +static struct widechar_array ifs_wide; + +/* Function to set one of the above from the multibyte array */ + +static void +set_widearray(char *mb_array, Widechar_array wca) +{ + if (wca->chars) { + free(wca->chars); + wca->chars = NULL; + } + wca->len = 0; + + if (!isset(MULTIBYTE)) + return; + + if (mb_array) { + VARARR(wchar_t, tmpwcs, strlen(mb_array)); + wchar_t *wcptr = tmpwcs; + wint_t wci; + + mb_charinit(); + while (*mb_array) { + int mblen; + + if (STOUC(*mb_array) <= 0x7f) { + mb_array++; + *wcptr++ = (wchar_t)*mb_array; + continue; + } + + mblen = mb_metacharlenconv(mb_array, &wci); + + if (!mblen) + break; + /* No good unless all characters are convertible */ + if (wci == WEOF) + return; + *wcptr++ = (wchar_t)wci; +#ifdef DEBUG + /* + * This generates a warning from the compiler (and is + * indeed useless) if chars are unsigned. It's + * extreme paranoia anyway. + */ + if (wcptr[-1] < 0) + fprintf(stderr, "BUG: Bad cast to wchar_t\n"); +#endif + mb_array += mblen; + } + + wca->len = wcptr - tmpwcs; + wca->chars = (wchar_t *)zalloc(wca->len * sizeof(wchar_t)); + wmemcpy(wca->chars, tmpwcs, wca->len); + } +} +#endif + + +/* Print an error + + The following functions use the following printf-like format codes + (implemented by zerrmsg()): + + Code Argument types Prints + %s const char * C string (null terminated) + %l const char *, int C string of given length (null not required) + %L long decimal value + %d int decimal value + %% (none) literal '%' + %c int character at that codepoint + %e int strerror() message (argument is typically 'errno') + */ + +static void +zwarning(const char *cmd, const char *fmt, va_list ap) +{ + if (isatty(2)) + zleentry(ZLE_CMD_TRASH); + + char *prefix = scriptname ? scriptname : (argzero ? argzero : ""); + + if (cmd) { + if (unset(SHINSTDIN) || locallevel) { + nicezputs(prefix, stderr); + fputc((unsigned char)':', stderr); + } + nicezputs(cmd, stderr); + fputc((unsigned char)':', stderr); + } else { + /* + * scriptname is set when sourcing scripts, so that we get the + * correct name instead of the generic name of whatever + * program/script is running. It's also set in shell functions, + * so test locallevel, too. + */ + nicezputs((isset(SHINSTDIN) && !locallevel) ? "zsh" : prefix, stderr); + fputc((unsigned char)':', stderr); + } + + zerrmsg(stderr, fmt, ap); +} + + +/**/ +mod_export void +zerr(VA_ALIST1(const char *fmt)) +VA_DCL +{ + va_list ap; + VA_DEF_ARG(const char *fmt); + + if (errflag || noerrs) { + if (noerrs < 2) + errflag |= ERRFLAG_ERROR; + return; + } + errflag |= ERRFLAG_ERROR; + + VA_START(ap, fmt); + VA_GET_ARG(ap, fmt, const char *); + zwarning(NULL, fmt, ap); + va_end(ap); +} + +/**/ +mod_export void +zerrnam(VA_ALIST2(const char *cmd, const char *fmt)) +VA_DCL +{ + va_list ap; + VA_DEF_ARG(const char *cmd); + VA_DEF_ARG(const char *fmt); + + if (errflag || noerrs) + return; + errflag |= ERRFLAG_ERROR; + + VA_START(ap, fmt); + VA_GET_ARG(ap, cmd, const char *); + VA_GET_ARG(ap, fmt, const char *); + zwarning(cmd, fmt, ap); + va_end(ap); +} + +/**/ +mod_export void +zwarn(VA_ALIST1(const char *fmt)) +VA_DCL +{ + va_list ap; + VA_DEF_ARG(const char *fmt); + + if (errflag || noerrs) + return; + + VA_START(ap, fmt); + VA_GET_ARG(ap, fmt, const char *); + zwarning(NULL, fmt, ap); + va_end(ap); +} + +/**/ +mod_export void +zwarnnam(VA_ALIST2(const char *cmd, const char *fmt)) +VA_DCL +{ + va_list ap; + VA_DEF_ARG(const char *cmd); + VA_DEF_ARG(const char *fmt); + + if (errflag || noerrs) + return; + + VA_START(ap, fmt); + VA_GET_ARG(ap, cmd, const char *); + VA_GET_ARG(ap, fmt, const char *); + zwarning(cmd, fmt, ap); + va_end(ap); +} + + +#ifdef DEBUG + +/**/ +mod_export void +dputs(VA_ALIST1(const char *message)) +VA_DCL +{ + char *filename; + FILE *file; + va_list ap; + VA_DEF_ARG(const char *message); + + VA_START(ap, message); + VA_GET_ARG(ap, message, const char *); + if ((filename = getsparam_u("ZSH_DEBUG_LOG")) != NULL && + (file = fopen(filename, "a")) != NULL) { + zerrmsg(file, message, ap); + fclose(file); + } else + zerrmsg(stderr, message, ap); + va_end(ap); +} + +#endif /* DEBUG */ + +#ifdef __CYGWIN__ +/* + * This works around an occasional problem with dllwrap on Cygwin, seen + * on at least two installations. It fails to find the last symbol + * exported in alphabetical order (in our case zwarnnam). Until this is + * properly categorised and fixed we add a dummy symbol at the end. + */ +mod_export void +zz_plural_z_alpha(void) +{ +} +#endif + +/**/ +void +zerrmsg(FILE *file, const char *fmt, va_list ap) +{ + const char *str; + int num; +#ifdef DEBUG + long lnum; +#endif +#ifdef HAVE_STRERROR_R +#define ERRBUFSIZE (80) + int olderrno; + char errbuf[ERRBUFSIZE]; +#endif + char *errmsg; + + if ((unset(SHINSTDIN) || locallevel) && lineno) { +#if defined(ZLONG_IS_LONG_LONG) && defined(PRINTF_HAS_LLD) + fprintf(file, "%lld: ", lineno); +#else + fprintf(file, "%ld: ", (long)lineno); +#endif + } else + fputc((unsigned char)' ', file); + + while (*fmt) + if (*fmt == '%') { + fmt++; + switch (*fmt++) { + case 's': + str = va_arg(ap, const char *); + nicezputs(str, file); + break; + case 'l': { + char *s; + str = va_arg(ap, const char *); + num = va_arg(ap, int); + num = metalen(str, num); + s = zhalloc(num + 1); + memcpy(s, str, num); + s[num] = '\0'; + nicezputs(s, file); + break; + } +#ifdef DEBUG + case 'L': + lnum = va_arg(ap, long); + fprintf(file, "%ld", lnum); + break; +#endif + case 'd': + num = va_arg(ap, int); + fprintf(file, "%d", num); + break; + case '%': + putc('%', file); + break; + case 'c': + num = va_arg(ap, int); +#ifdef MULTIBYTE_SUPPORT + mb_charinit(); + zputs(wcs_nicechar(num, NULL, NULL), file); +#else + zputs(nicechar(num), file); +#endif + break; + case 'e': + /* print the corresponding message for this errno */ + num = va_arg(ap, int); + if (num == EINTR) { + fputs("interrupt\n", file); + errflag |= ERRFLAG_ERROR; + return; + } + errmsg = strerror(num); + /* If the message is not about I/O problems, it looks better * + * if we uncapitalize the first letter of the message */ + if (num == EIO) + fputs(errmsg, file); + else { + fputc(tulower(errmsg[0]), file); + fputs(errmsg + 1, file); + } + break; + /* When adding format codes, update the comment above zwarning(). */ + } + } else { + putc(*fmt == Meta ? *++fmt ^ 32 : *fmt, file); + fmt++; + } + putc('\n', file); + fflush(file); +} + +/* + * Wrapper for setupterm() and del_curterm(). + * These are called from terminfo.c and termcap.c. + */ +static int term_count; /* reference count of cur_term */ + +/**/ +mod_export void +zsetupterm(void) +{ +#ifdef HAVE_SETUPTERM + int errret; + + DPUTS(term_count < 0 || (term_count > 0 && !cur_term), + "inconsistent term_count and/or cur_term"); + /* + * Just because we can't set up the terminal doesn't + * mean the modules hasn't booted---TERM may change, + * and it should be handled dynamically---so ignore errors here. + */ + if (term_count++ == 0) + (void)setupterm((char *)0, 1, &errret); +#endif +} + +/**/ +mod_export void +zdeleteterm(void) +{ +#ifdef HAVE_SETUPTERM + DPUTS(term_count < 1 || !cur_term, + "inconsistent term_count and/or cur_term"); + if (--term_count == 0) + del_curterm(cur_term); +#endif +} + +/* Output a single character, for the termcap routines. * + * This is used instead of putchar since it can be a macro. */ + +/**/ +mod_export int +putraw(int c) +{ + putc(c, stdout); + return 0; +} + +/* Output a single character, for the termcap routines. */ + +/**/ +mod_export int +putshout(int c) +{ + putc(c, shout); + return 0; +} + +#ifdef MULTIBYTE_SUPPORT +/* + * Turn a character into a visible representation thereof. The visible + * string is put together in a static buffer, and this function returns + * a pointer to it. Printable characters stand for themselves, DEL is + * represented as "^?", newline and tab are represented as "\n" and + * "\t", and normal control characters are represented in "^C" form. + * Characters with bit 7 set, if unprintable, are represented as "\M-" + * followed by the visible representation of the character with bit 7 + * stripped off. Tokens are interpreted, rather than being treated as + * literal characters. + * + * Note that the returned string is metafied, so that it must be + * treated like any other zsh internal string (and not, for example, + * output directly). + * + * This function is used even if MULTIBYTE_SUPPORT is defined: we + * use it as a fallback in case we couldn't identify a wide character + * in a multibyte string. + */ + +/**/ +mod_export char * +nicechar_sel(int c, int quotable) +{ + static char buf[10]; + char *s = buf; + c &= 0xff; + if (ZISPRINT(c)) + goto done; + if (c & 0x80) { + if (isset(PRINTEIGHTBIT)) + goto done; + *s++ = '\\'; + *s++ = 'M'; + *s++ = '-'; + c &= 0x7f; + if(ZISPRINT(c)) + goto done; + } + if (c == 0x7f) { + if (quotable) { + *s++ = '\\'; + *s++ = 'C'; + *s++ = '-'; + } else + *s++ = '^'; + c = '?'; + } else if (c == '\n') { + *s++ = '\\'; + c = 'n'; + } else if (c == '\t') { + *s++ = '\\'; + c = 't'; + } else if (c < 0x20) { + if (quotable) { + *s++ = '\\'; + *s++ = 'C'; + *s++ = '-'; + } else + *s++ = '^'; + c += 0x40; + } + done: + /* + * The resulting string is still metafied, so check if + * we are returning a character in the range that needs metafication. + * This can't happen if the character is printed "nicely", so + * this results in a maximum of two bytes total (plus the null). + */ + if (imeta(c)) { + *s++ = Meta; + *s++ = c ^ 32; + } else + *s++ = c; + *s = 0; + return buf; +} + +/**/ +mod_export char * +nicechar(int c) +{ + return nicechar_sel(c, 0); +} + +#else /* MULTIBYTE_SUPPORT */ + +/**/ +mod_export char * +nicechar(int c) +{ + static char buf[10]; + char *s = buf; + c &= 0xff; + if (ZISPRINT(c)) + goto done; + if (c & 0x80) { + if (isset(PRINTEIGHTBIT)) + goto done; + *s++ = '\\'; + *s++ = 'M'; + *s++ = '-'; + c &= 0x7f; + if(ZISPRINT(c)) + goto done; + } + if (c == 0x7f) { + *s++ = '\\'; + *s++ = 'C'; + *s++ = '-'; + c = '?'; + } else if (c == '\n') { + *s++ = '\\'; + c = 'n'; + } else if (c == '\t') { + *s++ = '\\'; + c = 't'; + } else if (c < 0x20) { + *s++ = '\\'; + *s++ = 'C'; + *s++ = '-'; + c += 0x40; + } + done: + /* + * The resulting string is still metafied, so check if + * we are returning a character in the range that needs metafication. + * This can't happen if the character is printed "nicely", so + * this results in a maximum of two bytes total (plus the null). + */ + if (imeta(c)) { + *s++ = Meta; + *s++ = c ^ 32; + } else + *s++ = c; + *s = 0; + return buf; +} + +#endif /* MULTIBYTE_SUPPORT */ + +/* + * Return 1 if nicechar() would reformat this character. + */ + +/**/ +mod_export int +is_nicechar(int c) +{ + c &= 0xff; + if (ZISPRINT(c)) + return 0; + if (c & 0x80) + return !isset(PRINTEIGHTBIT); + return (c == 0x7f || c == '\n' || c == '\t' || c < 0x20); +} + +/**/ +#ifdef MULTIBYTE_SUPPORT +static mbstate_t mb_shiftstate; + +/* + * Initialise multibyte state: called before a sequence of + * wcs_nicechar(), mb_metacharlenconv(), or + * mb_charlenconv(). + */ + +/**/ +mod_export void +mb_charinit(void) +{ + memset(&mb_shiftstate, 0, sizeof(mb_shiftstate)); +} + +/* + * The number of bytes we need to allocate for a "nice" representation + * of a multibyte character. + * + * We double MB_CUR_MAX to take account of the fact that + * we may need to metafy. In fact the representation probably + * doesn't allow every character to be in the meta range, but + * we don't need to be too pedantic. + * + * The 12 is for the output of a UCS-4 code; we don't actually + * need this at the same time as MB_CUR_MAX, but again it's + * not worth calculating more exactly. + */ +#define NICECHAR_MAX (12 + 2*MB_CUR_MAX) +/* + * Input a wide character. Output a printable representation, + * which is a metafied multibyte string. With widthp return + * the printing width. + * + * swide, if non-NULL, is used to help the completion code, which needs + * to know the printing width of the each part of the representation. + * *swide is set to the part of the returned string where the wide + * character starts. Any string up to that point is ASCII characters, + * so the width of it is (*swide - ). Anything left is + * a single wide character corresponding to the remaining width. + * Either the initial ASCII part or the wide character part may be empty + * (but not both). (Note the complication that the wide character + * part may contain metafied characters.) + * + * The caller needs to call mb_charinit() before the first call, to + * set up the multibyte shift state for a range of characters. + */ + +/**/ +mod_export char * +wcs_nicechar_sel(wchar_t c, size_t *widthp, char **swidep, int quotable) +{ + static char *buf; + static int bufalloc = 0, newalloc; + char *s, *mbptr; + int ret = 0; + VARARR(char, mbstr, MB_CUR_MAX); + + /* + * We want buf to persist beyond the return. MB_CUR_MAX and hence + * NICECHAR_MAX may not be constant, so we have to allocate this at + * run time. (We could probably get away with just allocating a + * large buffer, in practice.) For efficiency, only reallocate if + * we really need to, since this function will be called frequently. + */ + newalloc = NICECHAR_MAX; + if (bufalloc != newalloc) + { + bufalloc = newalloc; + buf = (char *)zrealloc(buf, bufalloc); + } + + s = buf; + if (!WC_ISPRINT(c) && (c < 0x80 || !isset(PRINTEIGHTBIT))) { + if (c == 0x7f) { + if (quotable) { + *s++ = '\\'; + *s++ = 'C'; + *s++ = '-'; + } else + *s++ = '^'; + c = '?'; + } else if (c == L'\n') { + *s++ = '\\'; + c = 'n'; + } else if (c == L'\t') { + *s++ = '\\'; + c = 't'; + } else if (c < 0x20) { + if (quotable) { + *s++ = '\\'; + *s++ = 'C'; + *s++ = '-'; + } else + *s++ = '^'; + c += 0x40; + } else if (c >= 0x80) { + ret = -1; + } + } + + if (ret != -1) + ret = wcrtomb(mbstr, c, &mb_shiftstate); + + if (ret == -1) { + memset(&mb_shiftstate, 0, sizeof(mb_shiftstate)); + /* + * Can't or don't want to convert character: use UCS-2 or + * UCS-4 code in print escape format. + * + * This comparison fails and generates a compiler warning + * if wchar_t is 16 bits, but the code is still correct. + */ + if (c >= 0x10000) { + sprintf(buf, "\\U%.8x", (unsigned int)c); + if (widthp) + *widthp = 10; + } else if (c >= 0x100) { + sprintf(buf, "\\u%.4x", (unsigned int)c); + if (widthp) + *widthp = 6; + } else { + strcpy(buf, nicechar((int)c)); + /* + * There may be metafied characters from nicechar(), + * so compute width and end position independently. + */ + if (widthp) + *widthp = ztrlen(buf); + if (swidep) + *swidep = buf + strlen(buf); + return buf; + } + if (swidep) + *swidep = widthp ? buf + *widthp : buf; + return buf; + } + + if (widthp) { + int wcw = WCWIDTH(c); + *widthp = (s - buf); + if (wcw >= 0) + *widthp += wcw; + else + (*widthp)++; + } + if (swidep) + *swidep = s; + for (mbptr = mbstr; ret; s++, mbptr++, ret--) { + DPUTS(s >= buf + NICECHAR_MAX, + "BUG: buffer too small in wcs_nicechar"); + if (imeta(*mbptr)) { + *s++ = Meta; + DPUTS(s >= buf + NICECHAR_MAX, + "BUG: buffer too small for metafied char in wcs_nicechar"); + *s = *mbptr ^ 32; + } else { + *s = *mbptr; + } + } + *s = 0; + return buf; +} + +/**/ +mod_export char * +wcs_nicechar(wchar_t c, size_t *widthp, char **swidep) +{ + return wcs_nicechar_sel(c, widthp, swidep, 0); +} + +/* + * Return 1 if wcs_nicechar() would reformat this character for display. + */ + +/**/ +mod_export int is_wcs_nicechar(wchar_t c) +{ + if (!WC_ISPRINT(c) && (c < 0x80 || !isset(PRINTEIGHTBIT))) { + if (c == 0x7f || c == L'\n' || c == L'\t' || c < 0x20) + return 1; + if (c >= 0x80) { + return (c >= 0x100); + } + } + return 0; +} + +/**/ +mod_export int +zwcwidth(wint_t wc) +{ + int wcw; + /* assume a single-byte character if not valid */ + if (wc == WEOF || unset(MULTIBYTE)) + return 1; + wcw = WCWIDTH(wc); + /* if not printable, assume width 1 */ + if (wcw < 0) + return 1; + return wcw; +} + +/**/ +#endif /* MULTIBYTE_SUPPORT */ + +/* + * Search the path for prog and return the file name. + * The returned value is unmetafied and in the unmeta storage + * area (N.B. should be duplicated if not used immediately and not + * equal to *namep). + * + * If namep is not NULL, *namep is set to the metafied programme + * name, which is in heap storage. + */ +/**/ +char * +pathprog(char *prog, char **namep) +{ + char **pp, ppmaxlen = 0, *buf, *funmeta; + struct stat st; + + for (pp = path; *pp; pp++) + { + int len = strlen(*pp); + if (len > ppmaxlen) + ppmaxlen = len; + } + buf = zhalloc(ppmaxlen + strlen(prog) + 2); + for (pp = path; *pp; pp++) { + sprintf(buf, "%s/%s", *pp, prog); + funmeta = unmeta(buf); + if (access(funmeta, F_OK) == 0 && + stat(funmeta, &st) >= 0 && + !S_ISDIR(st.st_mode)) { + if (namep) + *namep = buf; + return funmeta; + } + } + + return NULL; +} + +/* get a symlink-free pathname for s relative to PWD */ + +/**/ +char * +findpwd(char *s) +{ + char *t; + + if (*s == '/') + return xsymlink(s, 0); + s = tricat((pwd[1]) ? pwd : "", "/", s); + t = xsymlink(s, 0); + zsfree(s); + return t; +} + +/* Check whether a string contains the * + * name of the present directory. */ + +/**/ +int +ispwd(char *s) +{ + struct stat sbuf, tbuf; + + /* POSIX: environment PWD must be absolute */ + if (*s != '/') + return 0; + + if (stat((s = unmeta(s)), &sbuf) == 0 && stat(".", &tbuf) == 0) + if (sbuf.st_dev == tbuf.st_dev && sbuf.st_ino == tbuf.st_ino) { + /* POSIX: No element of $PWD may be "." or ".." */ + while (*s) { + if (s[0] == '.' && + (!s[1] || s[1] == '/' || + (s[1] == '.' && (!s[2] || s[2] == '/')))) + break; + while (*s++ != '/' && *s) + continue; + } + return !*s; + } + return 0; +} + +static char xbuf[PATH_MAX*2+1]; + +/**/ +static char ** +slashsplit(char *s) +{ + char *t, **r, **q; + int t0; + + if (!*s) + return (char **) zshcalloc(sizeof(char *)); + + for (t = s, t0 = 0; *t; t++) + if (*t == '/') + t0++; + q = r = (char **) zalloc(sizeof(char *) * (t0 + 2)); + + while ((t = strchr(s, '/'))) { + *q++ = ztrduppfx(s, t - s); + while (*t == '/') + t++; + if (!*t) { + *q = NULL; + return r; + } + s = t; + } + *q++ = ztrdup(s); + *q = NULL; + return r; +} + +/* expands symlinks and .. or . expressions */ + +/**/ +static int +xsymlinks(char *s, int full) +{ + char **pp, **opp; + char xbuf2[PATH_MAX*3+1], xbuf3[PATH_MAX*2+1]; + int t0, ret = 0; + zulong xbuflen = strlen(xbuf), pplen; + + opp = pp = slashsplit(s); + for (; xbuflen < sizeof(xbuf) && *pp && ret >= 0; pp++) { + if (!strcmp(*pp, ".")) + continue; + if (!strcmp(*pp, "..")) { + char *p; + + if (!strcmp(xbuf, "/")) + continue; + if (!*xbuf) + continue; + p = xbuf + xbuflen; + while (*--p != '/') + xbuflen--; + *p = '\0'; + /* The \0 isn't included in the length */ + xbuflen--; + continue; + } + /* Includes null byte. */ + pplen = strlen(*pp) + 1; + if (xbuflen + pplen + 1 > sizeof(xbuf2)) { + *xbuf = 0; + ret = -1; + break; + } + memcpy(xbuf2, xbuf, xbuflen); + xbuf2[xbuflen] = '/'; + memcpy(xbuf2 + xbuflen + 1, *pp, pplen); + t0 = readlink(unmeta(xbuf2), xbuf3, PATH_MAX); + if (t0 == -1) { + if ((xbuflen += pplen) < sizeof(xbuf)) { + strcat(xbuf, "/"); + strcat(xbuf, *pp); + } else { + *xbuf = 0; + ret = -1; + break; + } + } else { + ret = 1; + metafy(xbuf3, t0, META_NOALLOC); + if (!full) { + /* + * If only one expansion requested, ensure the + * full path is in xbuf. + */ + zulong len = xbuflen; + if (*xbuf3 == '/') + strcpy(xbuf, xbuf3); + else if ((len += strlen(xbuf3) + 1) < sizeof(xbuf)) { + strcpy(xbuf + xbuflen, "/"); + strcpy(xbuf + xbuflen + 1, xbuf3); + } else { + *xbuf = 0; + ret = -1; + break; + } + + while (*++pp) { + zulong newlen = len + strlen(*pp) + 1; + if (newlen < sizeof(xbuf)) { + strcpy(xbuf + len, "/"); + strcpy(xbuf + len + 1, *pp); + len = newlen; + } else { + *xbuf = 01; + ret = -1; + break; + } + } + /* + * No need to update xbuflen, we're finished + * the expansion (for now). + */ + break; + } + if (*xbuf3 == '/') { + strcpy(xbuf, ""); + if (xsymlinks(xbuf3 + 1, 1) < 0) + ret = -1; + else + xbuflen = strlen(xbuf); + } else + if (xsymlinks(xbuf3, 1) < 0) + ret = -1; + else + xbuflen = strlen(xbuf); + } + } + freearray(opp); + return ret; +} + +/* + * expand symlinks in s, and remove other weird things: + * note that this always expands symlinks. + * + * 'heap' indicates whether to malloc() or allocate on the heap. + */ + +/**/ +char * +xsymlink(char *s, int heap) +{ + if (*s != '/') + return NULL; + *xbuf = '\0'; + if (xsymlinks(s + 1, 1) < 0) + zwarn("path expansion failed, using root directory"); + if (!*xbuf) + return heap ? dupstring("/") : ztrdup("/"); + return heap ? dupstring(xbuf) : ztrdup(xbuf); +} + +/**/ +void +print_if_link(char *s, int all) +{ + if (*s == '/') { + *xbuf = '\0'; + if (all) { + char *start = s + 1; + char xbuflink[PATH_MAX+1]; + for (;;) { + if (xsymlinks(start, 0) > 0) { + printf(" -> "); + zputs(*xbuf ? xbuf : "/", stdout); + if (!*xbuf) + break; + strcpy(xbuflink, xbuf); + start = xbuflink + 1; + *xbuf = '\0'; + } else { + break; + } + } + } else { + if (xsymlinks(s + 1, 1) > 0) + printf(" -> "), zputs(*xbuf ? xbuf : "/", stdout); + } + } +} + +/* print a directory */ + +/**/ +void +fprintdir(char *s, FILE *f) +{ + Nameddir d = finddir(s); + + if (!d) + fputs(unmeta(s), f); + else { + putc('~', f); + fputs(unmeta(d->node.nam), f); + fputs(unmeta(s + strlen(d->dir)), f); + } +} + +/* + * Substitute a directory using a name. + * If there is none, return the original argument. + * + * At this level all strings involved are metafied. + */ + +/**/ +char * +substnamedir(char *s) +{ + Nameddir d = finddir(s); + + if (!d) + return quotestring(s, QT_BACKSLASH); + return zhtricat("~", d->node.nam, quotestring(s + strlen(d->dir), + QT_BACKSLASH)); +} + + +/* Returns the current username. It caches the username * + * and uid to try to avoid requerying the password files * + * or NIS/NIS+ database. */ + +/**/ +uid_t cached_uid; +/**/ +char *cached_username; + +/**/ +char * +get_username(void) +{ +#ifdef HAVE_GETPWUID + struct passwd *pswd; + uid_t current_uid; + + current_uid = getuid(); + if (current_uid != cached_uid) { + cached_uid = current_uid; + zsfree(cached_username); + if ((pswd = getpwuid(current_uid))) + cached_username = ztrdup(pswd->pw_name); + else + cached_username = ztrdup(""); + } +#else /* !HAVE_GETPWUID */ + cached_uid = getuid(); +#endif /* !HAVE_GETPWUID */ + return cached_username; +} + +/* static variables needed by finddir(). */ + +static char *finddir_full; +static Nameddir finddir_last; +static int finddir_best; + +/* ScanFunc used by finddir(). */ + +/**/ +static void +finddir_scan(HashNode hn, UNUSED(int flags)) +{ + Nameddir nd = (Nameddir) hn; + + if(nd->diff > finddir_best && !dircmp(nd->dir, finddir_full) + && !(nd->node.flags & ND_NOABBREV)) { + finddir_last=nd; + finddir_best=nd->diff; + } +} + +/* + * See if a path has a named directory as its prefix. + * If passed a NULL argument, it will invalidate any + * cached information. + * + * s here is metafied. + */ + +/**/ +Nameddir +finddir(char *s) +{ + static struct nameddir homenode = { {NULL, "", 0}, NULL, 0 }; + static int ffsz; + char **ares; + int len; + + /* Invalidate directory cache if argument is NULL. This is called * + * whenever a node is added to or removed from the hash table, and * + * whenever the value of $HOME changes. (On startup, too.) */ + if (!s) { + homenode.dir = home ? home : ""; + homenode.diff = home ? strlen(home) : 0; + if(homenode.diff==1) + homenode.diff = 0; + if(!finddir_full) + finddir_full = zalloc(ffsz = PATH_MAX+1); + finddir_full[0] = 0; + return finddir_last = NULL; + } + +#if 0 + /* + * It's not safe to use the cache while we have function + * transformations, and it's not clear it's worth the + * complexity of guessing here whether subst_string_by_hook + * is going to turn up the goods. + */ + if (!strcmp(s, finddir_full) && *finddir_full) + return finddir_last; +#endif + + if ((int)strlen(s) >= ffsz) { + free(finddir_full); + finddir_full = zalloc(ffsz = strlen(s) * 2); + } + strcpy(finddir_full, s); + finddir_best=0; + finddir_last=NULL; + finddir_scan(&homenode.node, 0); + scanhashtable(nameddirtab, 0, 0, 0, finddir_scan, 0); + + ares = subst_string_by_hook("zsh_directory_name", "d", finddir_full); + if (ares && arrlen_ge(ares, 2) && + (len = (int)zstrtol(ares[1], NULL, 10)) > finddir_best) { + /* better duplicate this string since it's come from REPLY */ + finddir_last = (Nameddir)hcalloc(sizeof(struct nameddir)); + finddir_last->node.nam = zhtricat("[", dupstring(ares[0]), "]"); + finddir_last->dir = dupstrpfx(finddir_full, len); + finddir_last->diff = len - strlen(finddir_last->node.nam); + finddir_best = len; + } + + return finddir_last; +} + +/* add a named directory */ + +/**/ +mod_export void +adduserdir(char *s, char *t, int flags, int always) +{ + Nameddir nd; + char *eptr; + + /* We don't maintain a hash table in non-interactive shells. */ + if (!interact) + return; + + /* The ND_USERNAME flag means that this possible hash table * + * entry is derived from a passwd entry. Such entries are * + * subordinate to explicitly generated entries. */ + if ((flags & ND_USERNAME) && nameddirtab->getnode2(nameddirtab, s)) + return; + + /* Normal parameter assignments generate calls to this function, * + * with always==0. Unless the AUTO_NAME_DIRS option is set, we * + * don't let such assignments actually create directory names. * + * Instead, a reference to the parameter as a directory name can * + * cause the actual creation of the hash table entry. */ + if (!always && unset(AUTONAMEDIRS) && + !nameddirtab->getnode2(nameddirtab, s)) + return; + + if (!t || *t != '/' || strlen(t) >= PATH_MAX) { + /* We can't use this value as a directory, so simply remove * + * the corresponding entry in the hash table, if any. */ + HashNode hn = nameddirtab->removenode(nameddirtab, s); + + if(hn) + nameddirtab->freenode(hn); + return; + } + + /* add the name */ + nd = (Nameddir) zshcalloc(sizeof *nd); + nd->node.flags = flags; + eptr = t + strlen(t); + while (eptr > t && eptr[-1] == '/') + eptr--; + if (eptr == t) { + /* + * Don't abbreviate multiple slashes at the start of a + * named directory, since these are sometimes used for + * special purposes. + */ + nd->dir = metafy(t, -1, META_DUP); + } else + nd->dir = metafy(t, eptr - t, META_DUP); + /* The variables PWD and OLDPWD are not to be displayed as ~PWD etc. */ + if (!strcmp(s, "PWD") || !strcmp(s, "OLDPWD")) + nd->node.flags |= ND_NOABBREV; + nameddirtab->addnode(nameddirtab, metafy(s, -1, META_DUP), nd); +} + +/* Get a named directory: this function can cause a directory name * + * to be added to the hash table, if it isn't there already. */ + +/**/ +char * +getnameddir(char *name) +{ + Param pm; + char *str; + Nameddir nd; + + /* Check if it is already in the named directory table */ + if ((nd = (Nameddir) nameddirtab->getnode(nameddirtab, name))) + return dupstring(nd->dir); + + /* Check if there is a scalar parameter with this name whose value * + * begins with a `/'. If there is, add it to the hash table and * + * return the new value. */ + if ((pm = (Param) paramtab->getnode(paramtab, name)) && + (PM_TYPE(pm->node.flags) == PM_SCALAR) && + (str = getsparam(name)) && *str == '/') { + pm->node.flags |= PM_NAMEDDIR; + adduserdir(name, str, 0, 1); + return str; + } + +#ifdef HAVE_GETPWNAM + { + /* Retrieve an entry from the password table/database for this user. */ + struct passwd *pw; + if ((pw = getpwnam(name))) { + char *dir = isset(CHASELINKS) ? xsymlink(pw->pw_dir, 0) + : ztrdup(pw->pw_dir); + if (dir) { + adduserdir(name, dir, ND_USERNAME, 1); + str = dupstring(dir); + zsfree(dir); + return str; + } else + return dupstring(pw->pw_dir); + } + } +#endif /* HAVE_GETPWNAM */ + + /* There are no more possible sources of directory names, so give up. */ + return NULL; +} + +/* + * Compare directories. Both are metafied. + */ + +/**/ +static int +dircmp(char *s, char *t) +{ + if (s) { + for (; *s == *t; s++, t++) + if (!*s) + return 0; + if (!*s && *t == '/') + return 0; + } + return 1; +} + +/* + * Extra functions to call before displaying the prompt. + * The data is a Prepromptfn. + */ + +static LinkList prepromptfns; + +/* Add a function to the list of pre-prompt functions. */ + +/**/ +mod_export void +addprepromptfn(voidvoidfnptr_t func) +{ + Prepromptfn ppdat = (Prepromptfn)zalloc(sizeof(struct prepromptfn)); + ppdat->func = func; + if (!prepromptfns) + prepromptfns = znewlinklist(); + zaddlinknode(prepromptfns, ppdat); +} + +/* Remove a function from the list of pre-prompt functions. */ + +/**/ +mod_export void +delprepromptfn(voidvoidfnptr_t func) +{ + LinkNode ln; + + for (ln = firstnode(prepromptfns); ln; ln = nextnode(ln)) { + Prepromptfn ppdat = (Prepromptfn)getdata(ln); + if (ppdat->func == func) { + (void)remnode(prepromptfns, ln); + zfree(ppdat, sizeof(struct prepromptfn)); + return; + } + } +#ifdef DEBUG + dputs("BUG: failed to delete node from prepromptfns"); +#endif +} + +/* + * Functions to call at a particular time even if not at + * the prompt. This is handled by zle. The data is a + * Timedfn. The functions must be in time order, but this + * is enforced by addtimedfn(). + * + * Note on debugging: the code in sched.c currently assumes it's + * the only user of timedfns for the purposes of checking whether + * there's a function on the list. If this becomes no longer the case, + * the DPUTS() tests in sched.c need rewriting. + */ + +/**/ +mod_export LinkList timedfns; + +/* Add a function to the list of timed functions. */ + +/**/ +mod_export void +addtimedfn(voidvoidfnptr_t func, time_t when) +{ + Timedfn tfdat = (Timedfn)zalloc(sizeof(struct timedfn)); + tfdat->func = func; + tfdat->when = when; + + if (!timedfns) { + timedfns = znewlinklist(); + zaddlinknode(timedfns, tfdat); + } else { + LinkNode ln = firstnode(timedfns); + + /* + * Insert the new element in the linked list. We do + * rather too much work here since the standard + * functions insert after a given node, whereas we + * want to insert the new data before the first element + * with a greater time. + * + * In practice, the only use of timed functions is + * sched, which only adds the one function; so this + * whole branch isn't used beyond the following block. + */ + if (!ln) { + zaddlinknode(timedfns, tfdat); + return; + } + for (;;) { + Timedfn tfdat2; + LinkNode next = nextnode(ln); + if (!next) { + zaddlinknode(timedfns, tfdat); + return; + } + tfdat2 = (Timedfn)getdata(next); + if (when < tfdat2->when) { + zinsertlinknode(timedfns, ln, tfdat); + return; + } + ln = next; + } + } +} + +/* + * Delete a function from the list of timed functions. + * Note that if the function apperas multiple times only + * the first occurrence will be removed. + * + * Note also that when zle calls the function it does *not* + * automatically delete the entry from the list. That must + * be done by the function called. This is recommended as otherwise + * the function will keep being called immediately. (It just so + * happens this "feature" fits in well with the only current use + * of timed functions.) + */ + +/**/ +mod_export void +deltimedfn(voidvoidfnptr_t func) +{ + LinkNode ln; + + for (ln = firstnode(timedfns); ln; ln = nextnode(ln)) { + Timedfn ppdat = (Timedfn)getdata(ln); + if (ppdat->func == func) { + (void)remnode(timedfns, ln); + zfree(ppdat, sizeof(struct timedfn)); + return; + } + } +#ifdef DEBUG + dputs("BUG: failed to delete node from timedfns"); +#endif +} + +/* the last time we checked mail */ + +/**/ +time_t lastmailcheck; + +/* the last time we checked the people in the WATCH variable */ + +/**/ +time_t lastwatch; + +/* + * Call a function given by "name" with optional arguments + * "lnklist". If these are present the first argument is the function name. + * + * If "arrayp" is not zero, we also look through + * the array "name"_functions and execute functions found there. + * + * If "retval" is not NULL, the return value of the first hook function to + * return non-zero is stored in *"retval". The return value is not otherwise + * available as the calling context is restored. + * + * Returns 0 if at least one function was called (regardless of that function's + * exit status), and 1 otherwise. + */ + +/**/ +mod_export int +callhookfunc(char *name, LinkList lnklst, int arrayp, int *retval) +{ + Shfunc shfunc; + /* + * Save stopmsg, since user doesn't get a chance to respond + * to a list of jobs generated in a hook. + */ + int osc = sfcontext, osm = stopmsg, stat = 1, ret = 0; + int old_incompfunc = incompfunc; + + sfcontext = SFC_HOOK; + incompfunc = 0; + + if ((shfunc = getshfunc(name))) { + ret = doshfunc(shfunc, lnklst, 1); + stat = 0; + } + + if (arrayp) { + char **arrptr; + int namlen = strlen(name); + VARARR(char, arrnam, namlen + HOOK_SUFFIX_LEN); + memcpy(arrnam, name, namlen); + memcpy(arrnam + namlen, HOOK_SUFFIX, HOOK_SUFFIX_LEN); + + if ((arrptr = getaparam(arrnam))) { + arrptr = arrdup(arrptr); + for (; *arrptr; arrptr++) { + if ((shfunc = getshfunc(*arrptr))) { + int newret = doshfunc(shfunc, lnklst, 1); + if (!ret) + ret = newret; + stat = 0; + } + } + } + } + + sfcontext = osc; + stopmsg = osm; + incompfunc = old_incompfunc; + + if (retval) + *retval = ret; + return stat; +} + +/* do pre-prompt stuff */ + +/**/ +void +preprompt(void) +{ + static time_t lastperiodic; + time_t currentmailcheck; + LinkNode ln; + zlong period = getiparam("PERIOD"); + zlong mailcheck = getiparam("MAILCHECK"); + + /* + * Handle any pending window size changes before we compute prompts, + * then block them again to avoid interrupts during prompt display. + */ + winch_unblock(); + winch_block(); + + if (isset(PROMPTSP) && isset(PROMPTCR) && !use_exit_printed && shout) { + /* The PROMPT_SP heuristic will move the prompt down to a new line + * if there was any dangling output on the line (assuming the terminal + * has automatic margins, but we try even if hasam isn't set). + * Unfortunately it interacts badly with ZLE displaying message + * when ^D has been pressed. So just disable PROMPT_SP logic in + * this case */ + char *eolmark = getsparam("PROMPT_EOL_MARK"); + char *str; + int percents = opts[PROMPTPERCENT], w = 0; + if (!eolmark) + eolmark = "%B%S%#%s%b"; + opts[PROMPTPERCENT] = 1; + str = promptexpand(eolmark, 1, NULL, NULL, NULL); + countprompt(str, &w, 0, -1); + opts[PROMPTPERCENT] = percents; + zputs(str, shout); + fprintf(shout, "%*s\r%*s\r", (int)zterm_columns - w - !hasxn, + "", w, ""); + fflush(shout); + free(str); + } + + /* If NOTIFY is not set, then check for completed * + * jobs before we print the prompt. */ + if (unset(NOTIFY)) + scanjobs(); + if (errflag) + return; + + /* If a shell function named "precmd" exists, * + * then execute it. */ + callhookfunc("precmd", NULL, 1, NULL); + if (errflag) + return; + + /* If 1) the parameter PERIOD exists, 2) a hook function for * + * "periodic" exists, 3) it's been greater than PERIOD since we * + * executed any such hook, then execute it now. */ + if (period && ((zlong)time(NULL) > (zlong)lastperiodic + period) && + !callhookfunc("periodic", NULL, 1, NULL)) + lastperiodic = time(NULL); + if (errflag) + return; + + /* If WATCH is set, then check for the * + * specified login/logout events. */ + if (watch) { + if ((int) difftime(time(NULL), lastwatch) > getiparam("LOGCHECK")) { + dowatch(); + lastwatch = time(NULL); + } + } + if (errflag) + return; + + /* Check mail */ + currentmailcheck = time(NULL); + if (mailcheck && + (zlong) difftime(currentmailcheck, lastmailcheck) > mailcheck) { + char *mailfile; + + if (mailpath && *mailpath && **mailpath) + checkmailpath(mailpath); + else { + queue_signals(); + if ((mailfile = getsparam("MAIL")) && *mailfile) { + char *x[2]; + + x[0] = mailfile; + x[1] = NULL; + checkmailpath(x); + } + unqueue_signals(); + } + lastmailcheck = currentmailcheck; + } + + if (prepromptfns) { + for(ln = firstnode(prepromptfns); ln; ln = nextnode(ln)) { + Prepromptfn ppnode = (Prepromptfn)getdata(ln); + ppnode->func(); + } + } +} + +/**/ +static void +checkmailpath(char **s) +{ + struct stat st; + char *v, *u, c; + + while (*s) { + for (v = *s; *v && *v != '?'; v++); + c = *v; + *v = '\0'; + if (c != '?') + u = NULL; + else + u = v + 1; + if (**s == 0) { + *v = c; + zerr("empty MAILPATH component: %s", *s); + } else if (mailstat(unmeta(*s), &st) == -1) { + if (errno != ENOENT) + zerr("%e: %s", errno, *s); + } else if (S_ISDIR(st.st_mode)) { + LinkList l; + DIR *lock = opendir(unmeta(*s)); + char buf[PATH_MAX * 2 + 1], **arr, **ap; + int buflen, ct = 1; + + if (lock) { + char *fn; + + pushheap(); + l = newlinklist(); + while ((fn = zreaddir(lock, 1)) && !errflag) { + if (u) + buflen = snprintf(buf, sizeof(buf), "%s/%s?%s", *s, fn, u); + else + buflen = snprintf(buf, sizeof(buf), "%s/%s", *s, fn); + if (buflen < 0 || buflen >= (int)sizeof(buf)) + continue; + addlinknode(l, dupstring(buf)); + ct++; + } + closedir(lock); + ap = arr = (char **) zhalloc(ct * sizeof(char *)); + + while ((*ap++ = (char *)ugetnode(l))); + checkmailpath(arr); + popheap(); + } + } else if (shout) { + if (st.st_size && st.st_atime <= st.st_mtime && + st.st_mtime >= lastmailcheck) { + if (!u) { + fprintf(shout, "You have new mail.\n"); + fflush(shout); + } else { + char *usav; + int uusav = underscoreused; + + usav = zalloc(underscoreused); + + if (usav) + memcpy(usav, zunderscore, underscoreused); + + setunderscore(*s); + + u = dupstring(u); + if (!parsestr(&u)) { + singsub(&u); + zputs(u, shout); + fputc('\n', shout); + fflush(shout); + } + if (usav) { + setunderscore(usav); + zfree(usav, uusav); + } + } + } + if (isset(MAILWARNING) && st.st_atime > st.st_mtime && + st.st_atime > lastmailcheck && st.st_size) { + fprintf(shout, "The mail in %s has been read.\n", unmeta(*s)); + fflush(shout); + } + } + *v = c; + s++; + } +} + +/* This prints the XTRACE prompt. */ + +/**/ +FILE *xtrerr = 0; + +/**/ +void +printprompt4(void) +{ + if (!xtrerr) + xtrerr = stderr; + if (prompt4) { + int l, t = opts[XTRACE]; + char *s = dupstring(prompt4); + + opts[XTRACE] = 0; + unmetafy(s, &l); + s = unmetafy(promptexpand(metafy(s, l, META_NOALLOC), + 0, NULL, NULL, NULL), &l); + opts[XTRACE] = t; + + fprintf(xtrerr, "%s", s); + free(s); + } +} + +/**/ +mod_export void +freestr(void *a) +{ + zsfree(a); +} + +/**/ +mod_export void +gettyinfo(struct ttyinfo *ti) +{ + if (SHTTY != -1) { +#ifdef HAVE_TERMIOS_H +# ifdef HAVE_TCGETATTR + if (tcgetattr(SHTTY, &ti->tio) == -1) +# else + if (ioctl(SHTTY, TCGETS, &ti->tio) == -1) +# endif + zerr("bad tcgets: %e", errno); +#else +# ifdef HAVE_TERMIO_H + ioctl(SHTTY, TCGETA, &ti->tio); +# else + ioctl(SHTTY, TIOCGETP, &ti->sgttyb); + ioctl(SHTTY, TIOCLGET, &ti->lmodes); + ioctl(SHTTY, TIOCGETC, &ti->tchars); + ioctl(SHTTY, TIOCGLTC, &ti->ltchars); +# endif +#endif + } +} + +/**/ +mod_export void +settyinfo(struct ttyinfo *ti) +{ + if (SHTTY != -1) { +#ifdef HAVE_TERMIOS_H +# ifdef HAVE_TCGETATTR +# ifndef TCSADRAIN +# define TCSADRAIN 1 /* XXX Princeton's include files are screwed up */ +# endif + while (tcsetattr(SHTTY, TCSADRAIN, &ti->tio) == -1 && errno == EINTR) + ; +# else + while (ioctl(SHTTY, TCSETS, &ti->tio) == -1 && errno == EINTR) + ; +# endif + /* zerr("settyinfo: %e",errno);*/ +#else +# ifdef HAVE_TERMIO_H + ioctl(SHTTY, TCSETA, &ti->tio); +# else + ioctl(SHTTY, TIOCSETN, &ti->sgttyb); + ioctl(SHTTY, TIOCLSET, &ti->lmodes); + ioctl(SHTTY, TIOCSETC, &ti->tchars); + ioctl(SHTTY, TIOCSLTC, &ti->ltchars); +# endif +#endif + } +} + +/* the default tty state */ + +/**/ +mod_export struct ttyinfo shttyinfo; + +/* != 0 if we need to call resetvideo() */ + +/**/ +mod_export int resetneeded; + +#ifdef TIOCGWINSZ +/* window size changed */ + +/**/ +mod_export int winchanged; +#endif + +static int +adjustlines(int signalled) +{ + int oldlines = zterm_lines; + +#ifdef TIOCGWINSZ + if (signalled || zterm_lines <= 0) + zterm_lines = shttyinfo.winsize.ws_row; + else + shttyinfo.winsize.ws_row = zterm_lines; +#endif /* TIOCGWINSZ */ + if (zterm_lines <= 0) { + DPUTS(signalled && zterm_lines < 0, + "BUG: Impossible TIOCGWINSZ rows"); + zterm_lines = tclines > 0 ? tclines : 24; + } + + if (zterm_lines > 2) + termflags &= ~TERM_SHORT; + else + termflags |= TERM_SHORT; + + return (zterm_lines != oldlines); +} + +static int +adjustcolumns(int signalled) +{ + int oldcolumns = zterm_columns; + +#ifdef TIOCGWINSZ + if (signalled || zterm_columns <= 0) + zterm_columns = shttyinfo.winsize.ws_col; + else + shttyinfo.winsize.ws_col = zterm_columns; +#endif /* TIOCGWINSZ */ + if (zterm_columns <= 0) { + DPUTS(signalled && zterm_columns < 0, + "BUG: Impossible TIOCGWINSZ cols"); + zterm_columns = tccolumns > 0 ? tccolumns : 80; + } + + if (zterm_columns > 2) + termflags &= ~TERM_NARROW; + else + termflags |= TERM_NARROW; + + return (zterm_columns != oldcolumns); +} + +/* check the size of the window and adjust if necessary. * + * The value of from: * + * 0: called from update_job or setupvals * + * 1: called from the SIGWINCH handler * + * 2: called from the LINES parameter callback * + * 3: called from the COLUMNS parameter callback */ + +/**/ +void +adjustwinsize(int from) +{ + static int getwinsz = 1; +#ifdef TIOCGWINSZ + int ttyrows = shttyinfo.winsize.ws_row; + int ttycols = shttyinfo.winsize.ws_col; +#endif + int resetzle = 0; + + if (getwinsz || from == 1) { +#ifdef TIOCGWINSZ + if (SHTTY == -1) + return; + if (ioctl(SHTTY, TIOCGWINSZ, (char *)&shttyinfo.winsize) == 0) { + resetzle = (ttyrows != shttyinfo.winsize.ws_row || + ttycols != shttyinfo.winsize.ws_col); + if (from == 0 && resetzle && ttyrows && ttycols) + from = 1; /* Signal missed while a job owned the tty? */ + ttyrows = shttyinfo.winsize.ws_row; + ttycols = shttyinfo.winsize.ws_col; + } else { + /* Set to value from environment on failure */ + shttyinfo.winsize.ws_row = zterm_lines; + shttyinfo.winsize.ws_col = zterm_columns; + resetzle = (from == 1); + } +#else + resetzle = from == 1; +#endif /* TIOCGWINSZ */ + } /* else + return; */ + + switch (from) { + case 0: + case 1: + getwinsz = 0; + /* Calling setiparam() here calls this function recursively, but * + * because we've already called adjustlines() and adjustcolumns() * + * here, recursive calls are no-ops unless a signal intervenes. * + * The commented "else return;" above might be a safe shortcut, * + * but I'm concerned about what happens on race conditions; e.g., * + * suppose the user resizes his xterm during `eval $(resize)'? */ + if (adjustlines(from) && zgetenv("LINES")) + setiparam("LINES", zterm_lines); + if (adjustcolumns(from) && zgetenv("COLUMNS")) + setiparam("COLUMNS", zterm_columns); + getwinsz = 1; + break; + case 2: + resetzle = adjustlines(0); + break; + case 3: + resetzle = adjustcolumns(0); + break; + } + +#ifdef TIOCGWINSZ + if (interact && from >= 2 && + (shttyinfo.winsize.ws_row != ttyrows || + shttyinfo.winsize.ws_col != ttycols)) { + /* shttyinfo.winsize is already set up correctly */ + /* ioctl(SHTTY, TIOCSWINSZ, (char *)&shttyinfo.winsize); */ + } +#endif /* TIOCGWINSZ */ + + if (zleactive && resetzle) { +#ifdef TIOCGWINSZ + winchanged = +#endif /* TIOCGWINSZ */ + resetneeded = 1; + zleentry(ZLE_CMD_RESET_PROMPT); + zleentry(ZLE_CMD_REFRESH); + } +} + +/* + * Ensure the fdtable is large enough for fd, and that the + * maximum fd is set appropriately. + */ +static void +check_fd_table(int fd) +{ + if (fd <= max_zsh_fd) + return; + + if (fd >= fdtable_size) { + int old_size = fdtable_size; + while (fd >= fdtable_size) + fdtable = zrealloc(fdtable, + (fdtable_size *= 2)*sizeof(*fdtable)); + memset(fdtable + old_size, 0, + (fdtable_size - old_size) * sizeof(*fdtable)); + } + max_zsh_fd = fd; +} + +/* Move a fd to a place >= 10 and mark the new fd in fdtable. If the fd * + * is already >= 10, it is not moved. If it is invalid, -1 is returned. */ + +/**/ +mod_export int +movefd(int fd) +{ + if(fd != -1 && fd < 10) { +#ifdef F_DUPFD + int fe = fcntl(fd, F_DUPFD, 10); +#else + int fe = movefd(dup(fd)); +#endif + /* + * To close or not to close if fe is -1? + * If it is -1, we haven't moved the fd, so if we close + * it we lose it; but we're probably not going to be able + * to use it in situ anyway. So probably better to avoid a leak. + */ + zclose(fd); + fd = fe; + } + if(fd != -1) { + check_fd_table(fd); + fdtable[fd] = FDT_INTERNAL; + } + return fd; +} + +/* + * Move fd x to y. If x == -1, fd y is closed. + * Returns y for success, -1 for failure. + */ + +/**/ +mod_export int +redup(int x, int y) +{ + int ret = y; + + if(x < 0) + zclose(y); + else if (x != y) { + if (dup2(x, y) == -1) { + ret = -1; + } else { + check_fd_table(y); + fdtable[y] = fdtable[x]; + if (fdtable[y] == FDT_FLOCK || fdtable[y] == FDT_FLOCK_EXEC) + fdtable[y] = FDT_INTERNAL; + } + /* + * Closing any fd to the locked file releases the lock. + * This isn't expected to happen, it's here for completeness. + */ + if (fdtable[x] == FDT_FLOCK) + fdtable_flocks--; + zclose(x); + } + + return ret; +} + +/* + * Add an fd opened ithin a module. + * + * fdt is the type of the fd; see the FDT_ definitions in zsh.h. + * The most likely falures are: + * + * FDT_EXTERNAL: the fd can be used within the shell for normal I/O but + * it will not be closed automatically or by normal shell syntax. + * + * FDT_MODULE: as FDT_EXTERNAL, but it can only be closed by the module + * (which should included zclose() as part of the sequence), not by + * the standard shell syntax for closing file descriptors. + * + * FDT_INTERNAL: fd is treated like others created by the shell for + * internal use; it can be closed and will be closed by the shell if it + * exec's or performs an exec with a fork optimised out. + * + * Safe if fd is -1 to indicate failure. + */ +/**/ +mod_export void +addmodulefd(int fd, int fdt) +{ + if (fd >= 0) { + check_fd_table(fd); + fdtable[fd] = fdt; + } +} + +/**/ + +/* + * Indicate that an fd has a file lock; if cloexec is 1 it will be closed + * on exec. + * The fd should already be known to fdtable (e.g. by movefd). + * Note the fdtable code doesn't care what sort of lock + * is used; this simply prevents the main shell exiting prematurely + * when it holds a lock. + */ + +/**/ +mod_export void +addlockfd(int fd, int cloexec) +{ + if (cloexec) { + if (fdtable[fd] != FDT_FLOCK) + fdtable_flocks++; + fdtable[fd] = FDT_FLOCK; + } else { + fdtable[fd] = FDT_FLOCK_EXEC; + } +} + +/* Close the given fd, and clear it from fdtable. */ + +/**/ +mod_export int +zclose(int fd) +{ + if (fd >= 0) { + /* + * Careful: we allow closing of arbitrary fd's, beyond + * max_zsh_fd. In that case we don't try anything clever. + */ + if (fd <= max_zsh_fd) { + if (fdtable[fd] == FDT_FLOCK) + fdtable_flocks--; + fdtable[fd] = FDT_UNUSED; + while (max_zsh_fd > 0 && fdtable[max_zsh_fd] == FDT_UNUSED) + max_zsh_fd--; + if (fd == coprocin) + coprocin = -1; + if (fd == coprocout) + coprocout = -1; + } + return close(fd); + } + return -1; +} + +/* + * Close an fd returning 0 if used for locking; return -1 if it isn't. + */ + +/**/ +mod_export int +zcloselockfd(int fd) +{ + if (fd > max_zsh_fd) + return -1; + if (fdtable[fd] != FDT_FLOCK && fdtable[fd] != FDT_FLOCK_EXEC) + return -1; + zclose(fd); + return 0; +} + +#ifdef HAVE__MKTEMP +extern char *_mktemp(char *); +#endif + +/* Get a unique filename for use as a temporary file. If "prefix" is + * NULL, the name is relative to $TMPPREFIX; If it is non-NULL, the + * unique suffix includes a prefixed '.' for improved readability. If + * "use_heap" is true, we allocate the returned name on the heap. + * The string passed as "prefix" is expected to be metafied. */ + +/**/ +mod_export char * +gettempname(const char *prefix, int use_heap) +{ + char *ret, *suffix = prefix ? ".XXXXXX" : "XXXXXX"; + + queue_signals(); + if (!prefix && !(prefix = getsparam("TMPPREFIX"))) + prefix = DEFAULT_TMPPREFIX; + if (use_heap) + ret = dyncat(unmeta(prefix), suffix); + else + ret = bicat(unmeta(prefix), suffix); + +#ifdef HAVE__MKTEMP + /* Zsh uses mktemp() safely, so silence the warnings */ + ret = (char *) _mktemp(ret); +#else + ret = (char *) mktemp(ret); +#endif + unqueue_signals(); + + return ret; +} + +/* The gettempfile() "prefix" is expected to be metafied, see hist.c + * and gettempname(). */ + +/**/ +mod_export int +gettempfile(const char *prefix, int use_heap, char **tempname) +{ + char *fn; + int fd; + mode_t old_umask; +#if HAVE_MKSTEMP + char *suffix = prefix ? ".XXXXXX" : "XXXXXX"; + + queue_signals(); + old_umask = umask(0177); + if (!prefix && !(prefix = getsparam("TMPPREFIX"))) + prefix = DEFAULT_TMPPREFIX; + if (use_heap) + fn = dyncat(unmeta(prefix), suffix); + else + fn = bicat(unmeta(prefix), suffix); + + fd = mkstemp(fn); + if (fd < 0) { + if (!use_heap) + free(fn); + fn = NULL; + } +#else + int failures = 0; + + queue_signals(); + old_umask = umask(0177); + do { + if (!(fn = gettempname(prefix, use_heap))) { + fd = -1; + break; + } + if ((fd = open(fn, O_RDWR | O_CREAT | O_EXCL, 0600)) >= 0) + break; + if (!use_heap) + free(fn); + fn = NULL; + } while (errno == EEXIST && ++failures < 16); +#endif + *tempname = fn; + + umask(old_umask); + unqueue_signals(); + return fd; +} + +/* Check if a string contains a token */ + +/**/ +mod_export int +has_token(const char *s) +{ + while(*s) + if(itok(*s++)) + return 1; + return 0; +} + +/* Delete a character in a string */ + +/**/ +mod_export void +chuck(char *str) +{ + while ((str[0] = str[1])) + str++; +} + +/**/ +mod_export int +tulower(int c) +{ + c &= 0xff; + return (isupper(c) ? tolower(c) : c); +} + +/**/ +mod_export int +tuupper(int c) +{ + c &= 0xff; + return (islower(c) ? toupper(c) : c); +} + +/* copy len chars from t into s, and null terminate */ + +/**/ +void +ztrncpy(char *s, char *t, int len) +{ + while (len--) + *s++ = *t++; + *s = '\0'; +} + +/* copy t into *s and update s */ + +/**/ +mod_export void +strucpy(char **s, char *t) +{ + char *u = *s; + + while ((*u++ = *t++)); + *s = u - 1; +} + +/**/ +mod_export void +struncpy(char **s, char *t, int n) +{ + char *u = *s; + + while (n-- && (*u = *t++)) + u++; + *s = u; + if (n > 0) /* just one null-byte will do, unlike strncpy(3) */ + *u = '\0'; +} + +/* Return the number of elements in an array of pointers. * + * It doesn't count the NULL pointer at the end. */ + +/**/ +mod_export int +arrlen(char **s) +{ + int count; + + for (count = 0; *s; s++, count++); + return count; +} + +/* Return TRUE iff arrlen(s) >= lower_bound, but more efficiently. */ + +/**/ +mod_export char +arrlen_ge(char **s, unsigned lower_bound) +{ + while (lower_bound--) + if (!*s++) + return 0 /* FALSE */; + + return 1 /* TRUE */; +} + +/* Return TRUE iff arrlen(s) > lower_bound, but more efficiently. */ + +/**/ +mod_export char +arrlen_gt(char **s, unsigned lower_bound) +{ + return arrlen_ge(s, 1+lower_bound); +} + +/* Return TRUE iff arrlen(s) <= upper_bound, but more efficiently. */ + +/**/ +mod_export char +arrlen_le(char **s, unsigned upper_bound) +{ + return arrlen_lt(s, 1+upper_bound); +} + +/* Return TRUE iff arrlen(s) < upper_bound, but more efficiently. */ + +/**/ +mod_export char +arrlen_lt(char **s, unsigned upper_bound) +{ + return !arrlen_ge(s, upper_bound); +} + +/* Skip over a balanced pair of parenthesis. */ + +/**/ +mod_export int +skipparens(char inpar, char outpar, char **s) +{ + int level; + + if (**s != inpar) + return -1; + + for (level = 1; *++*s && level;) + if (**s == inpar) + ++level; + else if (**s == outpar) + --level; + + return level; +} + +/**/ +mod_export zlong +zstrtol(const char *s, char **t, int base) +{ + return zstrtol_underscore(s, t, base, 0); +} + +/* Convert string to zlong (see zsh.h). This function (without the z) * + * is contained in the ANSI standard C library, but a lot of them seem * + * to be broken. */ + +/**/ +mod_export zlong +zstrtol_underscore(const char *s, char **t, int base, int underscore) +{ + const char *inp, *trunc = NULL; + zulong calc = 0, newcalc = 0; + int neg; + + while (inblank(*s)) + s++; + + if ((neg = IS_DASH(*s))) + s++; + else if (*s == '+') + s++; + + if (!base) { + if (*s != '0') + base = 10; + else if (*++s == 'x' || *s == 'X') + base = 16, s++; + else if (*s == 'b' || *s == 'B') + base = 2, s++; + else + base = 8; + } + inp = s; + if (base < 2 || base > 36) { + zerr("invalid base (must be 2 to 36 inclusive): %d", base); + return (zlong)0; + } else if (base <= 10) { + for (; (*s >= '0' && *s < ('0' + base)) || + (underscore && *s == '_'); s++) { + if (trunc || *s == '_') + continue; + newcalc = calc * base + *s - '0'; + if (newcalc < calc) + { + trunc = s; + continue; + } + calc = newcalc; + } + } else { + for (; idigit(*s) || (*s >= 'a' && *s < ('a' + base - 10)) + || (*s >= 'A' && *s < ('A' + base - 10)) + || (underscore && *s == '_'); s++) { + if (trunc || *s == '_') + continue; + newcalc = calc*base + (idigit(*s) ? (*s - '0') : (*s & 0x1f) + 9); + if (newcalc < calc) + { + trunc = s; + continue; + } + calc = newcalc; + } + } + + /* + * Special case: check for a number that was just too long for + * signed notation. + * Extra special case: the lowest negative number would trigger + * the first test, but is actually representable correctly. + * This is a 1 in the top bit, all others zero, so test for + * that explicitly. + */ + if (!trunc && (zlong)calc < 0 && + (!neg || calc & ~((zulong)1 << (8*sizeof(zulong)-1)))) + { + trunc = s - 1; + calc /= base; + } + + if (trunc) + zwarn("number truncated after %d digits: %s", (int)(trunc - inp), inp); + + if (t) + *t = (char *)s; + return neg ? -(zlong)calc : (zlong)calc; +} + +/* + * If s represents a complete unsigned integer (and nothing else) + * return 1 and set retval to the value. Otherwise return 0. + * + * Underscores are always allowed. + * + * Sensitive to OCTAL_ZEROES. + */ + +/**/ +mod_export int +zstrtoul_underscore(const char *s, zulong *retval) +{ + zulong calc = 0, newcalc = 0, base; + + if (*s == '+') + s++; + + if (*s != '0') + base = 10; + else if (*++s == 'x' || *s == 'X') + base = 16, s++; + else if (*s == 'b' || *s == 'B') + base = 2, s++; + else + base = isset(OCTALZEROES) ? 8 : 10; + if (base <= 10) { + for (; (*s >= '0' && *s < ('0' + base)) || + *s == '_'; s++) { + if (*s == '_') + continue; + newcalc = calc * base + *s - '0'; + if (newcalc < calc) + { + return 0; + } + calc = newcalc; + } + } else { + for (; idigit(*s) || (*s >= 'a' && *s < ('a' + base - 10)) + || (*s >= 'A' && *s < ('A' + base - 10)) + || *s == '_'; s++) { + if (*s == '_') + continue; + newcalc = calc*base + (idigit(*s) ? (*s - '0') : (*s & 0x1f) + 9); + if (newcalc < calc) + { + return 0; + } + calc = newcalc; + } + } + + if (*s) + return 0; + *retval = calc; + return 1; +} + +/**/ +mod_export int +setblock_fd(int turnonblocking, int fd, long *modep) +{ +#ifdef O_NDELAY +# ifdef O_NONBLOCK +# define NONBLOCK (O_NDELAY|O_NONBLOCK) +# else /* !O_NONBLOCK */ +# define NONBLOCK O_NDELAY +# endif /* !O_NONBLOCK */ +#else /* !O_NDELAY */ +# ifdef O_NONBLOCK +# define NONBLOCK O_NONBLOCK +# else /* !O_NONBLOCK */ +# define NONBLOCK 0 +# endif /* !O_NONBLOCK */ +#endif /* !O_NDELAY */ + +#if NONBLOCK + struct stat st; + + if (!fstat(fd, &st) && !S_ISREG(st.st_mode)) { + *modep = fcntl(fd, F_GETFL, 0); + if (*modep != -1) { + if (!turnonblocking) { + /* We want to know if blocking was off */ + if ((*modep & NONBLOCK) || + !fcntl(fd, F_SETFL, *modep | NONBLOCK)) + return 1; + } else if ((*modep & NONBLOCK) && + !fcntl(fd, F_SETFL, *modep & ~NONBLOCK)) { + /* Here we want to know if the state changed */ + return 1; + } + } + } else +#endif /* NONBLOCK */ + *modep = -1; + return 0; + +#undef NONBLOCK +} + +/**/ +int +setblock_stdin(void) +{ + long mode; + return setblock_fd(1, 0, &mode); +} + +/* + * Check for pending input on fd. If polltty is set, we may need to + * use termio to look for input. As a final resort, go to non-blocking + * input and try to read a character, which in this case will be + * returned in *readchar. + * + * Note that apart from setting (and restoring) non-blocking input, + * this function does not change the input mode. The calling function + * should have set cbreak mode if necessary. + * + * fd may be -1 to sleep until the timeout in microseconds. This is a + * fallback for old systems that don't have nanosleep(). Some very old + * systems might not have select: get with it, daddy-o. + */ + +/**/ +mod_export int +read_poll(int fd, int *readchar, int polltty, zlong microseconds) +{ + int ret = -1; + long mode = -1; + char c; +#ifdef HAVE_SELECT + fd_set foofd; + struct timeval expire_tv; +#else +#ifdef FIONREAD + int val; +#endif +#endif +#ifdef HAS_TIO + struct ttyinfo ti; +#endif + + if (fd < 0 || (polltty && !isatty(fd))) + polltty = 0; /* no tty to poll */ + +#if defined(HAS_TIO) && !defined(__CYGWIN__) + /* + * Under Solaris, at least, reading from the terminal in non-canonical + * mode requires that we use the VMIN mechanism to poll. Any attempt + * to check any other way, or to set the terminal to non-blocking mode + * and poll that way, fails; it will just for canonical mode input. + * We should probably use this mechanism if the user has set non-canonical + * mode, in which case testing here for isatty() and ~ICANON would be + * better than testing whether bin_read() set it, but for now we've got + * enough problems. + * + * Under Cygwin, you won't be surprised to here, this mechanism, + * although present, doesn't work, and we *have* to use ordinary + * non-blocking reads to find out if there is a character present + * in non-canonical mode. + * + * I am assuming Solaris is nearer the UNIX norm. This is not necessarily + * as plausible as it sounds, but it seems the right way to guess. + * pws 2000/06/26 + */ + if (polltty && fd >= 0) { + gettyinfo(&ti); + if ((polltty = ti.tio.c_cc[VMIN])) { + ti.tio.c_cc[VMIN] = 0; + /* termios timeout is 10ths of a second */ + ti.tio.c_cc[VTIME] = (int) (microseconds / (zlong)100000); + settyinfo(&ti); + } + } +#else + polltty = 0; +#endif +#ifdef HAVE_SELECT + expire_tv.tv_sec = (int) (microseconds / (zlong)1000000); + expire_tv.tv_usec = microseconds % (zlong)1000000; + FD_ZERO(&foofd); + if (fd > -1) { + FD_SET(fd, &foofd); + ret = select(fd+1, (SELECT_ARG_2_T) &foofd, NULL, NULL, &expire_tv); + } else + ret = select(0, NULL, NULL, NULL, &expire_tv); +#else + if (fd < 0) { + /* OK, can't do that. Just quietly sleep for a second. */ + sleep(1); + return 1; + } +#ifdef FIONREAD + if (ioctl(fd, FIONREAD, (char *) &val) == 0) + ret = (val > 0); +#endif +#endif + + if (fd >= 0 && ret < 0 && !errflag) { + /* + * Final attempt: set non-blocking read and try to read a character. + * Praise Bill, this works under Cygwin (nothing else seems to). + */ + if ((polltty || setblock_fd(0, fd, &mode)) && read(fd, &c, 1) > 0) { + *readchar = c; + ret = 1; + } + if (mode != -1) + fcntl(fd, F_SETFL, mode); + } +#ifdef HAS_TIO + if (polltty) { + ti.tio.c_cc[VMIN] = 1; + ti.tio.c_cc[VTIME] = 0; + settyinfo(&ti); + } +#endif + return (ret > 0); +} + +/* + * Sleep for the given number of microseconds --- must be within + * range of a long at the moment, but this is only used for + * limited internal purposes. + */ + +/**/ +int +zsleep(long us) +{ +#ifdef HAVE_NANOSLEEP + struct timespec sleeptime; + + sleeptime.tv_sec = (time_t)us / (time_t)1000000; + sleeptime.tv_nsec = (us % 1000000L) * 1000L; + for (;;) { + struct timespec rem; + int ret = nanosleep(&sleeptime, &rem); + + if (ret == 0) + return 1; + else if (errno != EINTR) + return 0; + sleeptime = rem; + } +#else + int dummy; + return read_poll(-1, &dummy, 0, us); +#endif +} + +/** + * Sleep for time (fairly) randomly up to max_us microseconds. + * Don't let the wallclock time extend beyond end_time. + * Return 1 if that seemed to work, else 0. + * + * For best results max_us should be a multiple of 2**16 or large + * enough that it doesn't matter. + */ + +/**/ +int +zsleep_random(long max_us, time_t end_time) +{ + long r; + time_t now = time(NULL); + + /* + * Randomish backoff. Doesn't need to be fundamentally + * unpredictable, just probably unlike the value another + * exiting shell is using. On some systems the bottom 16 + * bits aren't that random but the use here doesn't + * really care. + */ + r = (long)(rand() & 0xFFFF); + /* + * Turn this into a fraction of sleep_us. Again, this + * doesn't need to be particularly accurate and the base time + * is sufficient that we can do the division first and not + * worry about the range. + */ + r = (max_us >> 16) * r; + /* + * Don't sleep beyond timeout. + * Not that important as timeout is ridiculously long, but + * if there's an interface, interface to it... + */ + while (r && now + (time_t)(r / 1000000) > end_time) + r >>= 1; + if (r) /* pedantry */ + return zsleep(r); + return 0; +} + +/**/ +int +checkrmall(char *s) +{ + DIR *rmd; + int count = 0; + if (!shout) + return 1; + if (*s != '/') { + if (pwd[1]) + s = zhtricat(pwd, "/", s); + else + s = dyncat("/", s); + } + const int max_count = 100; + if ((rmd = opendir(unmeta(s)))) { + int ignoredots = !isset(GLOBDOTS); + char *fname; + + while ((fname = zreaddir(rmd, 1))) { + if (ignoredots && *fname == '.') + continue; + count++; + if (count > max_count) + break; + } + closedir(rmd); + } + if (count > max_count) + fprintf(shout, "zsh: sure you want to delete more than %d files in ", + max_count); + else if (count == 1) + fprintf(shout, "zsh: sure you want to delete the only file in "); + else if (count > 0) + fprintf(shout, "zsh: sure you want to delete all %d files in ", + count); + else { + /* We don't know how many files the glob will expand to; see 41707. */ + fprintf(shout, "zsh: sure you want to delete all the files in "); + } + nicezputs(s, shout); + if(isset(RMSTARWAIT)) { + fputs("? (waiting ten seconds)", shout); + fflush(shout); + zbeep(); + sleep(10); + fputc('\n', shout); + } + if (errflag) + return 0; + fputs(" [yn]? ", shout); + fflush(shout); + zbeep(); + return (getquery("ny", 1) == 'y'); +} + +/**/ +mod_export ssize_t +read_loop(int fd, char *buf, size_t len) +{ + ssize_t got = len; + + while (1) { + ssize_t ret = read(fd, buf, len); + if (ret == len) + break; + if (ret <= 0) { + if (ret < 0) { + if (errno == EINTR) + continue; + if (fd != SHTTY) + zwarn("read failed: %e", errno); + } + return ret; + } + buf += ret; + len -= ret; + } + + return got; +} + +/**/ +mod_export ssize_t +write_loop(int fd, const char *buf, size_t len) +{ + ssize_t wrote = len; + + while (1) { + ssize_t ret = write(fd, buf, len); + if (ret == len) + break; + if (ret < 0) { + if (errno == EINTR) + continue; + if (fd != SHTTY) + zwarn("write failed: %e", errno); + return -1; + } + buf += ret; + len -= ret; + } + + return wrote; +} + +static int +read1char(int echo) +{ + char c; + int q = queue_signal_level(); + + dont_queue_signals(); + while (read(SHTTY, &c, 1) != 1) { + if (errno != EINTR || errflag || retflag || breaks || contflag) { + restore_queue_signals(q); + return -1; + } + } + restore_queue_signals(q); + if (echo) + write_loop(SHTTY, &c, 1); + return STOUC(c); +} + +/**/ +mod_export int +noquery(int purge) +{ + int val = 0; + +#ifdef FIONREAD + char c; + + ioctl(SHTTY, FIONREAD, (char *)&val); + if (purge) { + for (; val; val--) { + if (read(SHTTY, &c, 1) != 1) { + /* Do nothing... */ + } + } + } +#endif + + return val; +} + +/**/ +int +getquery(char *valid_chars, int purge) +{ + int c, d, nl = 0; + int isem = !strcmp(term, "emacs"); + struct ttyinfo ti; + + attachtty(mypgrp); + + gettyinfo(&ti); +#ifdef HAS_TIO + ti.tio.c_lflag &= ~ECHO; + if (!isem) { + ti.tio.c_lflag &= ~ICANON; + ti.tio.c_cc[VMIN] = 1; + ti.tio.c_cc[VTIME] = 0; + } +#else + ti.sgttyb.sg_flags &= ~ECHO; + if (!isem) + ti.sgttyb.sg_flags |= CBREAK; +#endif + settyinfo(&ti); + + if (noquery(purge)) { + if (!isem) + settyinfo(&shttyinfo); + write_loop(SHTTY, "n\n", 2); + return 'n'; + } + + while ((c = read1char(0)) >= 0) { + if (c == 'Y') + c = 'y'; + else if (c == 'N') + c = 'n'; + if (!valid_chars) + break; + if (c == '\n') { + c = *valid_chars; + nl = 1; + break; + } + if (strchr(valid_chars, c)) { + nl = 1; + break; + } + zbeep(); + } + if (c >= 0) { + char buf = (char)c; + write_loop(SHTTY, &buf, 1); + } + if (nl) + write_loop(SHTTY, "\n", 1); + + if (isem) { + if (c != '\n') + while ((d = read1char(1)) >= 0 && d != '\n'); + } else { + if (c != '\n' && !valid_chars) { +#ifdef MULTIBYTE_SUPPORT + if (isset(MULTIBYTE) && c >= 0) { + /* + * No waiting for a valid character, and no draining; + * we should ensure we haven't stopped in the middle + * of a multibyte character. + */ + mbstate_t mbs; + char cc = (char)c; + memset(&mbs, 0, sizeof(mbs)); + for (;;) { + size_t ret = mbrlen(&cc, 1, &mbs); + + if (ret != MB_INCOMPLETE) + break; + c = read1char(1); + if (c < 0) + break; + cc = (char)c; + } + } +#endif + write_loop(SHTTY, "\n", 1); + } + } + settyinfo(&shttyinfo); + return c; +} + +static int d; +static char *guess, *best; +static Patprog spckpat, spnamepat; + +/**/ +static void +spscan(HashNode hn, UNUSED(int scanflags)) +{ + int nd; + + if (spckpat && pattry(spckpat, hn->nam)) + return; + + nd = spdist(hn->nam, guess, (int) strlen(guess) / 4 + 1); + if (nd <= d) { + best = hn->nam; + d = nd; + } +} + +/* spellcheck a word */ +/* fix s ; if hist is nonzero, fix the history list too */ + +/**/ +mod_export void +spckword(char **s, int hist, int cmd, int ask) +{ + char *t, *correct_ignore; + char ic = '\0'; + int preflen = 0; + int autocd = cmd && isset(AUTOCD) && strcmp(*s, ".") && strcmp(*s, ".."); + + if ((histdone & HISTFLAG_NOEXEC) || **s == '-' || **s == '%') + return; + if (!strcmp(*s, "in")) + return; + if (!(*s)[0] || !(*s)[1]) + return; + if (cmd) { + if (shfunctab->getnode(shfunctab, *s) || + builtintab->getnode(builtintab, *s) || + cmdnamtab->getnode(cmdnamtab, *s) || + aliastab->getnode(aliastab, *s) || + reswdtab->getnode(reswdtab, *s)) + return; + else if (isset(HASHLISTALL)) { + cmdnamtab->filltable(cmdnamtab); + if (cmdnamtab->getnode(cmdnamtab, *s)) + return; + } + } + t = *s; + if (*t == Tilde || *t == Equals || *t == String) + t++; + for (; *t; t++) + if (itok(*t)) + return; + best = NULL; + for (t = *s; *t; t++) + if (*t == '/') + break; + if (**s == Tilde && !*t) + return; + + if ((correct_ignore = getsparam("CORRECT_IGNORE")) != NULL) { + tokenize(correct_ignore = dupstring(correct_ignore)); + remnulargs(correct_ignore); + spckpat = patcompile(correct_ignore, 0, NULL); + } else + spckpat = NULL; + + if ((correct_ignore = getsparam("CORRECT_IGNORE_FILE")) != NULL) { + tokenize(correct_ignore = dupstring(correct_ignore)); + remnulargs(correct_ignore); + spnamepat = patcompile(correct_ignore, 0, NULL); + } else + spnamepat = NULL; + + if (**s == String && !*t) { + guess = *s + 1; + if (itype_end(guess, IIDENT, 1) == guess) + return; + ic = String; + d = 100; + scanhashtable(paramtab, 1, 0, 0, spscan, 0); + } else if (**s == Equals) { + if (*t) + return; + if (hashcmd(guess = *s + 1, pathchecked)) + return; + d = 100; + ic = Equals; + scanhashtable(aliastab, 1, 0, 0, spscan, 0); + scanhashtable(cmdnamtab, 1, 0, 0, spscan, 0); + } else { + guess = *s; + if (*guess == Tilde || *guess == String) { + int ne; + ic = *guess; + if (!*++t) + return; + guess = dupstring(guess); + ne = noerrs; + noerrs = 2; + singsub(&guess); + noerrs = ne; + if (!guess) + return; + preflen = strlen(guess) - strlen(t); + } + if (access(unmeta(guess), F_OK) == 0) + return; + best = spname(guess); + if (!*t && cmd) { + if (hashcmd(guess, pathchecked)) + return; + d = 100; + scanhashtable(reswdtab, 1, 0, 0, spscan, 0); + scanhashtable(aliastab, 1, 0, 0, spscan, 0); + scanhashtable(shfunctab, 1, 0, 0, spscan, 0); + scanhashtable(builtintab, 1, 0, 0, spscan, 0); + scanhashtable(cmdnamtab, 1, 0, 0, spscan, 0); + if (autocd) { + char **pp; + for (pp = cdpath; *pp; pp++) { + char bestcd[PATH_MAX + 1]; + int thisdist; + /* Less than d here, instead of less than or equal * + * as used in spscan(), so that an autocd is chosen * + * only when it is better than anything so far, and * + * so we prefer directories earlier in the cdpath. */ + if ((thisdist = mindist(*pp, *s, bestcd, 1)) < d) { + best = dupstring(bestcd); + d = thisdist; + } + } + } + } + } + if (errflag) + return; + if (best && (int)strlen(best) > 1 && strcmp(best, guess)) { + int x; + if (ic) { + char *u; + if (preflen) { + /* do not correct the result of an expansion */ + if (strncmp(guess, best, preflen)) + return; + /* replace the temporarily expanded prefix with the original */ + u = (char *) zhalloc(t - *s + strlen(best + preflen) + 1); + strncpy(u, *s, t - *s); + strcpy(u + (t - *s), best + preflen); + } else { + u = (char *) zhalloc(strlen(best) + 2); + *u = '\0'; + strcpy(u + 1, best); + } + best = u; + guess = *s; + *guess = *best = ztokens[ic - Pound]; + } + if (ask) { + if (noquery(0)) { + x = 'n'; + } else if (shout) { + char *pptbuf; + pptbuf = promptexpand(sprompt, 0, best, guess, NULL); + zputs(pptbuf, shout); + free(pptbuf); + fflush(shout); + zbeep(); + x = getquery("nyae", 0); + if (cmd && x == 'n') + pathchecked = path; + } else + x = 'n'; + } else + x = 'y'; + if (x == 'y') { + *s = dupstring(best); + if (hist) + hwrep(best); + } else if (x == 'a') { + histdone |= HISTFLAG_NOEXEC; + } else if (x == 'e') { + histdone |= HISTFLAG_NOEXEC | HISTFLAG_RECALL; + } + if (ic) + **s = ic; + } +} + +/* + * Helper for ztrftime. Called with a pointer to the length left + * in the buffer, and a new string length to decrement from that. + * Returns 0 if the new length fits, 1 otherwise. We assume a terminating + * NUL and return 1 if that doesn't fit. + */ + +static int +ztrftimebuf(int *bufsizeptr, int decr) +{ + if (*bufsizeptr <= decr) + return 1; + *bufsizeptr -= decr; + return 0; +} + +/* + * Like the system function, this returns the number of characters + * copied, not including the terminating NUL. This may be zero + * if the string didn't fit. + * + * As an extension, try to detect an error in strftime --- typically + * not enough memory --- and return -1. Not guaranteed to be portable, + * since the strftime() interface doesn't make any guarantees about + * the state of the buffer if it returns zero. + * + * fmt is metafied, but we need to unmetafy it on the fly to + * pass into strftime / combine with the output from strftime. + * The return value in buf is not metafied. + */ + +/**/ +mod_export int +ztrftime(char *buf, int bufsize, char *fmt, struct tm *tm, long nsec) +{ + int hr12; +#ifdef HAVE_STRFTIME + int decr; + char *fmtstart; +#else + static char *astr[] = + {"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"}; + static char *estr[] = + {"Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", + "Aug", "Sep", "Oct", "Nov", "Dec"}; +#endif + char *origbuf = buf; + + + while (*fmt) { + if (*fmt == Meta) { + int chr = fmt[1] ^ 32; + if (ztrftimebuf(&bufsize, 1)) + return -1; + *buf++ = chr; + fmt += 2; + } else if (*fmt == '%') { + int strip; + int digs = 3; + +#ifdef HAVE_STRFTIME + fmtstart = +#endif + fmt++; + + if (*fmt == '-') { + strip = 1; + fmt++; + } else + strip = 0; + if (idigit(*fmt)) { + /* Digit --- only useful with . */ + char *dstart = fmt; + char *dend = fmt+1; + while (idigit(*dend)) + dend++; + if (*dend == '.') { + fmt = dend; + digs = atoi(dstart); + } + } + /* + * Assume this format will take up at least two + * characters. Not always true, but if that matters + * we are so close to the edge it's not a big deal. + * Fix up some longer cases specially when we get to them. + */ + if (ztrftimebuf(&bufsize, 2)) + return -1; +#ifdef HAVE_STRFTIME + /* Our internal handling doesn't handle padding and other gnu extensions, + * so here we detect them and pass over to strftime(). We don't want + * to do this unconditionally though, as we have some extensions that + * strftime() doesn't have (%., %f, %L and %K) */ +morefmt: + if (!((fmt - fmtstart == 1) || (fmt - fmtstart == 2 && strip) || *fmt == '.')) { + while (*fmt && strchr("OE^#_-0123456789", *fmt)) + fmt++; + if (*fmt) { + fmt++; + goto strftimehandling; + } + } +#endif + switch (*fmt++) { + case '.': + if (ztrftimebuf(&bufsize, digs)) + return -1; + if (digs > 9) + digs = 9; + if (digs < 9) { + int trunc; + for (trunc = 8 - digs; trunc; trunc--) + nsec /= 10; + nsec = (nsec + 8) / 10; + } + sprintf(buf, "%0*ld", digs, nsec); + buf += digs; + break; + case '\0': + /* Guard against premature end of string */ + *buf++ = '%'; + fmt--; + break; + case 'f': + strip = 1; + /* FALLTHROUGH */ + case 'e': + if (tm->tm_mday > 9) + *buf++ = '0' + tm->tm_mday / 10; + else if (!strip) + *buf++ = ' '; + *buf++ = '0' + tm->tm_mday % 10; + break; + case 'K': + strip = 1; + /* FALLTHROUGH */ + case 'H': + case 'k': + if (tm->tm_hour > 9) + *buf++ = '0' + tm->tm_hour / 10; + else if (!strip) { + if (fmt[-1] == 'H') + *buf++ = '0'; + else + *buf++ = ' '; + } + *buf++ = '0' + tm->tm_hour % 10; + break; + case 'L': + strip = 1; + /* FALLTHROUGH */ + case 'l': + hr12 = tm->tm_hour % 12; + if (hr12 == 0) + hr12 = 12; + if (hr12 > 9) + *buf++ = '1'; + else if (!strip) + *buf++ = ' '; + + *buf++ = '0' + (hr12 % 10); + break; + case 'd': + if (tm->tm_mday > 9 || !strip) + *buf++ = '0' + tm->tm_mday / 10; + *buf++ = '0' + tm->tm_mday % 10; + break; + case 'm': + if (tm->tm_mon > 8 || !strip) + *buf++ = '0' + (tm->tm_mon + 1) / 10; + *buf++ = '0' + (tm->tm_mon + 1) % 10; + break; + case 'M': + if (tm->tm_min > 9 || !strip) + *buf++ = '0' + tm->tm_min / 10; + *buf++ = '0' + tm->tm_min % 10; + break; + case 'N': + if (ztrftimebuf(&bufsize, 9)) + return -1; + sprintf(buf, "%09ld", nsec); + buf += 9; + break; + case 'S': + if (tm->tm_sec > 9 || !strip) + *buf++ = '0' + tm->tm_sec / 10; + *buf++ = '0' + tm->tm_sec % 10; + break; + case 'y': + if (tm->tm_year > 9 || !strip) + *buf++ = '0' + (tm->tm_year / 10) % 10; + *buf++ = '0' + tm->tm_year % 10; + break; +#ifndef HAVE_STRFTIME + case 'Y': + { + int year, digits, testyear; + year = tm->tm_year + 1900; + digits = 1; + testyear = year; + while (testyear > 9) { + digits++; + testyear /= 10; + } + if (ztrftimebuf(&bufsize, digits)) + return -1; + sprintf(buf, "%d", year); + buf += digits; + break; + } + case 'a': + if (ztrftimebuf(&bufsize, strlen(astr[tm->tm_wday]) - 2)) + return -1; + strucpy(&buf, astr[tm->tm_wday]); + break; + case 'b': + if (ztrftimebuf(&bufsize, strlen(estr[tm->tm_mon]) - 2)) + return -1; + strucpy(&buf, estr[tm->tm_mon]); + break; + case 'p': + *buf++ = (tm->tm_hour > 11) ? 'p' : 'a'; + *buf++ = 'm'; + break; + default: + *buf++ = '%'; + if (fmt[-1] != '%') + *buf++ = fmt[-1]; +#else + case 'E': + case 'O': + case '^': + case '#': + case '_': + case '-': + case '0': case '1': case '2': case '3': case '4': + case '5': case '6': case '7': case '8': case '9': + goto morefmt; +strftimehandling: + default: + /* + * Remember we've already allowed for two characters + * in the accounting in bufsize (but nowhere else). + */ + { + char origchar = fmt[-1]; + int size = fmt - fmtstart; + char *tmp, *last; + tmp = zhalloc(size + 1); + strncpy(tmp, fmtstart, size); + last = fmt-1; + if (*last == Meta) { + /* + * This is for consistency in counting: + * a metafiable character isn't actually + * a valid strftime descriptor. + * + * Previous characters were explicitly checked, + * so can't be metafied. + */ + *last = *++fmt ^ 32; + } + tmp[size] = '\0'; + *buf = '\1'; + if (!strftime(buf, bufsize + 2, tmp, tm)) + { + /* + * Some locales don't have strings for + * AM/PM, so empty output is valid. + */ + if (*buf || (origchar != 'p' && origchar != 'P')) { + if (*buf) { + buf[0] = '\0'; + return -1; + } + return 0; + } + } + decr = strlen(buf); + buf += decr; + bufsize -= decr - 2; + } +#endif + break; + } + } else { + if (ztrftimebuf(&bufsize, 1)) + return -1; + *buf++ = *fmt++; + } + } + *buf = '\0'; + return buf - origbuf; +} + +/**/ +mod_export char * +zjoin(char **arr, int delim, int heap) +{ + int len = 0; + char **s, *ret, *ptr; + + for (s = arr; *s; s++) + len += strlen(*s) + 1 + (imeta(delim) ? 1 : 0); + if (!len) + return heap? "" : ztrdup(""); + ptr = ret = (char *) (heap ? zhalloc(len) : zalloc(len)); + for (s = arr; *s; s++) { + strucpy(&ptr, *s); + if (imeta(delim)) { + *ptr++ = Meta; + *ptr++ = delim ^ 32; + } + else + *ptr++ = delim; + } + ptr[-1 - (imeta(delim) ? 1 : 0)] = '\0'; + return ret; +} + +/* Split a string containing a colon separated list * + * of items into an array of strings. */ + +/**/ +mod_export char ** +colonsplit(char *s, int uniq) +{ + int ct; + char *t, **ret, **ptr, **p; + + for (t = s, ct = 0; *t; t++) /* count number of colons */ + if (*t == ':') + ct++; + ptr = ret = (char **) zalloc(sizeof(char *) * (ct + 2)); + + t = s; + do { + s = t; + /* move t to point at next colon */ + for (; *t && *t != ':'; t++); + if (uniq) + for (p = ret; p < ptr; p++) + if ((int)strlen(*p) == t - s && ! strncmp(*p, s, t - s)) + goto cont; + *ptr = (char *) zalloc((t - s) + 1); + ztrncpy(*ptr++, s, t - s); + cont: ; + } + while (*t++); + *ptr = NULL; + return ret; +} + +/**/ +static int +skipwsep(char **s) +{ + char *t = *s; + int i = 0; + + /* + * Don't need to handle mutlibyte characters, they can't + * be IWSEP. Do need to check for metafication. + */ + while (*t && iwsep(*t == Meta ? t[1] ^ 32 : *t)) { + if (*t == Meta) + t++; + t++; + i++; + } + *s = t; + return i; +} + +/* + * haven't worked out what allownull does; it's passed down from + * sepsplit but all the cases it's used are either 0 or 1 without + * a comment. it seems to be something to do with the `nulstring' + * which i think is some kind of a metafication thing, so probably + * allownull's value is associated with whether we are using + * metafied strings. + * see findsep() below for handling of `quote' argument + */ + +/**/ +mod_export char ** +spacesplit(char *s, int allownull, int heap, int quote) +{ + char *t, **ret, **ptr; + int l = sizeof(*ret) * (wordcount(s, NULL, -!allownull) + 1); + char *(*dup)(const char *) = (heap ? dupstring : ztrdup); + + /* ### TODO: s/calloc/alloc/ */ + ptr = ret = (char **) (heap ? hcalloc(l) : zshcalloc(l)); + + if (quote) { + /* + * we will be stripping quoted separators by hacking string, + * so make sure it's hackable. + */ + s = dupstring(s); + } + + t = s; + skipwsep(&s); + MB_METACHARINIT(); + if (*s && itype_end(s, ISEP, 1) != s) + *ptr++ = dup(allownull ? "" : nulstring); + else if (!allownull && t != s) + *ptr++ = dup(""); + while (*s) { + char *iend = itype_end(s, ISEP, 1); + if (iend != s) { + s = iend; + skipwsep(&s); + } + else if (quote && *s == '\\') { + s++; + skipwsep(&s); + } + t = s; + (void)findsep(&s, NULL, quote); + if (s > t || allownull) { + *ptr = (char *) (heap ? zhalloc((s - t) + 1) : + zalloc((s - t) + 1)); + ztrncpy(*ptr++, t, s - t); + } else + *ptr++ = dup(nulstring); + t = s; + skipwsep(&s); + } + if (!allownull && t != s) + *ptr++ = dup(""); + *ptr = NULL; + return ret; +} + +/* + * Find a separator. Return 0 if already at separator, 1 if separator + * found later, else -1. (Historical note: used to return length into + * string but this is all that is necessary and is less ambiguous with + * multibyte characters around.) + * + * *s is the string we are looking along, which will be updated + * to the point we have got to. + * + * sep is a possibly multicharacter separator to look for. If NULL, + * use normal separator characters. If *sep is NULL, split on individual + * characters. + * + * quote is a flag that '\' should not be treated as a separator. + * in this case we need to be able to strip the backslash directly + * in the string, so the calling function must have sent us something + * modifiable. currently this only works for sep == NULL. also in + * in this case only, we need to turn \\ into \. + */ + +/**/ +static int +findsep(char **s, char *sep, int quote) +{ + /* + */ + int i, ilen; + char *t, *tt; + convchar_t c; + + MB_METACHARINIT(); + if (!sep) { + for (t = *s; *t; t += ilen) { + if (quote && *t == '\\') { + if (t[1] == '\\') { + chuck(t); + ilen = 1; + continue; + } else { + ilen = MB_METACHARLENCONV(t+1, &c); + if (WC_ZISTYPE(c, ISEP)) { + chuck(t); + /* then advance over new character, length ilen */ + } else { + /* treat *t (backslash) as normal byte */ + if (isep(*t)) + break; + ilen = 1; + } + } + } else { + ilen = MB_METACHARLENCONV(t, &c); + if (WC_ZISTYPE(c, ISEP)) + break; + } + } + i = (t > *s); + *s = t; + return i; + } + if (!sep[0]) { + /* + * NULL separator just means advance past first character, + * if any. + */ + if (**s) { + *s += MB_METACHARLEN(*s); + return 1; + } + return -1; + } + for (i = 0; **s; i++) { + /* + * The following works for multibyte characters by virtue of + * the fact that sep may be a string (and we don't care how + * it divides up, we need to match all of it). + */ + for (t = sep, tt = *s; *t && *tt && *t == *tt; t++, tt++); + if (!*t) + return (i > 0); + *s += MB_METACHARLEN(*s); + } + return -1; +} + +/**/ +char * +findword(char **s, char *sep) +{ + char *r, *t; + int sl; + + if (!**s) + return NULL; + + if (sep) { + sl = strlen(sep); + r = *s; + while (! findsep(s, sep, 0)) { + r = *s += sl; + } + return r; + } + MB_METACHARINIT(); + for (t = *s; *t; t += sl) { + convchar_t c; + sl = MB_METACHARLENCONV(t, &c); + if (!WC_ZISTYPE(c, ISEP)) + break; + } + *s = t; + (void)findsep(s, sep, 0); + return t; +} + +/**/ +int +wordcount(char *s, char *sep, int mul) +{ + int r, sl, c; + + if (sep) { + r = 1; + sl = strlen(sep); + for (; (c = findsep(&s, sep, 0)) >= 0; s += sl) + if ((c || mul) && (sl || *(s + sl))) + r++; + } else { + char *t = s; + + r = 0; + if (mul <= 0) + skipwsep(&s); + if ((*s && itype_end(s, ISEP, 1) != s) || + (mul < 0 && t != s)) + r++; + for (; *s; r++) { + char *ie = itype_end(s, ISEP, 1); + if (ie != s) { + s = ie; + if (mul <= 0) + skipwsep(&s); + } + (void)findsep(&s, NULL, 0); + t = s; + if (mul <= 0) + skipwsep(&s); + } + if (mul < 0 && t != s) + r++; + } + return r; +} + +/**/ +mod_export char * +sepjoin(char **s, char *sep, int heap) +{ + char *r, *p, **t; + int l, sl; + char sepbuf[2]; + + if (!*s) + return heap ? "" : ztrdup(""); + if (!sep) { + /* optimise common case that ifs[0] is space */ + if (ifs && *ifs != ' ') { + MB_METACHARINIT(); + sep = dupstrpfx(ifs, MB_METACHARLEN(ifs)); + } else { + p = sep = sepbuf; + *p++ = ' '; + *p = '\0'; + } + } + sl = strlen(sep); + for (t = s, l = 1 - sl; *t; l += strlen(*t) + sl, t++); + r = p = (char *) (heap ? zhalloc(l) : zalloc(l)); + t = s; + while (*t) { + strucpy(&p, *t); + if (*++t) + strucpy(&p, sep); + } + *p = '\0'; + return r; +} + +/**/ +char ** +sepsplit(char *s, char *sep, int allownull, int heap) +{ + int n, sl; + char *t, *tt, **r, **p; + + /* Null string? Treat as empty string. */ + if (s[0] == Nularg && !s[1]) + s++; + + if (!sep) + return spacesplit(s, allownull, heap, 0); + + sl = strlen(sep); + n = wordcount(s, sep, 1); + r = p = (char **) (heap ? zhalloc((n + 1) * sizeof(char *)) : + zalloc((n + 1) * sizeof(char *))); + + for (t = s; n--;) { + tt = t; + (void)findsep(&t, sep, 0); + *p = (char *) (heap ? zhalloc(t - tt + 1) : + zalloc(t - tt + 1)); + strncpy(*p, tt, t - tt); + (*p)[t - tt] = '\0'; + p++; + t += sl; + } + *p = NULL; + + return r; +} + +/* Get the definition of a shell function */ + +/**/ +mod_export Shfunc +getshfunc(char *nam) +{ + return (Shfunc) shfunctab->getnode(shfunctab, nam); +} + +/* + * Call the function func to substitute string orig by setting + * the parameter reply. + * Return the array from reply, or NULL if the function returned + * non-zero status. + * The returned value comes directly from the parameter and + * so should be used before there is any chance of that + * being changed or unset. + * If arg1 is not NULL, it is used as an initial argument to + * the function, with the original string as the second argument. + */ + +/**/ +char ** +subst_string_by_func(Shfunc func, char *arg1, char *orig) +{ + int osc = sfcontext, osm = stopmsg, old_incompfunc = incompfunc; + LinkList l = newlinklist(); + char **ret; + + addlinknode(l, func->node.nam); + if (arg1) + addlinknode(l, arg1); + addlinknode(l, orig); + sfcontext = SFC_SUBST; + incompfunc = 0; + + if (doshfunc(func, l, 1)) + ret = NULL; + else + ret = getaparam("reply"); + + sfcontext = osc; + stopmsg = osm; + incompfunc = old_incompfunc; + return ret; +} + +/** + * Front end to subst_string_by_func to use hook-like logic. + * name can refer to a function, and name + "_hook" can refer + * to an array containing a list of functions. The functions + * are tried in order until one returns success. + */ +/**/ +char ** +subst_string_by_hook(char *name, char *arg1, char *orig) +{ + Shfunc func; + char **ret = NULL; + + if ((func = getshfunc(name))) { + ret = subst_string_by_func(func, arg1, orig); + } + + if (!ret) { + char **arrptr; + int namlen = strlen(name); + VARARR(char, arrnam, namlen + HOOK_SUFFIX_LEN); + memcpy(arrnam, name, namlen); + memcpy(arrnam + namlen, HOOK_SUFFIX, HOOK_SUFFIX_LEN); + + if ((arrptr = getaparam(arrnam))) { + /* Guard against internal modification of the array */ + arrptr = arrdup(arrptr); + for (; *arrptr; arrptr++) { + if ((func = getshfunc(*arrptr))) { + ret = subst_string_by_func(func, arg1, orig); + if (ret) + break; + } + } + } + } + + return ret; +} + +/**/ +mod_export char ** +mkarray(char *s) +{ + char **t = (char **) zalloc((s) ? (2 * sizeof s) : (sizeof s)); + + if ((*t = s)) + t[1] = NULL; + return t; +} + +/**/ +mod_export char ** +hmkarray(char *s) +{ + char **t = (char **) zhalloc((s) ? (2 * sizeof s) : (sizeof s)); + + if ((*t = s)) + t[1] = NULL; + return t; +} + +/**/ +mod_export void +zbeep(void) +{ + char *vb; + queue_signals(); + if ((vb = getsparam_u("ZBEEP"))) { + int len; + vb = getkeystring(vb, &len, GETKEYS_BINDKEY, NULL); + write_loop(SHTTY, vb, len); + } else if (isset(BEEP)) + write_loop(SHTTY, "\07", 1); + unqueue_signals(); +} + +/**/ +mod_export void +freearray(char **s) +{ + char **t = s; + + DPUTS(!s, "freearray() with zero argument"); + + while (*s) + zsfree(*s++); + free(t); +} + +/**/ +int +equalsplit(char *s, char **t) +{ + for (; *s && *s != '='; s++); + if (*s == '=') { + *s++ = '\0'; + *t = s; + return 1; + } + return 0; +} + + +/* the ztypes table */ + +/**/ +mod_export short int typtab[256]; +static int typtab_flags = 0; + +/* initialize the ztypes table */ + +/**/ +void +inittyptab(void) +{ + int t0; + char *s; + + if (!(typtab_flags & ZTF_INIT)) { + typtab_flags = ZTF_INIT; + if (interact && isset(SHINSTDIN)) + typtab_flags |= ZTF_INTERACT; + } + + queue_signals(); + + memset(typtab, 0, sizeof(typtab)); + for (t0 = 0; t0 != 32; t0++) + typtab[t0] = typtab[t0 + 128] = ICNTRL; + typtab[127] = ICNTRL; + for (t0 = '0'; t0 <= '9'; t0++) + typtab[t0] = IDIGIT | IALNUM | IWORD | IIDENT | IUSER; + for (t0 = 'a'; t0 <= 'z'; t0++) + typtab[t0] = typtab[t0 - 'a' + 'A'] = IALPHA | IALNUM | IIDENT | IUSER | IWORD; +#ifndef MULTIBYTE_SUPPORT + /* + * This really doesn't seem to me the right thing to do when + * we have multibyte character support... it was a hack to assume + * eight bit characters `worked' for some values of work before + * we could test for them properly. I'm not 100% convinced + * having IIDENT here is a good idea at all, but this code + * should disappear into history... + */ + for (t0 = 0240; t0 != 0400; t0++) + typtab[t0] = IALPHA | IALNUM | IIDENT | IUSER | IWORD; +#endif + /* typtab['.'] |= IIDENT; */ /* Allow '.' in variable names - broken */ + typtab['_'] = IIDENT | IUSER; + typtab['-'] = typtab['.'] = typtab[STOUC(Dash)] = IUSER; + typtab[' '] |= IBLANK | INBLANK; + typtab['\t'] |= IBLANK | INBLANK; + typtab['\n'] |= INBLANK; + typtab['\0'] |= IMETA; + typtab[STOUC(Meta) ] |= IMETA; + typtab[STOUC(Marker)] |= IMETA; + for (t0 = (int)STOUC(Pound); t0 <= (int)STOUC(LAST_NORMAL_TOK); t0++) + typtab[t0] |= ITOK | IMETA; + for (t0 = (int)STOUC(Snull); t0 <= (int)STOUC(Nularg); t0++) + typtab[t0] |= ITOK | IMETA | INULL; + for (s = ifs ? ifs : EMULATION(EMULATE_KSH|EMULATE_SH) ? + DEFAULT_IFS_SH : DEFAULT_IFS; *s; s++) { + int c = STOUC(*s == Meta ? *++s ^ 32 : *s); +#ifdef MULTIBYTE_SUPPORT + if (!isascii(c)) { + /* see comment for wordchars below */ + continue; + } +#endif + if (inblank(c)) { + if (s[1] == c) + s++; + else + typtab[c] |= IWSEP; + } + typtab[c] |= ISEP; + } + for (s = wordchars ? wordchars : DEFAULT_WORDCHARS; *s; s++) { + int c = STOUC(*s == Meta ? *++s ^ 32 : *s); +#ifdef MULTIBYTE_SUPPORT + if (!isascii(c)) { + /* + * If we have support for multibyte characters, we don't + * handle non-ASCII characters here; instead, we turn + * wordchars into a wide character array. + * (We may actually have a single-byte 8-bit character set, + * but it works the same way.) + */ + continue; + } +#endif + typtab[c] |= IWORD; + } +#ifdef MULTIBYTE_SUPPORT + set_widearray(wordchars, &wordchars_wide); + set_widearray(ifs ? ifs : EMULATION(EMULATE_KSH|EMULATE_SH) ? + DEFAULT_IFS_SH : DEFAULT_IFS, &ifs_wide); +#endif + for (s = SPECCHARS; *s; s++) + typtab[STOUC(*s)] |= ISPECIAL; + if (typtab_flags & ZTF_SP_COMMA) + typtab[STOUC(',')] |= ISPECIAL; + if (isset(BANGHIST) && bangchar && (typtab_flags & ZTF_INTERACT)) { + typtab_flags |= ZTF_BANGCHAR; + typtab[bangchar] |= ISPECIAL; + } else + typtab_flags &= ~ZTF_BANGCHAR; + for (s = PATCHARS; *s; s++) + typtab[STOUC(*s)] |= IPATTERN; + + unqueue_signals(); +} + +/**/ +mod_export void +makecommaspecial(int yesno) +{ + if (yesno != 0) { + typtab_flags |= ZTF_SP_COMMA; + typtab[STOUC(',')] |= ISPECIAL; + } else { + typtab_flags &= ~ZTF_SP_COMMA; + typtab[STOUC(',')] &= ~ISPECIAL; + } +} + +/**/ +mod_export void +makebangspecial(int yesno) +{ + /* Name and call signature for congruence with makecommaspecial(), + * but in this case when yesno is nonzero we defer to the state + * saved by inittyptab(). + */ + if (yesno == 0) { + typtab[bangchar] &= ~ISPECIAL; + } else if (typtab_flags & ZTF_BANGCHAR) { + typtab[bangchar] |= ISPECIAL; + } +} + + +/**/ +#ifdef MULTIBYTE_SUPPORT +/* A wide-character version of the iblank() macro. */ +/**/ +mod_export int +wcsiblank(wint_t wc) +{ + if (iswspace(wc) && wc != L'\n') + return 1; + return 0; +} + +/* + * zistype macro extended to support wide characters. + * Works for IIDENT, IWORD, IALNUM, ISEP. + * We don't need this for IWSEP because that only applies to + * a fixed set of ASCII characters. + * Note here that use of multibyte mode is not tested: + * that's because for ZLE this is unconditional, + * not dependent on the option. The caller must decide. + */ + +/**/ +mod_export int +wcsitype(wchar_t c, int itype) +{ + int len; + mbstate_t mbs; + VARARR(char, outstr, MB_CUR_MAX); + + if (!isset(MULTIBYTE)) + return zistype(c, itype); + + /* + * Strategy: the shell requires that the multibyte representation + * be an extension of ASCII. So see if converting the character + * produces an ASCII character. If it does, use zistype on that. + * If it doesn't, use iswalnum on the original character. + * If that fails, resort to the appropriate wide character array. + */ + memset(&mbs, 0, sizeof(mbs)); + len = wcrtomb(outstr, c, &mbs); + + if (len == 0) { + /* NULL is special */ + return zistype(0, itype); + } else if (len == 1 && isascii(outstr[0])) { + return zistype(outstr[0], itype); + } else { + switch (itype) { + case IIDENT: + if (!isset(POSIXIDENTIFIERS)) + return 0; + return iswalnum(c); + + case IWORD: + if (iswalnum(c)) + return 1; + /* + * If we are handling combining characters, any punctuation + * characters with zero width needs to be considered part of + * a word. If we are not handling combining characters then + * logically they are still part of the word, even if they + * don't get displayed properly, so always do this. + */ + if (IS_COMBINING(c)) + return 1; + return !!wmemchr(wordchars_wide.chars, c, wordchars_wide.len); + + case ISEP: + return !!wmemchr(ifs_wide.chars, c, ifs_wide.len); + + default: + return iswalnum(c); + } + } +} + +/**/ +#endif + + +/* + * Find the end of a set of characters in the set specified by itype; + * one of IALNUM, IIDENT, IWORD or IUSER. For non-ASCII characters, we assume + * alphanumerics are part of the set, with the exception that + * identifiers are not treated that way if POSIXIDENTIFIERS is set. + * + * See notes above for identifiers. + * Returns the same pointer as passed if not on an identifier character. + * If "once" is set, just test the first character, i.e. (outptr != + * inptr) tests whether the first character is valid in an identifier. + * + * Currently this is only called with itype IIDENT, IUSER or ISEP. + */ + +/**/ +mod_export char * +itype_end(const char *ptr, int itype, int once) +{ +#ifdef MULTIBYTE_SUPPORT + if (isset(MULTIBYTE) && + (itype != IIDENT || !isset(POSIXIDENTIFIERS))) { + mb_charinit(); + while (*ptr) { + int len; + if (itok(*ptr)) { + /* Not untokenised yet --- can happen in raw command line */ + len = 1; + if (!zistype(*ptr,itype)) + break; + } else { + wint_t wc; + len = mb_metacharlenconv(ptr, &wc); + + if (!len) + break; + + if (wc == WEOF) { + /* invalid, treat as single character */ + int chr = STOUC(*ptr == Meta ? ptr[1] ^ 32 : *ptr); + /* in this case non-ASCII characters can't match */ + if (chr > 127 || !zistype(chr,itype)) + break; + } else if (len == 1 && isascii(*ptr)) { + /* ASCII: can't be metafied, use standard test */ + if (!zistype(*ptr,itype)) + break; + } else { + /* + * Valid non-ASCII character. + */ + switch (itype) { + case IWORD: + if (!iswalnum(wc) && + !wmemchr(wordchars_wide.chars, wc, + wordchars_wide.len)) + return (char *)ptr; + break; + + case ISEP: + if (!wmemchr(ifs_wide.chars, wc, ifs_wide.len)) + return (char *)ptr; + break; + + default: + if (!iswalnum(wc)) + return (char *)ptr; + } + } + } + ptr += len; + + if (once) + break; + } + } else +#endif + for (;;) { + int chr = STOUC(*ptr == Meta ? ptr[1] ^ 32 : *ptr); + if (!zistype(chr,itype)) + break; + ptr += (*ptr == Meta) ? 2 : 1; + + if (once) + break; + } + + /* + * Nasty. The first argument is const char * because we + * don't modify it here. However, we really want to pass + * back the same type as was passed down, to allow idioms like + * p = itype_end(p, IIDENT, 0); + * So returning a const char * isn't really the right thing to do. + * Without having two different functions the following seems + * to be the best we can do. + */ + return (char *)ptr; +} + +/**/ +mod_export char ** +arrdup(char **s) +{ + char **x, **y; + + y = x = (char **) zhalloc(sizeof(char *) * (arrlen(s) + 1)); + + while ((*x++ = dupstring(*s++))); + + return y; +} + +/* Duplicate at most max elements of the array s with heap memory */ + +/**/ +mod_export char ** +arrdup_max(char **s, unsigned max) +{ + char **x, **y, **send; + int len = 0; + + if (max) + len = arrlen(s); + + /* Limit has sense only if not equal to len */ + if (max > len) + max = len; + + y = x = (char **) zhalloc(sizeof(char *) * (max + 1)); + + send = s + max; + while (s < send) + *x++ = dupstring(*s++); + *x = NULL; + + return y; +} + +/**/ +mod_export char ** +zarrdup(char **s) +{ + char **x, **y; + + y = x = (char **) zalloc(sizeof(char *) * (arrlen(s) + 1)); + + while ((*x++ = ztrdup(*s++))); + + return y; +} + +/**/ +#ifdef MULTIBYTE_SUPPORT +/**/ +mod_export wchar_t ** +wcs_zarrdup(wchar_t **s) +{ + wchar_t **x, **y; + + y = x = (wchar_t **) zalloc(sizeof(wchar_t *) * (arrlen((char **)s) + 1)); + + while ((*x++ = wcs_ztrdup(*s++))); + + return y; +} +/**/ +#endif /* MULTIBYTE_SUPPORT */ + +/**/ +static char * +spname(char *oldname) +{ + char *p, spnameguess[PATH_MAX + 1], spnamebest[PATH_MAX + 1]; + static char newname[PATH_MAX + 1]; + char *new = newname, *old = oldname; + int bestdist = 0, thisdist, thresh, maxthresh = 0; + + /* This loop corrects each directory component of the path, stopping * + * when any correction distance would exceed the distance threshold. * + * NULL is returned only if the first component cannot be corrected; * + * otherwise a copy of oldname with a corrected prefix is returned. * + * Rationale for this, if there ever was any, has been forgotten. */ + for (;;) { + while (*old == '/') { + if (new >= newname + sizeof(newname) - 1) + return NULL; + *new++ = *old++; + } + *new = '\0'; + if (*old == '\0') + return newname; + p = spnameguess; + for (; *old != '/' && *old != '\0'; old++) + if (p < spnameguess + PATH_MAX) + *p++ = *old; + *p = '\0'; + /* Every component is allowed a single distance 2 correction or two * + * distance 1 corrections. Longer ones get additional corrections. */ + thresh = (int)(p - spnameguess) / 4 + 1; + if (thresh < 3) + thresh = 3; + else if (thresh > 100) + thresh = 100; + thisdist = mindist(newname, spnameguess, spnamebest, *old == '/'); + if (thisdist >= thresh) { + /* The next test is always true, except for the first path * + * component. We could initialize bestdist to some large * + * constant instead, and then compare to that constant here, * + * because an invariant is that we've never exceeded the * + * threshold for any component so far; but I think that looks * + * odd to the human reader, and we may make use of the total * + * distance for all corrections at some point in the future. */ + if (bestdist < maxthresh) { + struncpy(&new, spnameguess, sizeof(newname) - (new - newname)); + struncpy(&new, old, sizeof(newname) - (new - newname)); + return (new >= newname + sizeof(newname) -1) ? NULL : newname; + } else + return NULL; + } else { + maxthresh = bestdist + thresh; + bestdist += thisdist; + } + for (p = spnamebest; (*new = *p++);) { + if (new >= newname + sizeof(newname) - 1) + return NULL; + new++; + } + } +} + +/**/ +static int +mindist(char *dir, char *mindistguess, char *mindistbest, int wantdir) +{ + int mindistd, nd; + DIR *dd; + char *fn; + char *buf; + struct stat st; + size_t dirlen; + + if (dir[0] == '\0') + dir = "."; + mindistd = 100; + + if (!(buf = zalloc((dirlen = strlen(dir)) + strlen(mindistguess) + 2))) + return 0; + sprintf(buf, "%s/%s", dir, mindistguess); + + if (stat(unmeta(buf), &st) == 0 && (!wantdir || S_ISDIR(st.st_mode))) { + strcpy(mindistbest, mindistguess); + free(buf); + return 0; + } + + if ((dd = opendir(unmeta(dir)))) { + while ((fn = zreaddir(dd, 0))) { + if (spnamepat && pattry(spnamepat, fn)) + continue; + nd = spdist(fn, mindistguess, + (int)strlen(mindistguess) / 4 + 1); + if (nd <= mindistd) { + if (wantdir) { + if (!(buf = zrealloc(buf, dirlen + strlen(fn) + 2))) + continue; + sprintf(buf, "%s/%s", dir, fn); + if (stat(unmeta(buf), &st) != 0 || !S_ISDIR(st.st_mode)) + continue; + } + strcpy(mindistbest, fn); + mindistd = nd; + if (mindistd == 0) + break; + } + } + closedir(dd); + } + free(buf); + return mindistd; +} + +/**/ +static int +spdist(char *s, char *t, int thresh) +{ + /* TODO: Correction for non-ASCII and multibyte-input keyboards. */ + char *p, *q; + const char qwertykeymap[] = + "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ +\t1234567890-=\t\ +\tqwertyuiop[]\t\ +\tasdfghjkl;'\n\t\ +\tzxcvbnm,./\t\t\t\ +\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ +\t!@#$%^&*()_+\t\ +\tQWERTYUIOP{}\t\ +\tASDFGHJKL:\"\n\t\ +\tZXCVBNM<>?\n\n\t\ +\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; + const char dvorakkeymap[] = + "\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ +\t1234567890[]\t\ +\t',.pyfgcrl/=\t\ +\taoeuidhtns-\n\t\ +\t;qjkxbmwvz\t\t\t\ +\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ +\t!@#$%^&*(){}\t\ +\t\"<>PYFGCRL?+\t\ +\tAOEUIDHTNS_\n\t\ +\t:QJKXBMWVZ\n\n\t\ +\n\n\n\n\n\n\n\n\n\n\n\n\n\n"; + const char *keymap; + if ( isset( DVORAK ) ) + keymap = dvorakkeymap; + else + keymap = qwertykeymap; + + if (!strcmp(s, t)) + return 0; + /* any number of upper/lower mistakes allowed (dist = 1) */ + for (p = s, q = t; *p && tulower(*p) == tulower(*q); p++, q++); + if (!*p && !*q) + return 1; + if (!thresh) + return 200; + for (p = s, q = t; *p && *q; p++, q++) + if (*p == *q) + continue; /* don't consider "aa" transposed, ash */ + else if (p[1] == q[0] && q[1] == p[0]) /* transpositions */ + return spdist(p + 2, q + 2, thresh - 1) + 1; + else if (p[1] == q[0]) /* missing letter */ + return spdist(p + 1, q + 0, thresh - 1) + 2; + else if (p[0] == q[1]) /* missing letter */ + return spdist(p + 0, q + 1, thresh - 1) + 2; + else if (*p != *q) + break; + if ((!*p && strlen(q) == 1) || (!*q && strlen(p) == 1)) + return 2; + for (p = s, q = t; *p && *q; p++, q++) + if (p[0] != q[0] && p[1] == q[1]) { + int t0; + char *z; + + /* mistyped letter */ + + if (!(z = strchr(keymap, p[0])) || *z == '\n' || *z == '\t') + return spdist(p + 1, q + 1, thresh - 1) + 1; + t0 = z - keymap; + if (*q == keymap[t0 - 15] || *q == keymap[t0 - 14] || + *q == keymap[t0 - 13] || + *q == keymap[t0 - 1] || *q == keymap[t0 + 1] || + *q == keymap[t0 + 13] || *q == keymap[t0 + 14] || + *q == keymap[t0 + 15]) + return spdist(p + 1, q + 1, thresh - 1) + 2; + return 200; + } else if (*p != *q) + break; + return 200; +} + +/* set cbreak mode, or the equivalent */ + +/**/ +void +setcbreak(void) +{ + struct ttyinfo ti; + + ti = shttyinfo; +#ifdef HAS_TIO + ti.tio.c_lflag &= ~ICANON; + ti.tio.c_cc[VMIN] = 1; + ti.tio.c_cc[VTIME] = 0; +#else + ti.sgttyb.sg_flags |= CBREAK; +#endif + settyinfo(&ti); +} + +/* give the tty to some process */ + +/**/ +mod_export void +attachtty(pid_t pgrp) +{ + static int ep = 0; + + if (jobbing && interact) { +#ifdef HAVE_TCSETPGRP + if (SHTTY != -1 && tcsetpgrp(SHTTY, pgrp) == -1 && !ep) +#else +# if ardent + if (SHTTY != -1 && setpgrp() == -1 && !ep) +# else + int arg = pgrp; + + if (SHTTY != -1 && ioctl(SHTTY, TIOCSPGRP, &arg) == -1 && !ep) +# endif +#endif + { + if (pgrp != mypgrp && kill(-pgrp, 0) == -1) + attachtty(mypgrp); + else { + if (errno != ENOTTY) + { + zwarn("can't set tty pgrp: %e", errno); + fflush(stderr); + } + opts[MONITOR] = 0; + ep = 1; + } + } + } +} + +/* get the process group associated with the tty */ + +/**/ +pid_t +gettygrp(void) +{ + pid_t arg; + + if (SHTTY == -1) + return -1; + +#ifdef HAVE_TCSETPGRP + arg = tcgetpgrp(SHTTY); +#else + ioctl(SHTTY, TIOCGPGRP, &arg); +#endif + + return arg; +} + + +/* Escape tokens and null characters. Buf is the string which should be * + * escaped. len is the length of the string. If len is -1, buf should be * + * null terminated. If len is non-negative and the third parameter is not * + * META_DUP, buf should point to an at least len+1 long memory area. The * + * return value points to the quoted string. If the given string does not * + * contain any special character which should be quoted and the third * + * parameter is not META_(HEAP|)DUP, buf is returned unchanged (a * + * terminating null character is appended to buf if necessary). Otherwise * + * the third `heap' argument determines the method used to allocate space * + * for the result. It can have the following values: * + * META_REALLOC: use zrealloc on buf * + * META_HREALLOC: use hrealloc on buf * + * META_USEHEAP: get memory from the heap. This leaves buf unchanged. * + * META_NOALLOC: buf points to a memory area which is long enough to hold * + * the quoted form, just quote it and return buf. * + * META_STATIC: store the quoted string in a static area. The original * + * string should be at most PATH_MAX long. * + * META_ALLOC: allocate memory for the new string with zalloc(). * + * META_DUP: leave buf unchanged and allocate space for the return * + * value even if buf does not contains special characters * + * META_HEAPDUP: same as META_DUP, but uses the heap */ + +/**/ +mod_export char * +metafy(char *buf, int len, int heap) +{ + int meta = 0; + char *t, *p, *e; + static char mbuf[PATH_MAX*2+1]; + + if (len == -1) { + for (e = buf, len = 0; *e; len++) + if (imeta(*e++)) + meta++; + } else + for (e = buf; e < buf + len;) + if (imeta(*e++)) + meta++; + + if (meta || heap == META_DUP || heap == META_HEAPDUP) { + switch (heap) { + case META_REALLOC: + buf = zrealloc(buf, len + meta + 1); + break; + case META_HREALLOC: + buf = hrealloc(buf, len, len + meta + 1); + break; + case META_ALLOC: + case META_DUP: + buf = memcpy(zalloc(len + meta + 1), buf, len); + break; + case META_USEHEAP: + case META_HEAPDUP: + buf = memcpy(zhalloc(len + meta + 1), buf, len); + break; + case META_STATIC: +#ifdef DEBUG + if (len > PATH_MAX) { + fprintf(stderr, "BUG: len = %d > PATH_MAX in metafy\n", len); + fflush(stderr); + } +#endif + buf = memcpy(mbuf, buf, len); + break; +#ifdef DEBUG + case META_NOALLOC: + break; + default: + fprintf(stderr, "BUG: metafy called with invalid heap value\n"); + fflush(stderr); + break; +#endif + } + p = buf + len; + e = t = buf + len + meta; + while (meta) { + if (imeta(*--t = *--p)) { + *t-- ^= 32; + *t = Meta; + meta--; + } + } + } + *e = '\0'; + return buf; +} + + +/* + * Duplicate a string, metafying it as we go. + * + * Typically, this is used only for strings imported from outside + * zsh, as strings internally are either already metafied or passed + * around with an associated length. + */ +/**/ +mod_export char * +ztrdup_metafy(const char *s) +{ + /* To mimic ztrdup() behaviour */ + if (!s) + return NULL; + /* + * metafy() does lots of different things, so the pointer + * isn't const. Using it with META_DUP should be safe. + */ + return metafy((char *)s, -1, META_DUP); +} + + +/* + * Take a null-terminated, metafied string in s into a literal + * representation by converting in place. The length is in *len + * len is non-NULL; if len is NULL, you don't know the length of + * the final string, but if it's to be supplied to some system + * routine that always uses NULL termination, such as a filename + * interpreter, that doesn't matter. Note the NULL termination + * is always copied for purposes of that kind. + */ + +/**/ +mod_export char * +unmetafy(char *s, int *len) +{ + char *p, *t; + + for (p = s; *p && *p != Meta; p++); + for (t = p; (*t = *p++);) + if (*t++ == Meta && *p) + t[-1] = *p++ ^ 32; + if (len) + *len = t - s; + return s; +} + +/* Return the character length of a metafied substring, given the * + * unmetafied substring length. */ + +/**/ +mod_export int +metalen(const char *s, int len) +{ + int mlen = len; + + while (len--) { + if (*s++ == Meta) { + mlen++; + s++; + } + } + return mlen; +} + +/* + * This function converts a zsh internal string to a form which can be + * passed to a system call as a filename. The result is stored in a + * single static area, sized to fit. If there is no Meta character + * the original string is returned. + */ + +/**/ +mod_export char * +unmeta(const char *file_name) +{ + static char *fn; + static int sz; + char *p; + const char *t; + int newsz, meta; + + if (!file_name) + return NULL; + + meta = 0; + for (t = file_name; *t; t++) { + if (*t == Meta) + meta = 1; + } + if (!meta) { + /* + * don't need allocation... free if it's long, see below + */ + if (sz > 4 * PATH_MAX) { + zfree(fn, sz); + fn = NULL; + sz = 0; + } + return (char *) file_name; + } + + newsz = (t - file_name) + 1; + /* + * Optimisation: don't resize if we don't have to. + * We need a new allocation if + * - nothing was allocated before + * - the new string is larger than the old one + * - the old string was larger than an arbitrary limit but the + * new string isn't so that we free up significant space by resizing. + */ + if (!fn || newsz > sz || (sz > 4 * PATH_MAX && newsz <= 4 * PATH_MAX)) + { + if (fn) + zfree(fn, sz); + sz = newsz; + fn = (char *)zalloc(sz); + if (!fn) { + sz = 0; + /* + * will quite likely crash in the caller anyway... + */ + return NULL; + } + } + + for (t = file_name, p = fn; *t; p++) + if ((*p = *t++) == Meta && *t) + *p = *t++ ^ 32; + *p = '\0'; + return fn; +} + +/* + * Unmetafy just one character and store the number of bytes it occupied. + */ +/**/ +mod_export convchar_t +unmeta_one(const char *in, int *sz) +{ + convchar_t wc; + int newsz; +#ifdef MULTIBYTE_SUPPORT + mbstate_t wstate; +#endif + + if (!sz) + sz = &newsz; + *sz = 0; + + if (!in || !*in) + return 0; + +#ifdef MULTIBYTE_SUPPORT + memset(&wstate, 0, sizeof(wstate)); + *sz = mb_metacharlenconv_r(in, &wc, &wstate); +#else + if (in[0] == Meta) { + *sz = 2; + wc = STOUC(in[1] ^ 32); + } else { + *sz = 1; + wc = STOUC(in[0]); + } +#endif + return wc; +} + +/* + * Unmetafy and compare two strings, comparing unsigned character values. + * "a\0" sorts after "a". + * + * Currently this is only used in hash table sorting, where the + * keys are names of hash nodes and where we don't use strcoll(); + * it's not clear if that's right but it does guarantee the ordering + * of shell structures on output. + * + * As we don't use strcoll(), it seems overkill to convert multibyte + * characters to wide characters for comparison every time. In the case + * of UTF-8, Unicode ordering is preserved when sorted raw, and for + * other character sets we rely on an extension of ASCII so the result, + * while it may not be correct, is at least rational. + */ + +/**/ +int +ztrcmp(char const *s1, char const *s2) +{ + int c1, c2; + + while(*s1 && *s1 == *s2) { + s1++; + s2++; + } + + if(!(c1 = *s1)) + c1 = -1; + else if(c1 == STOUC(Meta)) + c1 = *++s1 ^ 32; + if(!(c2 = *s2)) + c2 = -1; + else if(c2 == STOUC(Meta)) + c2 = *++s2 ^ 32; + + if(c1 == c2) + return 0; + else if(c1 < c2) + return -1; + else + return 1; +} + +/* Return the unmetafied length of a metafied string. */ + +/**/ +mod_export int +ztrlen(char const *s) +{ + int l; + + for (l = 0; *s; l++) { + if (*s++ == Meta) { +#ifdef DEBUG + if (! *s) { + fprintf(stderr, "BUG: unexpected end of string in ztrlen()\n"); + break; + } else +#endif + s++; + } + } + return l; +} + +#ifndef MULTIBYTE_SUPPORT +/* + * ztrlen() but with explicit end point for non-null-terminated + * segments. eptr may not be NULL. + */ + +/**/ +mod_export int +ztrlenend(char const *s, char const *eptr) +{ + int l; + + for (l = 0; s < eptr; l++) { + if (*s++ == Meta) { +#ifdef DEBUG + if (! *s) { + fprintf(stderr, + "BUG: unexpected end of string in ztrlenend()\n"); + break; + } else +#endif + s++; + } + } + return l; +} + +#endif /* MULTIBYTE_SUPPORT */ + +/* Subtract two pointers in a metafied string. */ + +/**/ +mod_export int +ztrsub(char const *t, char const *s) +{ + int l = t - s; + + while (s != t) { + if (*s++ == Meta) { +#ifdef DEBUG + if (! *s || s == t) + fprintf(stderr, "BUG: substring ends in the middle of a metachar in ztrsub()\n"); + else +#endif + s++; + l--; + } + } + return l; +} + +/* + * Wrapper for readdir(). + * + * If ignoredots is true, skip the "." and ".." entries. + * + * When __APPLE__ is defined, recode dirent names from UTF-8-MAC to UTF-8. + * + * Return the dirent's name, metafied. + */ + +/**/ +mod_export char * +zreaddir(DIR *dir, int ignoredots) +{ + struct dirent *de; +#if defined(HAVE_ICONV) && defined(__APPLE__) + static iconv_t conv_ds = (iconv_t)0; + static char *conv_name = 0; + char *conv_name_ptr, *orig_name_ptr; + size_t conv_name_len, orig_name_len; +#endif + + do { + de = readdir(dir); + if(!de) + return NULL; + } while(ignoredots && de->d_name[0] == '.' && + (!de->d_name[1] || (de->d_name[1] == '.' && !de->d_name[2]))); + +#if defined(HAVE_ICONV) && defined(__APPLE__) + if (!conv_ds) + conv_ds = iconv_open("UTF-8", "UTF-8-MAC"); + if (conv_ds != (iconv_t)(-1)) { + /* Force initial state in case re-using conv_ds */ + (void) iconv(conv_ds, 0, &orig_name_len, 0, &conv_name_len); + + orig_name_ptr = de->d_name; + orig_name_len = strlen(de->d_name); + conv_name = zrealloc(conv_name, orig_name_len+1); + conv_name_ptr = conv_name; + conv_name_len = orig_name_len; + if (iconv(conv_ds, + &orig_name_ptr, &orig_name_len, + &conv_name_ptr, &conv_name_len) != (size_t)(-1) && + orig_name_len == 0) { + /* Completely converted, metafy and return */ + *conv_name_ptr = '\0'; + return metafy(conv_name, -1, META_STATIC); + } + /* Error, or conversion incomplete, keep the original name */ + } +#endif + + return metafy(de->d_name, -1, META_STATIC); +} + +/* Unmetafy and output a string. Tokens are skipped. */ + +/**/ +mod_export int +zputs(char const *s, FILE *stream) +{ + int c; + + while (*s) { + if (*s == Meta) + c = *++s ^ 32; + else if(itok(*s)) { + s++; + continue; + } else + c = *s; + s++; + if (fputc(c, stream) < 0) + return EOF; + } + return 0; +} + +#ifndef MULTIBYTE_SUPPORT +/* Create a visibly-represented duplicate of a string. */ + +/**/ +mod_export char * +nicedup(char const *s, int heap) +{ + int c, len = strlen(s) * 5 + 1; + VARARR(char, buf, len); + char *p = buf, *n; + + while ((c = *s++)) { + if (itok(c)) { + if (c <= Comma) + c = ztokens[c - Pound]; + else + continue; + } + if (c == Meta) + c = *s++ ^ 32; + /* The result here is metafied */ + n = nicechar(c); + while(*n) + *p++ = *n++; + } + *p = '\0'; + return heap ? dupstring(buf) : ztrdup(buf); +} +#endif + +/**/ +mod_export char * +nicedupstring(char const *s) +{ + return nicedup(s, 1); +} + + +#ifndef MULTIBYTE_SUPPORT +/* Unmetafy and output a string, displaying special characters readably. */ + +/**/ +mod_export int +nicezputs(char const *s, FILE *stream) +{ + int c; + + while ((c = *s++)) { + if (itok(c)) { + if (c <= Comma) + c = ztokens[c - Pound]; + else + continue; + } + if (c == Meta) + c = *s++ ^ 32; + if(zputs(nicechar(c), stream) < 0) + return EOF; + } + return 0; +} + + +/* Return the length of the visible representation of a metafied string. */ + +/**/ +mod_export size_t +niceztrlen(char const *s) +{ + size_t l = 0; + int c; + + while ((c = *s++)) { + if (itok(c)) { + if (c <= Comma) + c = ztokens[c - Pound]; + else + continue; + } + if (c == Meta) + c = *s++ ^ 32; + l += strlen(nicechar(c)); + } + return l; +} +#endif + + +/**/ +#ifdef MULTIBYTE_SUPPORT +/* + * Version of both nicezputs() and niceztrlen() for use with multibyte + * characters. Input is a metafied string; output is the screen width of + * the string. + * + * If the FILE * is not NULL, output to that, too. + * + * If outstrp is not NULL, set *outstrp to a zalloc'd version of + * the output (still metafied). + * + * If flags contains NICEFLAG_HEAP, use the heap for *outstrp, else + * zalloc. + * If flags contsins NICEFLAG_QUOTE, the output is going to be within + * $'...', so quote "'" and "\" with a backslash. + */ + +/**/ +mod_export size_t +mb_niceformat(const char *s, FILE *stream, char **outstrp, int flags) +{ + size_t l = 0, newl; + int umlen, outalloc, outleft, eol = 0; + wchar_t c; + char *ums, *ptr, *fmt, *outstr, *outptr; + mbstate_t mbs; + + if (outstrp) { + outleft = outalloc = 5 * strlen(s); + outptr = outstr = zalloc(outalloc); + } else { + outleft = outalloc = 0; + outptr = outstr = NULL; + } + + ums = ztrdup(s); + /* + * is this necessary at this point? niceztrlen does this + * but it's used in lots of places. however, one day this may + * be, too. + */ + untokenize(ums); + ptr = unmetafy(ums, ¨en); + + memset(&mbs, 0, sizeof mbs); + while (umlen > 0) { + size_t cnt = eol ? MB_INVALID : mbrtowc(&c, ptr, umlen, &mbs); + + switch (cnt) { + case MB_INCOMPLETE: + eol = 1; + /* FALL THROUGH */ + case MB_INVALID: + /* The byte didn't convert, so output it as a \M-... sequence. */ + fmt = nicechar_sel(*ptr, flags & NICEFLAG_QUOTE); + newl = strlen(fmt); + cnt = 1; + /* Get mbs out of its undefined state. */ + memset(&mbs, 0, sizeof mbs); + break; + case 0: + /* Careful: converting '\0' returns 0, but a '\0' is a + * real character for us, so we should consume 1 byte. */ + cnt = 1; + /* FALL THROUGH */ + default: + if (c == L'\'' && (flags & NICEFLAG_QUOTE)) { + fmt = "\\'"; + newl = 2; + } + else if (c == L'\\' && (flags & NICEFLAG_QUOTE)) { + fmt = "\\\\"; + newl = 2; + } + else + fmt = wcs_nicechar_sel(c, &newl, NULL, flags & NICEFLAG_QUOTE); + break; + } + + umlen -= cnt; + ptr += cnt; + l += newl; + + if (stream) + zputs(fmt, stream); + if (outstr) { + /* Append to output string */ + int outlen = strlen(fmt); + if (outlen >= outleft) { + /* Reallocate to twice the length */ + int outoffset = outptr - outstr; + + outleft += outalloc; + outalloc *= 2; + outstr = zrealloc(outstr, outalloc); + outptr = outstr + outoffset; + } + memcpy(outptr, fmt, outlen); + /* Update start position */ + outptr += outlen; + /* Update available bytes */ + outleft -= outlen; + } + } + + free(ums); + if (outstrp) { + *outptr = '\0'; + /* Use more efficient storage for returned string */ + if (flags & NICEFLAG_NODUP) + *outstrp = outstr; + else { + *outstrp = (flags & NICEFLAG_HEAP) ? dupstring(outstr) : + ztrdup(outstr); + free(outstr); + } + } + + return l; +} + +/* + * Return 1 if mb_niceformat() would reformat this string, else 0. + */ + +/**/ +mod_export int +is_mb_niceformat(const char *s) +{ + int umlen, eol = 0, ret = 0; + wchar_t c; + char *ums, *ptr; + mbstate_t mbs; + + ums = ztrdup(s); + untokenize(ums); + ptr = unmetafy(ums, ¨en); + + memset(&mbs, 0, sizeof mbs); + while (umlen > 0) { + size_t cnt = eol ? MB_INVALID : mbrtowc(&c, ptr, umlen, &mbs); + + switch (cnt) { + case MB_INCOMPLETE: + eol = 1; + /* FALL THROUGH */ + case MB_INVALID: + /* The byte didn't convert, so output it as a \M-... sequence. */ + if (is_nicechar(*ptr)) { + ret = 1; + break; + } + cnt = 1; + /* Get mbs out of its undefined state. */ + memset(&mbs, 0, sizeof mbs); + break; + case 0: + /* Careful: converting '\0' returns 0, but a '\0' is a + * real character for us, so we should consume 1 byte. */ + cnt = 1; + /* FALL THROUGH */ + default: + if (is_wcs_nicechar(c)) + ret = 1; + break; + } + + if (ret) + break; + + umlen -= cnt; + ptr += cnt; + } + + free(ums); + + return ret; +} + +/* ztrdup multibyte string with nice formatting */ + +/**/ +mod_export char * +nicedup(const char *s, int heap) +{ + char *retstr; + + (void)mb_niceformat(s, NULL, &retstr, heap ? NICEFLAG_HEAP : 0); + + return retstr; +} + + +/* + * The guts of mb_metacharlenconv(). This version assumes we are + * processing a true multibyte character string without tokens, and + * takes the shift state as an argument. + */ + +/**/ +mod_export int +mb_metacharlenconv_r(const char *s, wint_t *wcp, mbstate_t *mbsp) +{ + size_t ret = MB_INVALID; + char inchar; + const char *ptr; + wchar_t wc; + + if (STOUC(*s) <= 0x7f) { + if (wcp) + *wcp = (wint_t)*s; + return 1; + } + + for (ptr = s; *ptr; ) { + if (*ptr == Meta) { + inchar = *++ptr ^ 32; + DPUTS(!*ptr, + "BUG: unexpected end of string in mb_metacharlen()\n"); + } else if (imeta(*ptr)) { + /* + * As this is metafied input, this is a token --- this + * can't be a part of the string. It might be + * something on the end of an unbracketed parameter + * reference, for example. + */ + break; + } else + inchar = *ptr; + ptr++; + ret = mbrtowc(&wc, &inchar, 1, mbsp); + + if (ret == MB_INVALID) + break; + if (ret == MB_INCOMPLETE) + continue; + if (wcp) + *wcp = wc; + return ptr - s; + } + + if (wcp) + *wcp = WEOF; + /* No valid multibyte sequence */ + memset(mbsp, 0, sizeof(*mbsp)); + if (ptr > s) { + return 1 + (*s == Meta); /* Treat as single byte character */ + } else + return 0; /* Probably shouldn't happen */ +} + +/* + * Length of metafied string s which contains the next multibyte + * character; single (possibly metafied) character if string is not null + * but character is not valid (e.g. possibly incomplete at end of string). + * Returned value is guaranteed not to reach beyond the end of the + * string (assuming correct metafication). + * + * If wcp is not NULL, the converted wide character is stored there. + * If no conversion could be done WEOF is used. + */ + +/**/ +mod_export int +mb_metacharlenconv(const char *s, wint_t *wcp) +{ + if (!isset(MULTIBYTE) || STOUC(*s) <= 0x7f) { + /* treat as single byte, possibly metafied */ + if (wcp) + *wcp = (wint_t)(*s == Meta ? s[1] ^ 32 : *s); + return 1 + (*s == Meta); + } + /* + * We have to handle tokens here, since we may be looking + * through a tokenized input. Obviously this isn't + * a valid multibyte character, so just return WEOF + * and let the caller handle it as a single character. + * + * TODO: I've a sneaking suspicion we could do more here + * to prevent the caller always needing to handle invalid + * characters specially, but sometimes it may need to know. + */ + if (itok(*s)) { + if (wcp) + *wcp = WEOF; + return 1; + } + + return mb_metacharlenconv_r(s, wcp, &mb_shiftstate); +} + +/* + * Total number of multibyte characters in metafied string s. + * Same answer as iterating mb_metacharlen() and counting calls + * until end of string. + * + * If width is 1, return total character width rather than number. + * If width is greater than 1, return 1 if character has non-zero width, + * else 0. + * + * Ends if either *ptr is '\0', the normal case (eptr may be NULL for + * this), or ptr is eptr (i.e. *eptr is where the null would be if null + * terminated) for strings not delimited by nulls --- note these are + * still metafied. + */ + +/**/ +mod_export int +mb_metastrlenend(char *ptr, int width, char *eptr) +{ + char inchar, *laststart; + size_t ret; + wchar_t wc; + int num, num_in_char, complete; + + if (!isset(MULTIBYTE) || MB_CUR_MAX == 1) + return eptr ? (int)(eptr - ptr) : ztrlen(ptr); + + laststart = ptr; + ret = MB_INVALID; + num = num_in_char = 0; + complete = 1; + + memset(&mb_shiftstate, 0, sizeof(mb_shiftstate)); + while (*ptr && !(eptr && ptr >= eptr)) { + if (*ptr == Meta) + inchar = *++ptr ^ 32; + else + inchar = *ptr; + ptr++; + + if (complete && STOUC(inchar) <= STOUC(0x7f)) { + /* + * We rely on 7-bit US-ASCII as a subset, so skip + * multibyte handling if we have such a character. + */ + num++; + laststart = ptr; + num_in_char = 0; + continue; + } + + ret = mbrtowc(&wc, &inchar, 1, &mb_shiftstate); + + if (ret == MB_INCOMPLETE) { + /* + * "num_in_char" is only used for incomplete characters. + * The assumption is that we will output all trailing octets + * that form part of an incomplete character as a single + * character (of single width) if we don't get a complete + * character. This is purely pragmatic --- I'm not aware + * of a standard way of dealing with incomplete characters. + * + * If we do get a complete character, num_in_char + * becomes irrelevant and is set to zero + * + * This is in contrast to "num" which counts the characters + * or widths in complete characters. The two are summed, + * so we don't count characters twice. + */ + num_in_char++; + complete = 0; + } else { + if (ret == MB_INVALID) { + /* Reset, treat as single character */ + memset(&mb_shiftstate, 0, sizeof(mb_shiftstate)); + ptr = laststart + (*laststart == Meta) + 1; + num++; + } else if (width) { + /* + * Returns -1 if not a printable character. We + * turn this into 0. + */ + int wcw = WCWIDTH(wc); + if (wcw > 0) { + if (width == 1) + num += wcw; + else + num++; + } + } else + num++; + laststart = ptr; + num_in_char = 0; + complete = 1; + } + } + + /* If incomplete, treat remainder as trailing single character */ + return num + (num_in_char ? 1 : 0); +} + +/* + * The equivalent of mb_metacharlenconv_r() for + * strings that aren't metafied and hence have + * explicit lengths. + */ + +/**/ +mod_export int +mb_charlenconv_r(const char *s, int slen, wint_t *wcp, mbstate_t *mbsp) +{ + size_t ret = MB_INVALID; + char inchar; + const char *ptr; + wchar_t wc; + + if (slen && STOUC(*s) <= 0x7f) { + if (wcp) + *wcp = (wint_t)*s; + return 1; + } + + for (ptr = s; slen; ) { + inchar = *ptr; + ptr++; + slen--; + ret = mbrtowc(&wc, &inchar, 1, mbsp); + + if (ret == MB_INVALID) + break; + if (ret == MB_INCOMPLETE) + continue; + if (wcp) + *wcp = wc; + return ptr - s; + } + + if (wcp) + *wcp = WEOF; + /* No valid multibyte sequence */ + memset(mbsp, 0, sizeof(*mbsp)); + if (ptr > s) { + return 1; /* Treat as single byte character */ + } else + return 0; /* Probably shouldn't happen */ +} + +/* + * The equivalent of mb_metacharlenconv() for + * strings that aren't metafied and hence have + * explicit lengths; + */ + +/**/ +mod_export int +mb_charlenconv(const char *s, int slen, wint_t *wcp) +{ + if (!isset(MULTIBYTE) || STOUC(*s) <= 0x7f) { + if (wcp) + *wcp = (wint_t)*s; + return 1; + } + + return mb_charlenconv_r(s, slen, wcp, &mb_shiftstate); +} + +/**/ +#else + +/* Simple replacement for mb_metacharlenconv */ + +/**/ +mod_export int +metacharlenconv(const char *x, int *c) +{ + /* + * Here we don't use STOUC() on the chars since they + * may be compared against other chars and this will fail + * if chars are signed and the high bit is set. + */ + if (*x == Meta) { + if (c) + *c = x[1] ^ 32; + return 2; + } + if (c) + *c = (char)*x; + return 1; +} + +/* Simple replacement for mb_charlenconv */ + +/**/ +mod_export int +charlenconv(const char *x, int len, int *c) +{ + if (!len) { + if (c) + *c = '\0'; + return 0; + } + + if (c) + *c = (char)*x; + return 1; +} + +/**/ +#endif /* MULTIBYTE_SUPPORT */ + +/* + * Expand tabs to given width, with given starting position on line. + * len is length of unmetafied string in bytes. + * Output to fout. + * Return the end position on the line, i.e. if this is 0 modulo width + * the next character is aligned with a tab stop. + * + * If all is set, all tabs are expanded, else only leading tabs. + */ + +/**/ +mod_export int +zexpandtabs(const char *s, int len, int width, int startpos, FILE *fout, + int all) +{ + int at_start = 1; + +#ifdef MULTIBYTE_SUPPORT + mbstate_t mbs; + size_t ret; + wchar_t wc; + + memset(&mbs, 0, sizeof(mbs)); +#endif + + while (len) { + if (*s == '\t') { + if (all || at_start) { + s++; + len--; + if (width <= 0 || !(startpos % width)) { + /* always output at least one space */ + fputc(' ', fout); + startpos++; + } + if (width <= 0) + continue; /* paranoia */ + while (startpos % width) { + fputc(' ', fout); + startpos++; + } + } else { + /* + * Leave tab alone. + * Guess width to apply... we might get this wrong. + * This is only needed if there's a following string + * that needs tabs expanding, which is unusual. + */ + startpos += width - startpos % width; + s++; + len--; + fputc('\t', fout); + } + continue; + } else if (*s == '\n' || *s == '\r') { + fputc(*s, fout); + s++; + len--; + startpos = 0; + at_start = 1; + continue; + } + + at_start = 0; +#ifdef MULTIBYTE_SUPPORT + if (isset(MULTIBYTE)) { + const char *sstart = s; + ret = mbrtowc(&wc, s, len, &mbs); + if (ret == MB_INVALID) { + /* Assume single character per character */ + memset(&mbs, 0, sizeof(mbs)); + s++; + len--; + } else if (ret == MB_INCOMPLETE) { + /* incomplete at end --- assume likewise, best we've got */ + s++; + len--; + } else { + s += ret; + len -= (int)ret; + } + if (ret == MB_INVALID || ret == MB_INCOMPLETE) { + startpos++; + } else { + int wcw = WCWIDTH(wc); + if (wcw > 0) /* paranoia */ + startpos += wcw; + } + fwrite(sstart, s - sstart, 1, fout); + + continue; + } +#endif /* MULTIBYTE_SUPPORT */ + fputc(*s, fout); + s++; + len--; + startpos++; + } + + return startpos; +} + +/* check for special characters in the string */ + +/**/ +mod_export int +hasspecial(char const *s) +{ + for (; *s; s++) { + if (ispecial(*s == Meta ? *++s ^ 32 : *s)) + return 1; + } + return 0; +} + + +static char * +addunprintable(char *v, const char *u, const char *uend) +{ + for (; u < uend; u++) { + /* + * Just do this byte by byte; there's no great + * advantage in being clever with multibyte + * characters if we don't think they're printable. + */ + int c; + if (*u == Meta) + c = STOUC(*++u ^ 32); + else + c = STOUC(*u); + switch (c) { + case '\0': + *v++ = '\\'; + *v++ = '0'; + if ('0' <= u[1] && u[1] <= '7') { + *v++ = '0'; + *v++ = '0'; + } + break; + + case '\007': *v++ = '\\'; *v++ = 'a'; break; + case '\b': *v++ = '\\'; *v++ = 'b'; break; + case '\f': *v++ = '\\'; *v++ = 'f'; break; + case '\n': *v++ = '\\'; *v++ = 'n'; break; + case '\r': *v++ = '\\'; *v++ = 'r'; break; + case '\t': *v++ = '\\'; *v++ = 't'; break; + case '\v': *v++ = '\\'; *v++ = 'v'; break; + + default: + *v++ = '\\'; + *v++ = '0' + ((c >> 6) & 7); + *v++ = '0' + ((c >> 3) & 7); + *v++ = '0' + (c & 7); + break; + } + } + + return v; +} + +/* + * Quote the string s and return the result as a string from the heap. + * + * The last argument is a QT_ value defined in zsh.h other than QT_NONE. + * + * Most quote styles other than backslash assume the quotes are to + * be added outside quotestring(). QT_SINGLE_OPTIONAL is different: + * the single quotes are only added where necessary, so the + * whole expression is handled here. + * + * The string may be metafied and contain tokens. + */ + +/**/ +mod_export char * +quotestring(const char *s, int instring) +{ + const char *u; + char *v; + int alloclen; + char *buf; + int shownull = 0; + /* + * quotesub is used with QT_SINGLE_OPTIONAL. + * quotesub = 0: mechanism not active + * quotesub = 1: mechanism pending, no "'" yet; + * needs adding at quotestart. + * quotesub = 2: mechanism active, added opening "'"; need + * closing "'". + */ + int quotesub = 0, slen; + char *quotestart; + convchar_t cc; + const char *uend; + + slen = strlen(s); + switch (instring) + { + case QT_BACKSLASH_SHOWNULL: + shownull = 1; + instring = QT_BACKSLASH; + /*FALLTHROUGH*/ + case QT_BACKSLASH: + /* + * With QT_BACKSLASH we may need to use $'\300' stuff. + * Keep memory usage within limits by allocating temporary + * storage and using heap for correct size at end. + */ + alloclen = slen * 7 + 1; + break; + + case QT_BACKSLASH_PATTERN: + alloclen = slen * 2 + 1; + break; + + case QT_SINGLE_OPTIONAL: + /* + * Here, we may need to add single quotes. + * Always show empty strings. + */ + alloclen = slen * 4 + 3; + quotesub = shownull = 1; + break; + + default: + alloclen = slen * 4 + 1; + break; + } + if (!*s && shownull) + alloclen += 2; /* for '' */ + + quotestart = v = buf = zshcalloc(alloclen); + + DPUTS(instring < QT_BACKSLASH || instring == QT_BACKTICK || + instring > QT_BACKSLASH_PATTERN, + "BUG: bad quote type in quotestring"); + u = s; + if (instring == QT_DOLLARS) { + /* + * The only way to get Nularg here is when + * it is placeholding for the empty string? + */ + if (inull(*u)) + u++; + /* + * As we test for printability here we need to be able + * to look for multibyte characters. + */ + MB_METACHARINIT(); + while (*u) { + uend = u + MB_METACHARLENCONV(u, &cc); + + if ( +#ifdef MULTIBYTE_SUPPORT + cc != WEOF && +#endif + WC_ISPRINT(cc)) { + switch (cc) { + case ZWC('\\'): + case ZWC('\''): + *v++ = '\\'; + break; + + default: + if (isset(BANGHIST) && cc == (wchar_t)bangchar) + *v++ = '\\'; + break; + } + while (u < uend) + *v++ = *u++; + } else { + /* Not printable */ + v = addunprintable(v, u, uend); + u = uend; + } + } + } else if (instring == QT_BACKSLASH_PATTERN) { + while (*u) { + if (ipattern(*u)) + *v++ = '\\'; + *v++ = *u++; + } + } else { + if (shownull) { + /* We can't show an empty string with just backslash quoting. */ + if (!*u) { + *v++ = '\''; + *v++ = '\''; + } + } + /* + * Here there are syntactic special characters, so + * we start by going through bytewise. + */ + while (*u) { + int dobackslash = 0; + if (*u == Tick || *u == Qtick) { + char c = *u++; + + *v++ = c; + while (*u && *u != c) + *v++ = *u++; + *v++ = c; + if (*u) + u++; + continue; + } else if ((*u == Qstring || *u == '$') && u[1] == '\'' && + instring == QT_DOUBLE) { + /* + * We don't need to quote $'...' inside a double-quoted + * string. This is largely cosmetic; it looks neater + * if we don't but it doesn't do any harm since the + * \ is stripped. + */ + *v++ = *u++; + } else if ((*u == String || *u == Qstring) && + (u[1] == Inpar || u[1] == Inbrack || u[1] == Inbrace)) { + char c = (u[1] == Inpar ? Outpar : (u[1] == Inbrace ? + Outbrace : Outbrack)); + char beg = *u; + int level = 0; + + *v++ = *u++; + *v++ = *u++; + while (*u && (*u != c || level)) { + if (*u == beg) + level++; + else if (*u == c) + level--; + *v++ = *u++; + } + if (*u) + *v++ = *u++; + continue; + } + else if (ispecial(*u) && + ((*u != '=' && *u != '~') || + u == s || + (isset(MAGICEQUALSUBST) && + (u[-1] == '=' || u[-1] == ':')) || + (*u == '~' && isset(EXTENDEDGLOB))) && + (instring == QT_BACKSLASH || + instring == QT_SINGLE_OPTIONAL || + (isset(BANGHIST) && *u == (char)bangchar && + instring != QT_SINGLE) || + (instring == QT_DOUBLE && + (*u == '$' || *u == '`' || *u == '\"' || *u == '\\')) || + (instring == QT_SINGLE && *u == '\''))) { + if (instring == QT_SINGLE_OPTIONAL) { + if (quotesub == 1) { + /* + * We haven't yet had to quote at the start. + */ + if (*u == '\'') { + /* + * We don't need to. + */ + *v++ = '\\'; + } else { + /* + * It's now time to add quotes. + */ + if (v > quotestart) + { + char *addq; + + for (addq = v; addq > quotestart; addq--) + *addq = addq[-1]; + } + *quotestart = '\''; + v++; + quotesub = 2; + } + *v++ = *u++; + /* + * Next place to start quotes is here. + */ + quotestart = v; + } else if (*u == '\'') { + if (unset(RCQUOTES)) { + *v++ = '\''; + *v++ = '\\'; + *v++ = '\''; + /* Don't restart quotes unless we need them */ + quotesub = 1; + quotestart = v; + } else { + /* simplest just to use '' always */ + *v++ = '\''; + *v++ = '\''; + } + /* dealt with */ + u++; + } else { + /* else already quoting, just add */ + *v++ = *u++; + } + continue; + } else if (*u == '\n' || + (instring == QT_SINGLE && *u == '\'')) { + if (*u == '\n') { + *v++ = '$'; + *v++ = '\''; + *v++ = '\\'; + *v++ = 'n'; + *v++ = '\''; + } else if (unset(RCQUOTES)) { + *v++ = '\''; + if (*u == '\'') + *v++ = '\\'; + *v++ = *u; + *v++ = '\''; + } else + *v++ = '\'', *v++ = '\''; + u++; + continue; + } else { + /* + * We'll need a backslash, but don't add it + * yet since if the character isn't printable + * we'll have to upgrade it to $'...'. + */ + dobackslash = 1; + } + } + + if (itok(*u) || instring != QT_BACKSLASH) { + /* Needs to be passed straight through. */ + if (dobackslash) + *v++ = '\\'; + if (*u == Inparmath) { + /* + * Already syntactically quoted: don't + * add more. + */ + int inmath = 1; + *v++ = *u++; + for (;;) { + char uc = *u; + *v++ = *u++; + if (uc == '\0') + break; + else if (uc == Outparmath && !--inmath) + break; + else if (uc == Inparmath) + ++inmath; + } + } else + *v++ = *u++; + continue; + } + + /* + * Now check if the output is unprintable in the + * current character set. + */ + uend = u + MB_METACHARLENCONV(u, &cc); + if ( +#ifdef MULTIBYTE_SUPPORT + cc != WEOF && +#endif + WC_ISPRINT(cc)) { + if (dobackslash) + *v++ = '\\'; + while (u < uend) { + if (*u == Meta) + *v++ = *u++; + *v++ = *u++; + } + } else { + /* Not printable */ + *v++ = '$'; + *v++ = '\''; + v = addunprintable(v, u, uend); + *v++ = '\''; + u = uend; + } + } + } + if (quotesub == 2) + *v++ = '\''; + *v = '\0'; + + v = dupstring(buf); + zfree(buf, alloclen); + return v; +} + +/* + * Unmetafy and output a string, quoted if it contains special + * characters. + * + * If stream is NULL, return the same output with any allocation on the + * heap. + */ + +/**/ +mod_export char * +quotedzputs(char const *s, FILE *stream) +{ + int inquote = 0, c; + char *outstr, *ptr; + + /* check for empty string */ + if(!*s) { + if (!stream) + return dupstring("''"); + fputs("''", stream); + return NULL; + } + +#ifdef MULTIBYTE_SUPPORT + if (is_mb_niceformat(s)) { + if (stream) { + fputs("$'", stream); + mb_niceformat(s, stream, NULL, NICEFLAG_QUOTE); + fputc('\'', stream); + return NULL; + } else { + char *substr; + mb_niceformat(s, NULL, &substr, NICEFLAG_QUOTE|NICEFLAG_NODUP); + outstr = (char *)zhalloc(4 + strlen(substr)); + sprintf(outstr, "$'%s'", substr); + free(substr); + return outstr; + } + } +#endif /* MULTIBYTE_SUPPORT */ + + if (!hasspecial(s)) { + if (stream) { + zputs(s, stream); + return NULL; + } else { + return dupstring(s); + } + } + + if (!stream) { + const char *cptr; + int l = strlen(s) + 2; + for (cptr = s; *cptr; cptr++) { + if (*cptr == Meta) + cptr++; + else if (*cptr == '\'') + l += isset(RCQUOTES) ? 1 : 3; + } + ptr = outstr = zhalloc(l + 1); + } else { + ptr = outstr = NULL; + } + if (isset(RCQUOTES)) { + /* use rc-style quotes-within-quotes for the whole string */ + if (stream) { + if (fputc('\'', stream) < 0) + return NULL; + } else + *ptr++ = '\''; + while(*s) { + if (*s == Dash) + c = '-'; + else if (*s == Meta) + c = *++s ^ 32; + else + c = *s; + s++; + if (c == '\'') { + if (stream) { + if (fputc('\'', stream) < 0) + return NULL; + } else + *ptr++ = '\''; + } else if (c == '\n' && isset(CSHJUNKIEQUOTES)) { + if (stream) { + if (fputc('\\', stream) < 0) + return NULL; + } else + *ptr++ = '\\'; + } + if (stream) { + if (fputc(c, stream) < 0) + return NULL; + } else { + if (imeta(c)) { + *ptr++ = Meta; + *ptr++ = c ^ 32; + } else + *ptr++ = c; + } + } + if (stream) { + if (fputc('\'', stream) < 0) + return NULL; + } else + *ptr++ = '\''; + } else { + /* use Bourne-style quoting, avoiding empty quoted strings */ + while (*s) { + if (*s == Dash) + c = '-'; + else if (*s == Meta) + c = *++s ^ 32; + else + c = *s; + s++; + if (c == '\'') { + if (inquote) { + if (stream) { + if (putc('\'', stream) < 0) + return NULL; + } else + *ptr++ = '\''; + inquote=0; + } + if (stream) { + if (fputs("\\'", stream) < 0) + return NULL; + } else { + *ptr++ = '\\'; + *ptr++ = '\''; + } + } else { + if (!inquote) { + if (stream) { + if (fputc('\'', stream) < 0) + return NULL; + } else + *ptr++ = '\''; + inquote=1; + } + if (c == '\n' && isset(CSHJUNKIEQUOTES)) { + if (stream) { + if (fputc('\\', stream) < 0) + return NULL; + } else + *ptr++ = '\\'; + } + if (stream) { + if (fputc(c, stream) < 0) + return NULL; + } else { + if (imeta(c)) { + *ptr++ = Meta; + *ptr++ = c ^ 32; + } else + *ptr++ = c; + } + } + } + if (inquote) { + if (stream) { + if (fputc('\'', stream) < 0) + return NULL; + } else + *ptr++ = '\''; + } + } + if (!stream) + *ptr++ = '\0'; + + return outstr; +} + +/* Double-quote a metafied string. */ + +/**/ +mod_export char * +dquotedztrdup(char const *s) +{ + int len = strlen(s) * 4 + 2; + char *buf = zalloc(len); + char *p = buf, *ret; + + if(isset(CSHJUNKIEQUOTES)) { + int inquote = 0; + + while(*s) { + int c = *s++; + + if (c == Meta) + c = *s++ ^ 32; + switch(c) { + case '"': + case '$': + case '`': + if(inquote) { + *p++ = '"'; + inquote = 0; + } + *p++ = '\\'; + *p++ = c; + break; + default: + if(!inquote) { + *p++ = '"'; + inquote = 1; + } + if(c == '\n') + *p++ = '\\'; + *p++ = c; + break; + } + } + if (inquote) + *p++ = '"'; + } else { + int pending = 0; + + *p++ = '"'; + while(*s) { + int c = *s++; + + if (c == Meta) + c = *s++ ^ 32; + switch(c) { + case '\\': + if(pending) + *p++ = '\\'; + *p++ = '\\'; + pending = 1; + break; + case '"': + case '$': + case '`': + if(pending) + *p++ = '\\'; + *p++ = '\\'; + /* FALL THROUGH */ + default: + *p++ = c; + pending = 0; + break; + } + } + if(pending) + *p++ = '\\'; + *p++ = '"'; + } + ret = metafy(buf, p - buf, META_DUP); + zfree(buf, len); + return ret; +} + +/* Unmetafy and output a string, double quoting it in its entirety. */ + +#if 0 /**/ +int +dquotedzputs(char const *s, FILE *stream) +{ + char *d = dquotedztrdup(s); + int ret = zputs(d, stream); + + zsfree(d); + return ret; +} +#endif + +# if defined(HAVE_NL_LANGINFO) && defined(CODESET) && !defined(__STDC_ISO_10646__) +/* Convert a character from UCS4 encoding to UTF-8 */ + +static size_t +ucs4toutf8(char *dest, unsigned int wval) +{ + size_t len; + + if (wval < 0x80) + len = 1; + else if (wval < 0x800) + len = 2; + else if (wval < 0x10000) + len = 3; + else if (wval < 0x200000) + len = 4; + else if (wval < 0x4000000) + len = 5; + else + len = 6; + + switch (len) { /* falls through except to the last case */ + case 6: dest[5] = (wval & 0x3f) | 0x80; wval >>= 6; + case 5: dest[4] = (wval & 0x3f) | 0x80; wval >>= 6; + case 4: dest[3] = (wval & 0x3f) | 0x80; wval >>= 6; + case 3: dest[2] = (wval & 0x3f) | 0x80; wval >>= 6; + case 2: dest[1] = (wval & 0x3f) | 0x80; wval >>= 6; + *dest = wval | ((0xfc << (6 - len)) & 0xfc); + break; + case 1: *dest = wval; + } + + return len; +} +#endif + + +/* + * The following only occurs once or twice in the code, but in different + * places depending how character set conversion is implemented. + */ +#define CHARSET_FAILED() \ + if (how & GETKEY_DOLLAR_QUOTE) { \ + while ((*tdest++ = *++s)) { \ + if (how & GETKEY_UPDATE_OFFSET) { \ + if (s - sstart > *misc) \ + (*misc)++; \ + } \ + if (*s == Snull) { \ + *len = (s - sstart) + 1; \ + *tdest = '\0'; \ + return buf; \ + } \ + } \ + *len = tdest - buf; \ + return buf; \ + } \ + *t = '\0'; \ + *len = t - buf; \ + return buf + +/* + * Decode a key string, turning it into the literal characters. + * The value returned is a newly allocated string from the heap. + * + * The length is returned in *len. This is usually the length of + * the final unmetafied string. The exception is the case of + * a complete GETKEY_DOLLAR_QUOTE conversion where *len is the + * length of the input string which has been used (up to and including + * the terminating single quote); as the final string is metafied and + * NULL-terminated its length is not required. If both GETKEY_DOLLAR_QUOTE + * and GETKEY_UPDATE_OFFSET are present in "how", the string is not + * expected to be terminated (this is used in completion to parse + * a partial $'...'-quoted string) and the length passed back is + * that of the converted string. Note in both cases that this is a length + * in bytes (i.e. the same as given by a raw pointer difference), not + * characters, which may occupy multiple bytes. + * + * how is a set of bits from the GETKEY_ values defined in zsh.h; + * not all combinations of bits are useful. Callers will typically + * use one of the GETKEYS_ values which define sets of bits. + * Note, for example that: + * - GETKEY_SINGLE_CHAR must not be combined with GETKEY_DOLLAR_QUOTE. + * - GETKEY_UPDATE_OFFSET is only allowed if GETKEY_DOLLAR_QUOTE is + * also present. + * + * *misc is used for various purposes: + * - If GETKEY_BACKSLASH_MINUS is set, it indicates the presence + * of \- in the input. + * - If GETKEY_BACKSLASH_C is set, it indicates the presence + * of \c in the input. + * - If GETKEY_UPDATE_OFFSET is set, it is set on input to some + * mystical completion offset and is updated to a new offset based + * on the converted characters. All Hail the Completion System + * [makes the mystic completion system runic sign in the air]. + * + * The return value is unmetafied unless GETKEY_DOLLAR_QUOTE is + * in use. + */ + +/**/ +mod_export char * +getkeystring(char *s, int *len, int how, int *misc) +{ + char *buf, tmp[1]; + char *t, *tdest = NULL, *u = NULL, *sstart = s, *tbuf = NULL; + char svchar = '\0'; + int meta = 0, control = 0, ignoring = 0; + int i; +#if defined(HAVE_WCHAR_H) && defined(HAVE_WCTOMB) && defined(__STDC_ISO_10646__) + wint_t wval; + int count; +#else + unsigned int wval; +# if defined(HAVE_NL_LANGINFO) && defined(CODESET) +# if defined(HAVE_ICONV) + iconv_t cd; + char inbuf[4]; + size_t inbytes, outbytes; +# endif + size_t count; +# endif +#endif + + DPUTS((how & GETKEY_UPDATE_OFFSET) && + (how & ~(GETKEYS_DOLLARS_QUOTE|GETKEY_UPDATE_OFFSET)), + "BUG: offset updating in getkeystring only supported with $'."); + DPUTS((how & (GETKEY_DOLLAR_QUOTE|GETKEY_SINGLE_CHAR)) == + (GETKEY_DOLLAR_QUOTE|GETKEY_SINGLE_CHAR), + "BUG: incompatible options in getkeystring"); + + if (how & GETKEY_SINGLE_CHAR) + t = buf = tmp; + else { + /* Length including terminating NULL */ + int maxlen = 1; + /* + * We're not necessarily guaranteed the output string will + * be no longer than the input with \u and \U when output + * characters need to be metafied. As this is the only + * case where the string can get longer (?I think), + * include it in the allocation length here but don't + * bother taking account of other factors. + */ + for (t = s; *t; t++) { + if (*t == '\\') { + if (!t[1]) { + maxlen++; + break; + } + if (t[1] == 'u' || t[1] == 'U') + maxlen += MB_CUR_MAX * 2; + else + maxlen += 2; + /* skip the backslash and the following character */ + t++; + } else + maxlen++; + } + if (how & GETKEY_DOLLAR_QUOTE) { + /* + * We're going to unmetafy into a new string, but + * to get a proper metafied input we're going to metafy + * into an intermediate buffer. This is necessary if we have + * \u and \U's with multiple metafied bytes. We can't + * simply remetafy the entire string because there may + * be tokens (indeed, we know there are lexical nulls floating + * around), so we have to be aware character by character + * what we are converting. + * + * In this case, buf is the final buffer (as usual), + * but t points into a temporary buffer that just has + * to be long enough to hold the result of one escape + * code transformation. We count this is a full multibyte + * character (MB_CUR_MAX) with every character metafied + * (*2) plus a little bit of fuzz (for e.g. the odd backslash). + */ + buf = tdest = zhalloc(maxlen); + t = tbuf = zhalloc(MB_CUR_MAX * 3 + 1); + } else { + t = buf = zhalloc(maxlen); + } + } + for (; *s; s++) { + if (*s == '\\' && s[1]) { + int miscadded; + if ((how & GETKEY_UPDATE_OFFSET) && s - sstart < *misc) { + (*misc)--; + miscadded = 1; + } else + miscadded = 0; + switch (*++s) { + case 'a': +#ifdef __STDC__ + *t++ = '\a'; +#else + *t++ = '\07'; +#endif + break; + case 'n': + *t++ = '\n'; + break; + case 'b': + *t++ = '\b'; + break; + case 't': + *t++ = '\t'; + break; + case 'v': + *t++ = '\v'; + break; + case 'f': + *t++ = '\f'; + break; + case 'r': + *t++ = '\r'; + break; + case 'E': + if (!(how & GETKEY_EMACS)) { + *t++ = '\\', s--; + if (miscadded) + (*misc)++; + continue; + } + /* FALL THROUGH */ + case 'e': + *t++ = '\033'; + break; + case 'M': + /* HERE: GETKEY_UPDATE_OFFSET */ + if (how & GETKEY_EMACS) { + if (s[1] == '-') + s++; + meta = 1 + control; /* preserve the order of ^ and meta */ + } else { + if (miscadded) + (*misc)++; + *t++ = '\\', s--; + } + continue; + case 'C': + /* HERE: GETKEY_UPDATE_OFFSET */ + if (how & GETKEY_EMACS) { + if (s[1] == '-') + s++; + control = 1; + } else { + if (miscadded) + (*misc)++; + *t++ = '\\', s--; + } + continue; + case Meta: + if (miscadded) + (*misc)++; + *t++ = '\\', s--; + break; + case '-': + if (how & GETKEY_BACKSLASH_MINUS) { + *misc = 1; + break; + } + goto def; + case 'c': + if (how & GETKEY_BACKSLASH_C) { + *misc = 1; + *t = '\0'; + *len = t - buf; + return buf; + } + goto def; + case 'U': + if ((how & GETKEY_UPDATE_OFFSET) && s - sstart < *misc) + (*misc) -= 4; + /* FALLTHROUGH */ + case 'u': + if ((how & GETKEY_UPDATE_OFFSET) && s - sstart < *misc) { + (*misc) -= 6; /* HERE don't really believe this */ + /* + * We've now adjusted the offset for all the input + * characters, so we need to add for each + * byte of output below. + */ + } + wval = 0; + for (i=(*s == 'u' ? 4 : 8); i>0; i--) { + if (*++s && idigit(*s)) + wval = wval * 16 + (*s - '0'); + else if (*s && ((*s >= 'a' && *s <= 'f') || + (*s >= 'A' && *s <= 'F'))) + wval = wval * 16 + (*s & 0x1f) + 9; + else { + s--; + break; + } + } + if (how & GETKEY_SINGLE_CHAR) { + *misc = wval; + return s+1; + } +#if defined(HAVE_WCHAR_H) && defined(HAVE_WCTOMB) && defined(__STDC_ISO_10646__) + count = wctomb(t, (wchar_t)wval); + if (count == -1) { + zerr("character not in range"); + CHARSET_FAILED(); + } + if ((how & GETKEY_UPDATE_OFFSET) && s - sstart < *misc) + (*misc) += count; + t += count; +# else +# if defined(HAVE_NL_LANGINFO) && defined(CODESET) + if (!strcmp(nl_langinfo(CODESET), "UTF-8")) { + count = ucs4toutf8(t, wval); + t += count; + if ((how & GETKEY_UPDATE_OFFSET) && s - sstart < *misc) + (*misc) += count; + } else { +# ifdef HAVE_ICONV + ICONV_CONST char *inptr = inbuf; + const char *codesetstr = nl_langinfo(CODESET); + inbytes = 4; + outbytes = 6; + /* store value in big endian form */ + for (i=3;i>=0;i--) { + inbuf[i] = wval & 0xff; + wval >>= 8; + } + + /* + * If the code set isn't handled, we'd better + * assume it's US-ASCII rather than just failing + * hopelessly. Solaris has a weird habit of + * returning 646. This is handled by the + * native iconv(), but not by GNU iconv; what's + * more, some versions of the native iconv don't + * handle standard names like ASCII. + * + * This should only be a problem if there's a + * mismatch between the NLS and the iconv in use, + * which probably only means if libiconv is in use. + * We checked at configure time if our libraries + * pulled in _libiconv_version, which should be + * a good test. + * + * It shouldn't ever be NULL, but while we're + * being paranoid... + */ +#ifdef ICONV_FROM_LIBICONV + if (!codesetstr || !*codesetstr) + codesetstr = "US-ASCII"; +#endif + cd = iconv_open(codesetstr, "UCS-4BE"); +#ifdef ICONV_FROM_LIBICONV + if (cd == (iconv_t)-1 && !strcmp(codesetstr, "646")) { + codesetstr = "US-ASCII"; + cd = iconv_open(codesetstr, "UCS-4BE"); + } +#endif + if (cd == (iconv_t)-1) { + zerr("cannot do charset conversion (iconv failed)"); + CHARSET_FAILED(); + } + count = iconv(cd, &inptr, &inbytes, &t, &outbytes); + iconv_close(cd); + if (count == (size_t)-1) { + zerr("character not in range"); + CHARSET_FAILED(); + } + if ((how & GETKEY_UPDATE_OFFSET) && s - sstart < *misc) + (*misc) += count; +# else + zerr("cannot do charset conversion (iconv not available)"); + CHARSET_FAILED(); +# endif + } +# else + zerr("cannot do charset conversion (NLS not supported)"); + CHARSET_FAILED(); +# endif +# endif + if (how & GETKEY_DOLLAR_QUOTE) { + char *t2; + for (t2 = tbuf; t2 < t; t2++) { + if (imeta(*t2)) { + *tdest++ = Meta; + *tdest++ = *t2 ^ 32; + } else + *tdest++ = *t2; + } + /* reset temporary buffer after handling */ + t = tbuf; + } + continue; + case '\'': + case '\\': + if (how & GETKEY_DOLLAR_QUOTE) { + /* + * Usually \' and \\ will have the initial + * \ turned into a Bnull, however that's not + * necessarily the case when called from + * completion. + */ + *t++ = *s; + break; + } + /* FALLTHROUGH */ + default: + def: + /* HERE: GETKEY_UPDATE_OFFSET? */ + if ((idigit(*s) && *s < '8') || *s == 'x') { + if (!(how & GETKEY_OCTAL_ESC)) { + if (*s == '0') + s++; + else if (*s != 'x') { + *t++ = '\\', s--; + continue; + } + } + if (s[1] && s[2] && s[3]) { + svchar = s[3]; + s[3] = '\0'; + u = s; + } + *t++ = zstrtol(s + (*s == 'x'), &s, + (*s == 'x') ? 16 : 8); + if ((how & GETKEY_PRINTF_PERCENT) && t[-1] == '%') + *t++ = '%'; + if (svchar) { + u[3] = svchar; + svchar = '\0'; + } + s--; + } else { + if (!(how & GETKEY_EMACS) && *s != '\\') { + if (miscadded) + (*misc)++; + *t++ = '\\'; + } + *t++ = *s; + } + break; + } + } else if ((how & GETKEY_DOLLAR_QUOTE) && *s == Snull) { + /* return length to following character */ + *len = (s - sstart) + 1; + *tdest = '\0'; + return buf; + } else if (*s == '^' && !control && (how & GETKEY_CTRL) && s[1]) { + control = 1; + continue; +#ifdef MULTIBYTE_SUPPORT + } else if ((how & GETKEY_SINGLE_CHAR) && + isset(MULTIBYTE) && STOUC(*s) > 127) { + wint_t wc; + int len; + len = mb_metacharlenconv(s, &wc); + if (wc != WEOF) { + *misc = (int)wc; + return s + len; + } +#endif + + } else if (*s == Meta) + *t++ = *++s ^ 32; + else { + if (itok(*s)) { + /* + * We need to be quite careful here. We haven't + * necessarily got an input stream with all tokens + * removed, so the majority of tokens need passing + * through untouched and without Meta handling. + * However, me may need to handle tokenized + * backslashes. + */ + if (meta || control) { + /* + * Presumably we should be using meta or control + * on the character representing the token. + * + * Special case: $'\M-\\' where the token is a Bnull. + * This time we dump the Bnull since we're + * replacing the whole thing. The lexer + * doesn't know about the meta or control modifiers. + */ + if ((how & GETKEY_DOLLAR_QUOTE) && *s == Bnull) + *t++ = *++s; + else + *t++ = ztokens[*s - Pound]; + } else if (how & GETKEY_DOLLAR_QUOTE) { + /* + * We don't want to metafy this, it's a real + * token. + */ + *tdest++ = *s; + if (*s == Bnull) { + /* + * Bnull is a backslash which quotes a couple + * of special characters that always appear + * literally next. See strquote handling + * in gettokstr() in lex.c. We need + * to retain the Bnull (as above) so that quote + * handling in completion can tell where the + * backslash was. + */ + *tdest++ = *++s; + } + /* reset temporary buffer, now handled */ + t = tbuf; + continue; + } else + *t++ = *s; + } else + *t++ = *s; + } + if (meta == 2) { + t[-1] |= 0x80; + meta = 0; + } + if (control) { + if (t[-1] == '?') + t[-1] = 0x7f; + else + t[-1] &= 0x9f; + control = 0; + } + if (meta) { + t[-1] |= 0x80; + meta = 0; + } + if (how & GETKEY_DOLLAR_QUOTE) { + char *t2; + for (t2 = tbuf; t2 < t; t2++) { + /* + * In POSIX mode, an embedded NULL is discarded and + * terminates processing. It just does, that's why. + */ + if (isset(POSIXSTRINGS)) { + if (*t2 == '\0') + ignoring = 1; + if (ignoring) + break; + } + if (imeta(*t2)) { + *tdest++ = Meta; + *tdest++ = *t2 ^ 32; + } else { + *tdest++ = *t2; + } + } + /* + * Reset use of temporary buffer. + */ + t = tbuf; + } + if ((how & GETKEY_SINGLE_CHAR) && t != tmp) { + *misc = STOUC(tmp[0]); + return s + 1; + } + } + /* + * When called from completion, where we use GETKEY_UPDATE_OFFSET to + * update the index into the metafied editor line, we don't necessarily + * have the end of a $'...' quotation, else we should do. + */ + DPUTS((how & (GETKEY_DOLLAR_QUOTE|GETKEY_UPDATE_OFFSET)) == + GETKEY_DOLLAR_QUOTE, "BUG: unterminated $' substitution"); + *t = '\0'; + if (how & GETKEY_DOLLAR_QUOTE) + *tdest = '\0'; + if (how & GETKEY_SINGLE_CHAR) + *misc = 0; + else + *len = ((how & GETKEY_DOLLAR_QUOTE) ? tdest : t) - buf; + return buf; +} + +/* Return non-zero if s is a prefix of t. */ + +/**/ +mod_export int +strpfx(const char *s, const char *t) +{ + while (*s && *s == *t) + s++, t++; + return !*s; +} + +/* Return non-zero if s is a suffix of t. */ + +/**/ +mod_export int +strsfx(char *s, char *t) +{ + int ls = strlen(s), lt = strlen(t); + + if (ls <= lt) + return !strcmp(t + lt - ls, s); + return 0; +} + +/**/ +static int +upchdir(int n) +{ + char buf[PATH_MAX+1]; + char *s; + int err = -1; + + while (n > 0) { + for (s = buf; s < buf + PATH_MAX - 4 && n--; ) + *s++ = '.', *s++ = '.', *s++ = '/'; + s[-1] = '\0'; + if (chdir(buf)) + return err; + err = -2; + } + return 0; +} + +/* + * Initialize a "struct dirsav". + * The structure will be set to the directory we want to save + * the first time we change to a different directory. + */ + +/**/ +mod_export void +init_dirsav(Dirsav d) +{ + d->ino = d->dev = 0; + d->dirname = NULL; + d->dirfd = d->level = -1; +} + +/* + * Change directory, without following symlinks. Returns 0 on success, -1 + * on failure. Sets errno to ENOTDIR if any symlinks are encountered. If + * fchdir() fails, or the current directory is unreadable, we might end up + * in an unwanted directory in case of failure. + * + * path is an unmetafied but null-terminated string, as needed by system + * calls. + */ + +/**/ +mod_export int +lchdir(char const *path, struct dirsav *d, int hard) +{ + char const *pptr; + int level; + struct stat st1; + struct dirsav ds; +#ifdef HAVE_LSTAT + char buf[PATH_MAX + 1], *ptr; + int err; + struct stat st2; +#endif +#ifdef HAVE_FCHDIR + int close_dir = 0; +#endif + + if (!d) { + init_dirsav(&ds); + d = &ds; + } +#ifdef HAVE_LSTAT + if ((*path == '/' || !hard) && + (d != &ds || hard)){ +#else + if (*path == '/') { +#endif + level = -1; +#ifndef HAVE_FCHDIR + if (!d->dirname) + zgetdir(d); +#endif + } else { + level = 0; + if (!d->dev && !d->ino) { + stat(".", &st1); + d->dev = st1.st_dev; + d->ino = st1.st_ino; + } + } + +#ifdef HAVE_LSTAT + if (!hard) +#endif + { + if (d != &ds) { + for (pptr = path; *pptr; level++) { + while (*pptr && *pptr++ != '/'); + while (*pptr == '/') + pptr++; + } + d->level = level; + } + return zchdir((char *) path); + } + +#ifdef HAVE_LSTAT +#ifdef HAVE_FCHDIR + if (d->dirfd < 0) { + close_dir = 1; + if ((d->dirfd = open(".", O_RDONLY | O_NOCTTY)) < 0 && + zgetdir(d) && *d->dirname != '/') + d->dirfd = open("..", O_RDONLY | O_NOCTTY); + } +#endif + if (*path == '/') + if (chdir("/") < 0) + zwarn("failed to chdir(/): %e", errno); + for(;;) { + while(*path == '/') + path++; + if(!*path) { + if (d == &ds) + zsfree(ds.dirname); + else + d->level = level; +#ifdef HAVE_FCHDIR + if (d->dirfd >=0 && close_dir) { + close(d->dirfd); + d->dirfd = -1; + } +#endif + return 0; + } + for(pptr = path; *++pptr && *pptr != '/'; ) ; + if(pptr - path > PATH_MAX) { + err = ENAMETOOLONG; + break; + } + for(ptr = buf; path != pptr; ) + *ptr++ = *path++; + *ptr = 0; + if(lstat(buf, &st1)) { + err = errno; + break; + } + if(!S_ISDIR(st1.st_mode)) { + err = ENOTDIR; + break; + } + if(chdir(buf)) { + err = errno; + break; + } + if (level >= 0) + level++; + if(lstat(".", &st2)) { + err = errno; + break; + } + if(st1.st_dev != st2.st_dev || st1.st_ino != st2.st_ino) { + err = ENOTDIR; + break; + } + } + if (restoredir(d)) { + int restoreerr = errno; + int i; + /* + * Failed to restore the directory. + * Just be definite, cd to root and report the result. + */ + for (i = 0; i < 2; i++) { + const char *cdest; + if (i) + cdest = "/"; + else { + if (!home) + continue; + cdest = home; + } + zsfree(pwd); + pwd = ztrdup(cdest); + if (chdir(pwd) == 0) + break; + } + if (i == 2) + zerr("lost current directory, failed to cd to /: %e", errno); + else + zerr("lost current directory: %e: changed to `%s'", restoreerr, + pwd); + if (d == &ds) + zsfree(ds.dirname); +#ifdef HAVE_FCHDIR + if (d->dirfd >=0 && close_dir) { + close(d->dirfd); + d->dirfd = -1; + } +#endif + errno = err; + return -2; + } + if (d == &ds) + zsfree(ds.dirname); +#ifdef HAVE_FCHDIR + if (d->dirfd >=0 && close_dir) { + close(d->dirfd); + d->dirfd = -1; + } +#endif + errno = err; + return -1; +#endif /* HAVE_LSTAT */ +} + +/**/ +mod_export int +restoredir(struct dirsav *d) +{ + int err = 0; + struct stat sbuf; + + if (d->dirname && *d->dirname == '/') + return chdir(d->dirname); +#ifdef HAVE_FCHDIR + if (d->dirfd >= 0) { + if (!fchdir(d->dirfd)) { + if (!d->dirname) { + return 0; + } else if (chdir(d->dirname)) { + close(d->dirfd); + d->dirfd = -1; + err = -2; + } + } else { + close(d->dirfd); + d->dirfd = err = -1; + } + } else +#endif + if (d->level > 0) + err = upchdir(d->level); + else if (d->level < 0) + err = -1; + if (d->dev || d->ino) { + stat(".", &sbuf); + if (sbuf.st_ino != d->ino || sbuf.st_dev != d->dev) + err = -2; + } + return err; +} + + +/* Check whether the shell is running with privileges in effect. * + * This is the case if EITHER the euid is zero, OR (if the system * + * supports POSIX.1e (POSIX.6) capability sets) the process' * + * Effective or Inheritable capability sets are non-empty. */ + +/**/ +int +privasserted(void) +{ + if(!geteuid()) + return 1; +#ifdef HAVE_CAP_GET_PROC + { + cap_t caps = cap_get_proc(); + if(caps) { + /* POSIX doesn't define a way to test whether a capability set * + * is empty or not. Typical. I hope this is conforming... */ + cap_flag_value_t val; + cap_value_t n; + for(n = 0; !cap_get_flag(caps, n, CAP_EFFECTIVE, &val); n++) + if(val) { + cap_free(caps); + return 1; + } + } + cap_free(caps); + } +#endif /* HAVE_CAP_GET_PROC */ + return 0; +} + +/**/ +mod_export int +mode_to_octal(mode_t mode) +{ + int m = 0; + + if(mode & S_ISUID) + m |= 04000; + if(mode & S_ISGID) + m |= 02000; + if(mode & S_ISVTX) + m |= 01000; + if(mode & S_IRUSR) + m |= 00400; + if(mode & S_IWUSR) + m |= 00200; + if(mode & S_IXUSR) + m |= 00100; + if(mode & S_IRGRP) + m |= 00040; + if(mode & S_IWGRP) + m |= 00020; + if(mode & S_IXGRP) + m |= 00010; + if(mode & S_IROTH) + m |= 00004; + if(mode & S_IWOTH) + m |= 00002; + if(mode & S_IXOTH) + m |= 00001; + return m; +} + +#ifdef MAILDIR_SUPPORT +/* + * Stat a file. If it's a maildir, check all messages + * in the maildir and present the grand total as a file. + * The fields in the 'struct stat' are from the mail directory. + * The following fields are emulated: + * + * st_nlink always 1 + * st_size total number of bytes in all files + * st_blocks total number of messages + * st_atime access time of newest file in maildir + * st_mtime modify time of newest file in maildir + * st_mode S_IFDIR changed to S_IFREG + * + * This is good enough for most mail-checking applications. + */ + +/**/ +int +mailstat(char *path, struct stat *st) +{ + DIR *dd; + struct dirent *fn; + struct stat st_ret, st_tmp; + static struct stat st_ret_last; + char *dir, *file = 0; + int i; + time_t atime = 0, mtime = 0; + size_t plen = strlen(path), dlen; + + /* First see if it's a directory. */ + if ((i = stat(path, st)) != 0 || !S_ISDIR(st->st_mode)) + return i; + + st_ret = *st; + st_ret.st_nlink = 1; + st_ret.st_size = 0; + st_ret.st_blocks = 0; + st_ret.st_mode &= ~S_IFDIR; + st_ret.st_mode |= S_IFREG; + + /* See if cur/ is present */ + dir = appstr(ztrdup(path), "/cur"); + if (stat(dir, &st_tmp) || !S_ISDIR(st_tmp.st_mode)) return 0; + st_ret.st_atime = st_tmp.st_atime; + + /* See if tmp/ is present */ + dir[plen] = 0; + dir = appstr(dir, "/tmp"); + if (stat(dir, &st_tmp) || !S_ISDIR(st_tmp.st_mode)) return 0; + st_ret.st_mtime = st_tmp.st_mtime; + + /* And new/ */ + dir[plen] = 0; + dir = appstr(dir, "/new"); + if (stat(dir, &st_tmp) || !S_ISDIR(st_tmp.st_mode)) return 0; + st_ret.st_mtime = st_tmp.st_mtime; + +#if THERE_IS_EXACTLY_ONE_MAILDIR_IN_MAILPATH + { + static struct stat st_new_last; + /* Optimization - if new/ didn't change, nothing else did. */ + if (st_tmp.st_dev == st_new_last.st_dev && + st_tmp.st_ino == st_new_last.st_ino && + st_tmp.st_atime == st_new_last.st_atime && + st_tmp.st_mtime == st_new_last.st_mtime) { + *st = st_ret_last; + return 0; + } + st_new_last = st_tmp; + } +#endif + + /* Loop over new/ and cur/ */ + for (i = 0; i < 2; i++) { + dir[plen] = 0; + dir = appstr(dir, i ? "/cur" : "/new"); + if ((dd = opendir(dir)) == NULL) { + zsfree(file); + zsfree(dir); + return 0; + } + dlen = strlen(dir) + 1; /* include the "/" */ + while ((fn = readdir(dd)) != NULL) { + if (fn->d_name[0] == '.') + continue; + if (file) { + file[dlen] = 0; + file = appstr(file, fn->d_name); + } else { + file = tricat(dir, "/", fn->d_name); + } + if (stat(file, &st_tmp) != 0) + continue; + st_ret.st_size += st_tmp.st_size; + st_ret.st_blocks++; + if (st_tmp.st_atime != st_tmp.st_mtime && + st_tmp.st_atime > atime) + atime = st_tmp.st_atime; + if (st_tmp.st_mtime > mtime) + mtime = st_tmp.st_mtime; + } + closedir(dd); + } + zsfree(file); + zsfree(dir); + + if (atime) st_ret.st_atime = atime; + if (mtime) st_ret.st_mtime = mtime; + + *st = st_ret_last = st_ret; + return 0; +} +#endif diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/wcwidth9.h b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/wcwidth9.h new file mode 100644 index 00000000..448f548e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/wcwidth9.h @@ -0,0 +1,1325 @@ +#ifndef WCWIDTH9_H +#define WCWIDTH9_H + +#include +#include + +struct wcwidth9_interval { + long first; + long last; +}; + +static const struct wcwidth9_interval wcwidth9_private[] = { + {0x00e000, 0x00f8ff}, + {0x0f0000, 0x0ffffd}, + {0x100000, 0x10fffd}, +}; + +static const struct wcwidth9_interval wcwidth9_nonprint[] = { + {0x0000, 0x001f}, + {0x007f, 0x009f}, + {0x00ad, 0x00ad}, + {0x070f, 0x070f}, + {0x180b, 0x180e}, + {0x200b, 0x200f}, + {0x2028, 0x2029}, + {0x202a, 0x202e}, + {0x206a, 0x206f}, + {0xd800, 0xdfff}, + {0xfeff, 0xfeff}, + {0xfff9, 0xfffb}, + {0xfffe, 0xffff}, +}; + +static const struct wcwidth9_interval wcwidth9_combining[] = { + {0x0300, 0x036f}, + {0x0483, 0x0489}, + {0x0591, 0x05bd}, + {0x05bf, 0x05bf}, + {0x05c1, 0x05c2}, + {0x05c4, 0x05c5}, + {0x05c7, 0x05c7}, + {0x0610, 0x061a}, + {0x064b, 0x065f}, + {0x0670, 0x0670}, + {0x06d6, 0x06dc}, + {0x06df, 0x06e4}, + {0x06e7, 0x06e8}, + {0x06ea, 0x06ed}, + {0x0711, 0x0711}, + {0x0730, 0x074a}, + {0x07a6, 0x07b0}, + {0x07eb, 0x07f3}, + {0x0816, 0x0819}, + {0x081b, 0x0823}, + {0x0825, 0x0827}, + {0x0829, 0x082d}, + {0x0859, 0x085b}, + {0x08d4, 0x08e1}, + {0x08e3, 0x0903}, + {0x093a, 0x093c}, + {0x093e, 0x094f}, + {0x0951, 0x0957}, + {0x0962, 0x0963}, + {0x0981, 0x0983}, + {0x09bc, 0x09bc}, + {0x09be, 0x09c4}, + {0x09c7, 0x09c8}, + {0x09cb, 0x09cd}, + {0x09d7, 0x09d7}, + {0x09e2, 0x09e3}, + {0x0a01, 0x0a03}, + {0x0a3c, 0x0a3c}, + {0x0a3e, 0x0a42}, + {0x0a47, 0x0a48}, + {0x0a4b, 0x0a4d}, + {0x0a51, 0x0a51}, + {0x0a70, 0x0a71}, + {0x0a75, 0x0a75}, + {0x0a81, 0x0a83}, + {0x0abc, 0x0abc}, + {0x0abe, 0x0ac5}, + {0x0ac7, 0x0ac9}, + {0x0acb, 0x0acd}, + {0x0ae2, 0x0ae3}, + {0x0b01, 0x0b03}, + {0x0b3c, 0x0b3c}, + {0x0b3e, 0x0b44}, + {0x0b47, 0x0b48}, + {0x0b4b, 0x0b4d}, + {0x0b56, 0x0b57}, + {0x0b62, 0x0b63}, + {0x0b82, 0x0b82}, + {0x0bbe, 0x0bc2}, + {0x0bc6, 0x0bc8}, + {0x0bca, 0x0bcd}, + {0x0bd7, 0x0bd7}, + {0x0c00, 0x0c03}, + {0x0c3e, 0x0c44}, + {0x0c46, 0x0c48}, + {0x0c4a, 0x0c4d}, + {0x0c55, 0x0c56}, + {0x0c62, 0x0c63}, + {0x0c81, 0x0c83}, + {0x0cbc, 0x0cbc}, + {0x0cbe, 0x0cc4}, + {0x0cc6, 0x0cc8}, + {0x0cca, 0x0ccd}, + {0x0cd5, 0x0cd6}, + {0x0ce2, 0x0ce3}, + {0x0d01, 0x0d03}, + {0x0d3e, 0x0d44}, + {0x0d46, 0x0d48}, + {0x0d4a, 0x0d4d}, + {0x0d57, 0x0d57}, + {0x0d62, 0x0d63}, + {0x0d82, 0x0d83}, + {0x0dca, 0x0dca}, + {0x0dcf, 0x0dd4}, + {0x0dd6, 0x0dd6}, + {0x0dd8, 0x0ddf}, + {0x0df2, 0x0df3}, + {0x0e31, 0x0e31}, + {0x0e34, 0x0e3a}, + {0x0e47, 0x0e4e}, + {0x0eb1, 0x0eb1}, + {0x0eb4, 0x0eb9}, + {0x0ebb, 0x0ebc}, + {0x0ec8, 0x0ecd}, + {0x0f18, 0x0f19}, + {0x0f35, 0x0f35}, + {0x0f37, 0x0f37}, + {0x0f39, 0x0f39}, + {0x0f3e, 0x0f3f}, + {0x0f71, 0x0f84}, + {0x0f86, 0x0f87}, + {0x0f8d, 0x0f97}, + {0x0f99, 0x0fbc}, + {0x0fc6, 0x0fc6}, + {0x102b, 0x103e}, + {0x1056, 0x1059}, + {0x105e, 0x1060}, + {0x1062, 0x1064}, + {0x1067, 0x106d}, + {0x1071, 0x1074}, + {0x1082, 0x108d}, + {0x108f, 0x108f}, + {0x109a, 0x109d}, + {0x135d, 0x135f}, + {0x1712, 0x1714}, + {0x1732, 0x1734}, + {0x1752, 0x1753}, + {0x1772, 0x1773}, + {0x17b4, 0x17d3}, + {0x17dd, 0x17dd}, + {0x180b, 0x180d}, + {0x1885, 0x1886}, + {0x18a9, 0x18a9}, + {0x1920, 0x192b}, + {0x1930, 0x193b}, + {0x1a17, 0x1a1b}, + {0x1a55, 0x1a5e}, + {0x1a60, 0x1a7c}, + {0x1a7f, 0x1a7f}, + {0x1ab0, 0x1abe}, + {0x1b00, 0x1b04}, + {0x1b34, 0x1b44}, + {0x1b6b, 0x1b73}, + {0x1b80, 0x1b82}, + {0x1ba1, 0x1bad}, + {0x1be6, 0x1bf3}, + {0x1c24, 0x1c37}, + {0x1cd0, 0x1cd2}, + {0x1cd4, 0x1ce8}, + {0x1ced, 0x1ced}, + {0x1cf2, 0x1cf4}, + {0x1cf8, 0x1cf9}, + {0x1dc0, 0x1df5}, + {0x1dfb, 0x1dff}, + {0x20d0, 0x20f0}, + {0x2cef, 0x2cf1}, + {0x2d7f, 0x2d7f}, + {0x2de0, 0x2dff}, + {0x302a, 0x302f}, + {0x3099, 0x309a}, + {0xa66f, 0xa672}, + {0xa674, 0xa67d}, + {0xa69e, 0xa69f}, + {0xa6f0, 0xa6f1}, + {0xa802, 0xa802}, + {0xa806, 0xa806}, + {0xa80b, 0xa80b}, + {0xa823, 0xa827}, + {0xa880, 0xa881}, + {0xa8b4, 0xa8c5}, + {0xa8e0, 0xa8f1}, + {0xa926, 0xa92d}, + {0xa947, 0xa953}, + {0xa980, 0xa983}, + {0xa9b3, 0xa9c0}, + {0xa9e5, 0xa9e5}, + {0xaa29, 0xaa36}, + {0xaa43, 0xaa43}, + {0xaa4c, 0xaa4d}, + {0xaa7b, 0xaa7d}, + {0xaab0, 0xaab0}, + {0xaab2, 0xaab4}, + {0xaab7, 0xaab8}, + {0xaabe, 0xaabf}, + {0xaac1, 0xaac1}, + {0xaaeb, 0xaaef}, + {0xaaf5, 0xaaf6}, + {0xabe3, 0xabea}, + {0xabec, 0xabed}, + {0xfb1e, 0xfb1e}, + {0xfe00, 0xfe0f}, + {0xfe20, 0xfe2f}, + {0x101fd, 0x101fd}, + {0x102e0, 0x102e0}, + {0x10376, 0x1037a}, + {0x10a01, 0x10a03}, + {0x10a05, 0x10a06}, + {0x10a0c, 0x10a0f}, + {0x10a38, 0x10a3a}, + {0x10a3f, 0x10a3f}, + {0x10ae5, 0x10ae6}, + {0x11000, 0x11002}, + {0x11038, 0x11046}, + {0x1107f, 0x11082}, + {0x110b0, 0x110ba}, + {0x11100, 0x11102}, + {0x11127, 0x11134}, + {0x11173, 0x11173}, + {0x11180, 0x11182}, + {0x111b3, 0x111c0}, + {0x111ca, 0x111cc}, + {0x1122c, 0x11237}, + {0x1123e, 0x1123e}, + {0x112df, 0x112ea}, + {0x11300, 0x11303}, + {0x1133c, 0x1133c}, + {0x1133e, 0x11344}, + {0x11347, 0x11348}, + {0x1134b, 0x1134d}, + {0x11357, 0x11357}, + {0x11362, 0x11363}, + {0x11366, 0x1136c}, + {0x11370, 0x11374}, + {0x11435, 0x11446}, + {0x114b0, 0x114c3}, + {0x115af, 0x115b5}, + {0x115b8, 0x115c0}, + {0x115dc, 0x115dd}, + {0x11630, 0x11640}, + {0x116ab, 0x116b7}, + {0x1171d, 0x1172b}, + {0x11c2f, 0x11c36}, + {0x11c38, 0x11c3f}, + {0x11c92, 0x11ca7}, + {0x11ca9, 0x11cb6}, + {0x16af0, 0x16af4}, + {0x16b30, 0x16b36}, + {0x16f51, 0x16f7e}, + {0x16f8f, 0x16f92}, + {0x1bc9d, 0x1bc9e}, + {0x1d165, 0x1d169}, + {0x1d16d, 0x1d172}, + {0x1d17b, 0x1d182}, + {0x1d185, 0x1d18b}, + {0x1d1aa, 0x1d1ad}, + {0x1d242, 0x1d244}, + {0x1da00, 0x1da36}, + {0x1da3b, 0x1da6c}, + {0x1da75, 0x1da75}, + {0x1da84, 0x1da84}, + {0x1da9b, 0x1da9f}, + {0x1daa1, 0x1daaf}, + {0x1e000, 0x1e006}, + {0x1e008, 0x1e018}, + {0x1e01b, 0x1e021}, + {0x1e023, 0x1e024}, + {0x1e026, 0x1e02a}, + {0x1e8d0, 0x1e8d6}, + {0x1e944, 0x1e94a}, + {0xe0100, 0xe01ef}, +}; + +static const struct wcwidth9_interval wcwidth9_doublewidth[] = { + {0x1100, 0x115f}, + {0x231a, 0x231b}, + {0x2329, 0x232a}, + {0x23e9, 0x23ec}, + {0x23f0, 0x23f0}, + {0x23f3, 0x23f3}, + {0x25fd, 0x25fe}, + {0x2614, 0x2615}, + {0x2648, 0x2653}, + {0x267f, 0x267f}, + {0x2693, 0x2693}, + {0x26a1, 0x26a1}, + {0x26aa, 0x26ab}, + {0x26bd, 0x26be}, + {0x26c4, 0x26c5}, + {0x26ce, 0x26ce}, + {0x26d4, 0x26d4}, + {0x26ea, 0x26ea}, + {0x26f2, 0x26f3}, + {0x26f5, 0x26f5}, + {0x26fa, 0x26fa}, + {0x26fd, 0x26fd}, + {0x2705, 0x2705}, + {0x270a, 0x270b}, + {0x2728, 0x2728}, + {0x274c, 0x274c}, + {0x274e, 0x274e}, + {0x2753, 0x2755}, + {0x2757, 0x2757}, + {0x2795, 0x2797}, + {0x27b0, 0x27b0}, + {0x27bf, 0x27bf}, + {0x2b1b, 0x2b1c}, + {0x2b50, 0x2b50}, + {0x2b55, 0x2b55}, + {0x2e80, 0x2e99}, + {0x2e9b, 0x2ef3}, + {0x2f00, 0x2fd5}, + {0x2ff0, 0x2ffb}, + {0x3000, 0x303e}, + {0x3041, 0x3096}, + {0x3099, 0x30ff}, + {0x3105, 0x312d}, + {0x3131, 0x318e}, + {0x3190, 0x31ba}, + {0x31c0, 0x31e3}, + {0x31f0, 0x321e}, + {0x3220, 0x3247}, + {0x3250, 0x32fe}, + {0x3300, 0x4dbf}, + {0x4e00, 0xa48c}, + {0xa490, 0xa4c6}, + {0xa960, 0xa97c}, + {0xac00, 0xd7a3}, + {0xf900, 0xfaff}, + {0xfe10, 0xfe19}, + {0xfe30, 0xfe52}, + {0xfe54, 0xfe66}, + {0xfe68, 0xfe6b}, + {0xff01, 0xff60}, + {0xffe0, 0xffe6}, + {0x16fe0, 0x16fe0}, + {0x17000, 0x187ec}, + {0x18800, 0x18af2}, + {0x1b000, 0x1b001}, + {0x1f004, 0x1f004}, + {0x1f0cf, 0x1f0cf}, + {0x1f18e, 0x1f18e}, + {0x1f191, 0x1f19a}, + {0x1f200, 0x1f202}, + {0x1f210, 0x1f23b}, + {0x1f240, 0x1f248}, + {0x1f250, 0x1f251}, + {0x1f300, 0x1f320}, + {0x1f32d, 0x1f335}, + {0x1f337, 0x1f37c}, + {0x1f37e, 0x1f393}, + {0x1f3a0, 0x1f3ca}, + {0x1f3cf, 0x1f3d3}, + {0x1f3e0, 0x1f3f0}, + {0x1f3f4, 0x1f3f4}, + {0x1f3f8, 0x1f43e}, + {0x1f440, 0x1f440}, + {0x1f442, 0x1f4fc}, + {0x1f4ff, 0x1f53d}, + {0x1f54b, 0x1f54e}, + {0x1f550, 0x1f567}, + {0x1f57a, 0x1f57a}, + {0x1f595, 0x1f596}, + {0x1f5a4, 0x1f5a4}, + {0x1f5fb, 0x1f64f}, + {0x1f680, 0x1f6c5}, + {0x1f6cc, 0x1f6cc}, + {0x1f6d0, 0x1f6d2}, + {0x1f6eb, 0x1f6ec}, + {0x1f6f4, 0x1f6f6}, + {0x1f910, 0x1f91e}, + {0x1f920, 0x1f927}, + {0x1f930, 0x1f930}, + {0x1f933, 0x1f93e}, + {0x1f940, 0x1f94b}, + {0x1f950, 0x1f95e}, + {0x1f980, 0x1f991}, + {0x1f9c0, 0x1f9c0}, + {0x20000, 0x2fffd}, + {0x30000, 0x3fffd}, +}; + +static const struct wcwidth9_interval wcwidth9_ambiguous[] = { + {0x00a1, 0x00a1}, + {0x00a4, 0x00a4}, + {0x00a7, 0x00a8}, + {0x00aa, 0x00aa}, + {0x00ad, 0x00ae}, + {0x00b0, 0x00b4}, + {0x00b6, 0x00ba}, + {0x00bc, 0x00bf}, + {0x00c6, 0x00c6}, + {0x00d0, 0x00d0}, + {0x00d7, 0x00d8}, + {0x00de, 0x00e1}, + {0x00e6, 0x00e6}, + {0x00e8, 0x00ea}, + {0x00ec, 0x00ed}, + {0x00f0, 0x00f0}, + {0x00f2, 0x00f3}, + {0x00f7, 0x00fa}, + {0x00fc, 0x00fc}, + {0x00fe, 0x00fe}, + {0x0101, 0x0101}, + {0x0111, 0x0111}, + {0x0113, 0x0113}, + {0x011b, 0x011b}, + {0x0126, 0x0127}, + {0x012b, 0x012b}, + {0x0131, 0x0133}, + {0x0138, 0x0138}, + {0x013f, 0x0142}, + {0x0144, 0x0144}, + {0x0148, 0x014b}, + {0x014d, 0x014d}, + {0x0152, 0x0153}, + {0x0166, 0x0167}, + {0x016b, 0x016b}, + {0x01ce, 0x01ce}, + {0x01d0, 0x01d0}, + {0x01d2, 0x01d2}, + {0x01d4, 0x01d4}, + {0x01d6, 0x01d6}, + {0x01d8, 0x01d8}, + {0x01da, 0x01da}, + {0x01dc, 0x01dc}, + {0x0251, 0x0251}, + {0x0261, 0x0261}, + {0x02c4, 0x02c4}, + {0x02c7, 0x02c7}, + {0x02c9, 0x02cb}, + {0x02cd, 0x02cd}, + {0x02d0, 0x02d0}, + {0x02d8, 0x02db}, + {0x02dd, 0x02dd}, + {0x02df, 0x02df}, + {0x0300, 0x036f}, + {0x0391, 0x03a1}, + {0x03a3, 0x03a9}, + {0x03b1, 0x03c1}, + {0x03c3, 0x03c9}, + {0x0401, 0x0401}, + {0x0410, 0x044f}, + {0x0451, 0x0451}, + {0x2010, 0x2010}, + {0x2013, 0x2016}, + {0x2018, 0x2019}, + {0x201c, 0x201d}, + {0x2020, 0x2022}, + {0x2024, 0x2027}, + {0x2030, 0x2030}, + {0x2032, 0x2033}, + {0x2035, 0x2035}, + {0x203b, 0x203b}, + {0x203e, 0x203e}, + {0x2074, 0x2074}, + {0x207f, 0x207f}, + {0x2081, 0x2084}, + {0x20ac, 0x20ac}, + {0x2103, 0x2103}, + {0x2105, 0x2105}, + {0x2109, 0x2109}, + {0x2113, 0x2113}, + {0x2116, 0x2116}, + {0x2121, 0x2122}, + {0x2126, 0x2126}, + {0x212b, 0x212b}, + {0x2153, 0x2154}, + {0x215b, 0x215e}, + {0x2160, 0x216b}, + {0x2170, 0x2179}, + {0x2189, 0x2189}, + {0x2190, 0x2199}, + {0x21b8, 0x21b9}, + {0x21d2, 0x21d2}, + {0x21d4, 0x21d4}, + {0x21e7, 0x21e7}, + {0x2200, 0x2200}, + {0x2202, 0x2203}, + {0x2207, 0x2208}, + {0x220b, 0x220b}, + {0x220f, 0x220f}, + {0x2211, 0x2211}, + {0x2215, 0x2215}, + {0x221a, 0x221a}, + {0x221d, 0x2220}, + {0x2223, 0x2223}, + {0x2225, 0x2225}, + {0x2227, 0x222c}, + {0x222e, 0x222e}, + {0x2234, 0x2237}, + {0x223c, 0x223d}, + {0x2248, 0x2248}, + {0x224c, 0x224c}, + {0x2252, 0x2252}, + {0x2260, 0x2261}, + {0x2264, 0x2267}, + {0x226a, 0x226b}, + {0x226e, 0x226f}, + {0x2282, 0x2283}, + {0x2286, 0x2287}, + {0x2295, 0x2295}, + {0x2299, 0x2299}, + {0x22a5, 0x22a5}, + {0x22bf, 0x22bf}, + {0x2312, 0x2312}, + {0x2460, 0x24e9}, + {0x24eb, 0x254b}, + {0x2550, 0x2573}, + {0x2580, 0x258f}, + {0x2592, 0x2595}, + {0x25a0, 0x25a1}, + {0x25a3, 0x25a9}, + {0x25b2, 0x25b3}, + {0x25b6, 0x25b7}, + {0x25bc, 0x25bd}, + {0x25c0, 0x25c1}, + {0x25c6, 0x25c8}, + {0x25cb, 0x25cb}, + {0x25ce, 0x25d1}, + {0x25e2, 0x25e5}, + {0x25ef, 0x25ef}, + {0x2605, 0x2606}, + {0x2609, 0x2609}, + {0x260e, 0x260f}, + {0x261c, 0x261c}, + {0x261e, 0x261e}, + {0x2640, 0x2640}, + {0x2642, 0x2642}, + {0x2660, 0x2661}, + {0x2663, 0x2665}, + {0x2667, 0x266a}, + {0x266c, 0x266d}, + {0x266f, 0x266f}, + {0x269e, 0x269f}, + {0x26bf, 0x26bf}, + {0x26c6, 0x26cd}, + {0x26cf, 0x26d3}, + {0x26d5, 0x26e1}, + {0x26e3, 0x26e3}, + {0x26e8, 0x26e9}, + {0x26eb, 0x26f1}, + {0x26f4, 0x26f4}, + {0x26f6, 0x26f9}, + {0x26fb, 0x26fc}, + {0x26fe, 0x26ff}, + {0x273d, 0x273d}, + {0x2776, 0x277f}, + {0x2b56, 0x2b59}, + {0x3248, 0x324f}, + {0xe000, 0xf8ff}, + {0xfe00, 0xfe0f}, + {0xfffd, 0xfffd}, + {0x1f100, 0x1f10a}, + {0x1f110, 0x1f12d}, + {0x1f130, 0x1f169}, + {0x1f170, 0x1f18d}, + {0x1f18f, 0x1f190}, + {0x1f19b, 0x1f1ac}, + {0xe0100, 0xe01ef}, + {0xf0000, 0xffffd}, + {0x100000, 0x10fffd}, +}; + +static const struct wcwidth9_interval wcwidth9_emoji_width[] = { + {0x1f1e6, 0x1f1ff}, + {0x1f321, 0x1f321}, + {0x1f324, 0x1f32c}, + {0x1f336, 0x1f336}, + {0x1f37d, 0x1f37d}, + {0x1f396, 0x1f397}, + {0x1f399, 0x1f39b}, + {0x1f39e, 0x1f39f}, + {0x1f3cb, 0x1f3ce}, + {0x1f3d4, 0x1f3df}, + {0x1f3f3, 0x1f3f5}, + {0x1f3f7, 0x1f3f7}, + {0x1f43f, 0x1f43f}, + {0x1f441, 0x1f441}, + {0x1f4fd, 0x1f4fd}, + {0x1f549, 0x1f54a}, + {0x1f56f, 0x1f570}, + {0x1f573, 0x1f579}, + {0x1f587, 0x1f587}, + {0x1f58a, 0x1f58d}, + {0x1f590, 0x1f590}, + {0x1f5a5, 0x1f5a5}, + {0x1f5a8, 0x1f5a8}, + {0x1f5b1, 0x1f5b2}, + {0x1f5bc, 0x1f5bc}, + {0x1f5c2, 0x1f5c4}, + {0x1f5d1, 0x1f5d3}, + {0x1f5dc, 0x1f5de}, + {0x1f5e1, 0x1f5e1}, + {0x1f5e3, 0x1f5e3}, + {0x1f5e8, 0x1f5e8}, + {0x1f5ef, 0x1f5ef}, + {0x1f5f3, 0x1f5f3}, + {0x1f5fa, 0x1f5fa}, + {0x1f6cb, 0x1f6cf}, + {0x1f6e0, 0x1f6e5}, + {0x1f6e9, 0x1f6e9}, + {0x1f6f0, 0x1f6f0}, + {0x1f6f3, 0x1f6f3}, +}; + +static const struct wcwidth9_interval wcwidth9_not_assigned[] = { + {0x0378, 0x0379}, + {0x0380, 0x0383}, + {0x038b, 0x038b}, + {0x038d, 0x038d}, + {0x03a2, 0x03a2}, + {0x0530, 0x0530}, + {0x0557, 0x0558}, + {0x0560, 0x0560}, + {0x0588, 0x0588}, + {0x058b, 0x058c}, + {0x0590, 0x0590}, + {0x05c8, 0x05cf}, + {0x05eb, 0x05ef}, + {0x05f5, 0x05ff}, + {0x061d, 0x061d}, + {0x070e, 0x070e}, + {0x074b, 0x074c}, + {0x07b2, 0x07bf}, + {0x07fb, 0x07ff}, + {0x082e, 0x082f}, + {0x083f, 0x083f}, + {0x085c, 0x085d}, + {0x085f, 0x089f}, + {0x08b5, 0x08b5}, + {0x08be, 0x08d3}, + {0x0984, 0x0984}, + {0x098d, 0x098e}, + {0x0991, 0x0992}, + {0x09a9, 0x09a9}, + {0x09b1, 0x09b1}, + {0x09b3, 0x09b5}, + {0x09ba, 0x09bb}, + {0x09c5, 0x09c6}, + {0x09c9, 0x09ca}, + {0x09cf, 0x09d6}, + {0x09d8, 0x09db}, + {0x09de, 0x09de}, + {0x09e4, 0x09e5}, + {0x09fc, 0x0a00}, + {0x0a04, 0x0a04}, + {0x0a0b, 0x0a0e}, + {0x0a11, 0x0a12}, + {0x0a29, 0x0a29}, + {0x0a31, 0x0a31}, + {0x0a34, 0x0a34}, + {0x0a37, 0x0a37}, + {0x0a3a, 0x0a3b}, + {0x0a3d, 0x0a3d}, + {0x0a43, 0x0a46}, + {0x0a49, 0x0a4a}, + {0x0a4e, 0x0a50}, + {0x0a52, 0x0a58}, + {0x0a5d, 0x0a5d}, + {0x0a5f, 0x0a65}, + {0x0a76, 0x0a80}, + {0x0a84, 0x0a84}, + {0x0a8e, 0x0a8e}, + {0x0a92, 0x0a92}, + {0x0aa9, 0x0aa9}, + {0x0ab1, 0x0ab1}, + {0x0ab4, 0x0ab4}, + {0x0aba, 0x0abb}, + {0x0ac6, 0x0ac6}, + {0x0aca, 0x0aca}, + {0x0ace, 0x0acf}, + {0x0ad1, 0x0adf}, + {0x0ae4, 0x0ae5}, + {0x0af2, 0x0af8}, + {0x0afa, 0x0b00}, + {0x0b04, 0x0b04}, + {0x0b0d, 0x0b0e}, + {0x0b11, 0x0b12}, + {0x0b29, 0x0b29}, + {0x0b31, 0x0b31}, + {0x0b34, 0x0b34}, + {0x0b3a, 0x0b3b}, + {0x0b45, 0x0b46}, + {0x0b49, 0x0b4a}, + {0x0b4e, 0x0b55}, + {0x0b58, 0x0b5b}, + {0x0b5e, 0x0b5e}, + {0x0b64, 0x0b65}, + {0x0b78, 0x0b81}, + {0x0b84, 0x0b84}, + {0x0b8b, 0x0b8d}, + {0x0b91, 0x0b91}, + {0x0b96, 0x0b98}, + {0x0b9b, 0x0b9b}, + {0x0b9d, 0x0b9d}, + {0x0ba0, 0x0ba2}, + {0x0ba5, 0x0ba7}, + {0x0bab, 0x0bad}, + {0x0bba, 0x0bbd}, + {0x0bc3, 0x0bc5}, + {0x0bc9, 0x0bc9}, + {0x0bce, 0x0bcf}, + {0x0bd1, 0x0bd6}, + {0x0bd8, 0x0be5}, + {0x0bfb, 0x0bff}, + {0x0c04, 0x0c04}, + {0x0c0d, 0x0c0d}, + {0x0c11, 0x0c11}, + {0x0c29, 0x0c29}, + {0x0c3a, 0x0c3c}, + {0x0c45, 0x0c45}, + {0x0c49, 0x0c49}, + {0x0c4e, 0x0c54}, + {0x0c57, 0x0c57}, + {0x0c5b, 0x0c5f}, + {0x0c64, 0x0c65}, + {0x0c70, 0x0c77}, + {0x0c84, 0x0c84}, + {0x0c8d, 0x0c8d}, + {0x0c91, 0x0c91}, + {0x0ca9, 0x0ca9}, + {0x0cb4, 0x0cb4}, + {0x0cba, 0x0cbb}, + {0x0cc5, 0x0cc5}, + {0x0cc9, 0x0cc9}, + {0x0cce, 0x0cd4}, + {0x0cd7, 0x0cdd}, + {0x0cdf, 0x0cdf}, + {0x0ce4, 0x0ce5}, + {0x0cf0, 0x0cf0}, + {0x0cf3, 0x0d00}, + {0x0d04, 0x0d04}, + {0x0d0d, 0x0d0d}, + {0x0d11, 0x0d11}, + {0x0d3b, 0x0d3c}, + {0x0d45, 0x0d45}, + {0x0d49, 0x0d49}, + {0x0d50, 0x0d53}, + {0x0d64, 0x0d65}, + {0x0d80, 0x0d81}, + {0x0d84, 0x0d84}, + {0x0d97, 0x0d99}, + {0x0db2, 0x0db2}, + {0x0dbc, 0x0dbc}, + {0x0dbe, 0x0dbf}, + {0x0dc7, 0x0dc9}, + {0x0dcb, 0x0dce}, + {0x0dd5, 0x0dd5}, + {0x0dd7, 0x0dd7}, + {0x0de0, 0x0de5}, + {0x0df0, 0x0df1}, + {0x0df5, 0x0e00}, + {0x0e3b, 0x0e3e}, + {0x0e5c, 0x0e80}, + {0x0e83, 0x0e83}, + {0x0e85, 0x0e86}, + {0x0e89, 0x0e89}, + {0x0e8b, 0x0e8c}, + {0x0e8e, 0x0e93}, + {0x0e98, 0x0e98}, + {0x0ea0, 0x0ea0}, + {0x0ea4, 0x0ea4}, + {0x0ea6, 0x0ea6}, + {0x0ea8, 0x0ea9}, + {0x0eac, 0x0eac}, + {0x0eba, 0x0eba}, + {0x0ebe, 0x0ebf}, + {0x0ec5, 0x0ec5}, + {0x0ec7, 0x0ec7}, + {0x0ece, 0x0ecf}, + {0x0eda, 0x0edb}, + {0x0ee0, 0x0eff}, + {0x0f48, 0x0f48}, + {0x0f6d, 0x0f70}, + {0x0f98, 0x0f98}, + {0x0fbd, 0x0fbd}, + {0x0fcd, 0x0fcd}, + {0x0fdb, 0x0fff}, + {0x10c6, 0x10c6}, + {0x10c8, 0x10cc}, + {0x10ce, 0x10cf}, + {0x1249, 0x1249}, + {0x124e, 0x124f}, + {0x1257, 0x1257}, + {0x1259, 0x1259}, + {0x125e, 0x125f}, + {0x1289, 0x1289}, + {0x128e, 0x128f}, + {0x12b1, 0x12b1}, + {0x12b6, 0x12b7}, + {0x12bf, 0x12bf}, + {0x12c1, 0x12c1}, + {0x12c6, 0x12c7}, + {0x12d7, 0x12d7}, + {0x1311, 0x1311}, + {0x1316, 0x1317}, + {0x135b, 0x135c}, + {0x137d, 0x137f}, + {0x139a, 0x139f}, + {0x13f6, 0x13f7}, + {0x13fe, 0x13ff}, + {0x169d, 0x169f}, + {0x16f9, 0x16ff}, + {0x170d, 0x170d}, + {0x1715, 0x171f}, + {0x1737, 0x173f}, + {0x1754, 0x175f}, + {0x176d, 0x176d}, + {0x1771, 0x1771}, + {0x1774, 0x177f}, + {0x17de, 0x17df}, + {0x17ea, 0x17ef}, + {0x17fa, 0x17ff}, + {0x180f, 0x180f}, + {0x181a, 0x181f}, + {0x1878, 0x187f}, + {0x18ab, 0x18af}, + {0x18f6, 0x18ff}, + {0x191f, 0x191f}, + {0x192c, 0x192f}, + {0x193c, 0x193f}, + {0x1941, 0x1943}, + {0x196e, 0x196f}, + {0x1975, 0x197f}, + {0x19ac, 0x19af}, + {0x19ca, 0x19cf}, + {0x19db, 0x19dd}, + {0x1a1c, 0x1a1d}, + {0x1a5f, 0x1a5f}, + {0x1a7d, 0x1a7e}, + {0x1a8a, 0x1a8f}, + {0x1a9a, 0x1a9f}, + {0x1aae, 0x1aaf}, + {0x1abf, 0x1aff}, + {0x1b4c, 0x1b4f}, + {0x1b7d, 0x1b7f}, + {0x1bf4, 0x1bfb}, + {0x1c38, 0x1c3a}, + {0x1c4a, 0x1c4c}, + {0x1c89, 0x1cbf}, + {0x1cc8, 0x1ccf}, + {0x1cf7, 0x1cf7}, + {0x1cfa, 0x1cff}, + {0x1df6, 0x1dfa}, + {0x1f16, 0x1f17}, + {0x1f1e, 0x1f1f}, + {0x1f46, 0x1f47}, + {0x1f4e, 0x1f4f}, + {0x1f58, 0x1f58}, + {0x1f5a, 0x1f5a}, + {0x1f5c, 0x1f5c}, + {0x1f5e, 0x1f5e}, + {0x1f7e, 0x1f7f}, + {0x1fb5, 0x1fb5}, + {0x1fc5, 0x1fc5}, + {0x1fd4, 0x1fd5}, + {0x1fdc, 0x1fdc}, + {0x1ff0, 0x1ff1}, + {0x1ff5, 0x1ff5}, + {0x1fff, 0x1fff}, + {0x2065, 0x2065}, + {0x2072, 0x2073}, + {0x208f, 0x208f}, + {0x209d, 0x209f}, + {0x20bf, 0x20cf}, + {0x20f1, 0x20ff}, + {0x218c, 0x218f}, + {0x23ff, 0x23ff}, + {0x2427, 0x243f}, + {0x244b, 0x245f}, + {0x2b74, 0x2b75}, + {0x2b96, 0x2b97}, + {0x2bba, 0x2bbc}, + {0x2bc9, 0x2bc9}, + {0x2bd2, 0x2beb}, + {0x2bf0, 0x2bff}, + {0x2c2f, 0x2c2f}, + {0x2c5f, 0x2c5f}, + {0x2cf4, 0x2cf8}, + {0x2d26, 0x2d26}, + {0x2d28, 0x2d2c}, + {0x2d2e, 0x2d2f}, + {0x2d68, 0x2d6e}, + {0x2d71, 0x2d7e}, + {0x2d97, 0x2d9f}, + {0x2da7, 0x2da7}, + {0x2daf, 0x2daf}, + {0x2db7, 0x2db7}, + {0x2dbf, 0x2dbf}, + {0x2dc7, 0x2dc7}, + {0x2dcf, 0x2dcf}, + {0x2dd7, 0x2dd7}, + {0x2ddf, 0x2ddf}, + {0x2e45, 0x2e7f}, + {0x2e9a, 0x2e9a}, + {0x2ef4, 0x2eff}, + {0x2fd6, 0x2fef}, + {0x2ffc, 0x2fff}, + {0x3040, 0x3040}, + {0x3097, 0x3098}, + {0x3100, 0x3104}, + {0x312e, 0x3130}, + {0x318f, 0x318f}, + {0x31bb, 0x31bf}, + {0x31e4, 0x31ef}, + {0x321f, 0x321f}, + {0x32ff, 0x32ff}, + {0x4db6, 0x4dbf}, + {0x9fd6, 0x9fff}, + {0xa48d, 0xa48f}, + {0xa4c7, 0xa4cf}, + {0xa62c, 0xa63f}, + {0xa6f8, 0xa6ff}, + {0xa7af, 0xa7af}, + {0xa7b8, 0xa7f6}, + {0xa82c, 0xa82f}, + {0xa83a, 0xa83f}, + {0xa878, 0xa87f}, + {0xa8c6, 0xa8cd}, + {0xa8da, 0xa8df}, + {0xa8fe, 0xa8ff}, + {0xa954, 0xa95e}, + {0xa97d, 0xa97f}, + {0xa9ce, 0xa9ce}, + {0xa9da, 0xa9dd}, + {0xa9ff, 0xa9ff}, + {0xaa37, 0xaa3f}, + {0xaa4e, 0xaa4f}, + {0xaa5a, 0xaa5b}, + {0xaac3, 0xaada}, + {0xaaf7, 0xab00}, + {0xab07, 0xab08}, + {0xab0f, 0xab10}, + {0xab17, 0xab1f}, + {0xab27, 0xab27}, + {0xab2f, 0xab2f}, + {0xab66, 0xab6f}, + {0xabee, 0xabef}, + {0xabfa, 0xabff}, + {0xd7a4, 0xd7af}, + {0xd7c7, 0xd7ca}, + {0xd7fc, 0xd7ff}, + {0xfa6e, 0xfa6f}, + {0xfada, 0xfaff}, + {0xfb07, 0xfb12}, + {0xfb18, 0xfb1c}, + {0xfb37, 0xfb37}, + {0xfb3d, 0xfb3d}, + {0xfb3f, 0xfb3f}, + {0xfb42, 0xfb42}, + {0xfb45, 0xfb45}, + {0xfbc2, 0xfbd2}, + {0xfd40, 0xfd4f}, + {0xfd90, 0xfd91}, + {0xfdc8, 0xfdef}, + {0xfdfe, 0xfdff}, + {0xfe1a, 0xfe1f}, + {0xfe53, 0xfe53}, + {0xfe67, 0xfe67}, + {0xfe6c, 0xfe6f}, + {0xfe75, 0xfe75}, + {0xfefd, 0xfefe}, + {0xff00, 0xff00}, + {0xffbf, 0xffc1}, + {0xffc8, 0xffc9}, + {0xffd0, 0xffd1}, + {0xffd8, 0xffd9}, + {0xffdd, 0xffdf}, + {0xffe7, 0xffe7}, + {0xffef, 0xfff8}, + {0xfffe, 0xffff}, + {0x1000c, 0x1000c}, + {0x10027, 0x10027}, + {0x1003b, 0x1003b}, + {0x1003e, 0x1003e}, + {0x1004e, 0x1004f}, + {0x1005e, 0x1007f}, + {0x100fb, 0x100ff}, + {0x10103, 0x10106}, + {0x10134, 0x10136}, + {0x1018f, 0x1018f}, + {0x1019c, 0x1019f}, + {0x101a1, 0x101cf}, + {0x101fe, 0x1027f}, + {0x1029d, 0x1029f}, + {0x102d1, 0x102df}, + {0x102fc, 0x102ff}, + {0x10324, 0x1032f}, + {0x1034b, 0x1034f}, + {0x1037b, 0x1037f}, + {0x1039e, 0x1039e}, + {0x103c4, 0x103c7}, + {0x103d6, 0x103ff}, + {0x1049e, 0x1049f}, + {0x104aa, 0x104af}, + {0x104d4, 0x104d7}, + {0x104fc, 0x104ff}, + {0x10528, 0x1052f}, + {0x10564, 0x1056e}, + {0x10570, 0x105ff}, + {0x10737, 0x1073f}, + {0x10756, 0x1075f}, + {0x10768, 0x107ff}, + {0x10806, 0x10807}, + {0x10809, 0x10809}, + {0x10836, 0x10836}, + {0x10839, 0x1083b}, + {0x1083d, 0x1083e}, + {0x10856, 0x10856}, + {0x1089f, 0x108a6}, + {0x108b0, 0x108df}, + {0x108f3, 0x108f3}, + {0x108f6, 0x108fa}, + {0x1091c, 0x1091e}, + {0x1093a, 0x1093e}, + {0x10940, 0x1097f}, + {0x109b8, 0x109bb}, + {0x109d0, 0x109d1}, + {0x10a04, 0x10a04}, + {0x10a07, 0x10a0b}, + {0x10a14, 0x10a14}, + {0x10a18, 0x10a18}, + {0x10a34, 0x10a37}, + {0x10a3b, 0x10a3e}, + {0x10a48, 0x10a4f}, + {0x10a59, 0x10a5f}, + {0x10aa0, 0x10abf}, + {0x10ae7, 0x10aea}, + {0x10af7, 0x10aff}, + {0x10b36, 0x10b38}, + {0x10b56, 0x10b57}, + {0x10b73, 0x10b77}, + {0x10b92, 0x10b98}, + {0x10b9d, 0x10ba8}, + {0x10bb0, 0x10bff}, + {0x10c49, 0x10c7f}, + {0x10cb3, 0x10cbf}, + {0x10cf3, 0x10cf9}, + {0x10d00, 0x10e5f}, + {0x10e7f, 0x10fff}, + {0x1104e, 0x11051}, + {0x11070, 0x1107e}, + {0x110c2, 0x110cf}, + {0x110e9, 0x110ef}, + {0x110fa, 0x110ff}, + {0x11135, 0x11135}, + {0x11144, 0x1114f}, + {0x11177, 0x1117f}, + {0x111ce, 0x111cf}, + {0x111e0, 0x111e0}, + {0x111f5, 0x111ff}, + {0x11212, 0x11212}, + {0x1123f, 0x1127f}, + {0x11287, 0x11287}, + {0x11289, 0x11289}, + {0x1128e, 0x1128e}, + {0x1129e, 0x1129e}, + {0x112aa, 0x112af}, + {0x112eb, 0x112ef}, + {0x112fa, 0x112ff}, + {0x11304, 0x11304}, + {0x1130d, 0x1130e}, + {0x11311, 0x11312}, + {0x11329, 0x11329}, + {0x11331, 0x11331}, + {0x11334, 0x11334}, + {0x1133a, 0x1133b}, + {0x11345, 0x11346}, + {0x11349, 0x1134a}, + {0x1134e, 0x1134f}, + {0x11351, 0x11356}, + {0x11358, 0x1135c}, + {0x11364, 0x11365}, + {0x1136d, 0x1136f}, + {0x11375, 0x113ff}, + {0x1145a, 0x1145a}, + {0x1145c, 0x1145c}, + {0x1145e, 0x1147f}, + {0x114c8, 0x114cf}, + {0x114da, 0x1157f}, + {0x115b6, 0x115b7}, + {0x115de, 0x115ff}, + {0x11645, 0x1164f}, + {0x1165a, 0x1165f}, + {0x1166d, 0x1167f}, + {0x116b8, 0x116bf}, + {0x116ca, 0x116ff}, + {0x1171a, 0x1171c}, + {0x1172c, 0x1172f}, + {0x11740, 0x1189f}, + {0x118f3, 0x118fe}, + {0x11900, 0x11abf}, + {0x11af9, 0x11bff}, + {0x11c09, 0x11c09}, + {0x11c37, 0x11c37}, + {0x11c46, 0x11c4f}, + {0x11c6d, 0x11c6f}, + {0x11c90, 0x11c91}, + {0x11ca8, 0x11ca8}, + {0x11cb7, 0x11fff}, + {0x1239a, 0x123ff}, + {0x1246f, 0x1246f}, + {0x12475, 0x1247f}, + {0x12544, 0x12fff}, + {0x1342f, 0x143ff}, + {0x14647, 0x167ff}, + {0x16a39, 0x16a3f}, + {0x16a5f, 0x16a5f}, + {0x16a6a, 0x16a6d}, + {0x16a70, 0x16acf}, + {0x16aee, 0x16aef}, + {0x16af6, 0x16aff}, + {0x16b46, 0x16b4f}, + {0x16b5a, 0x16b5a}, + {0x16b62, 0x16b62}, + {0x16b78, 0x16b7c}, + {0x16b90, 0x16eff}, + {0x16f45, 0x16f4f}, + {0x16f7f, 0x16f8e}, + {0x16fa0, 0x16fdf}, + {0x16fe1, 0x16fff}, + {0x187ed, 0x187ff}, + {0x18af3, 0x1afff}, + {0x1b002, 0x1bbff}, + {0x1bc6b, 0x1bc6f}, + {0x1bc7d, 0x1bc7f}, + {0x1bc89, 0x1bc8f}, + {0x1bc9a, 0x1bc9b}, + {0x1bca4, 0x1cfff}, + {0x1d0f6, 0x1d0ff}, + {0x1d127, 0x1d128}, + {0x1d1e9, 0x1d1ff}, + {0x1d246, 0x1d2ff}, + {0x1d357, 0x1d35f}, + {0x1d372, 0x1d3ff}, + {0x1d455, 0x1d455}, + {0x1d49d, 0x1d49d}, + {0x1d4a0, 0x1d4a1}, + {0x1d4a3, 0x1d4a4}, + {0x1d4a7, 0x1d4a8}, + {0x1d4ad, 0x1d4ad}, + {0x1d4ba, 0x1d4ba}, + {0x1d4bc, 0x1d4bc}, + {0x1d4c4, 0x1d4c4}, + {0x1d506, 0x1d506}, + {0x1d50b, 0x1d50c}, + {0x1d515, 0x1d515}, + {0x1d51d, 0x1d51d}, + {0x1d53a, 0x1d53a}, + {0x1d53f, 0x1d53f}, + {0x1d545, 0x1d545}, + {0x1d547, 0x1d549}, + {0x1d551, 0x1d551}, + {0x1d6a6, 0x1d6a7}, + {0x1d7cc, 0x1d7cd}, + {0x1da8c, 0x1da9a}, + {0x1daa0, 0x1daa0}, + {0x1dab0, 0x1dfff}, + {0x1e007, 0x1e007}, + {0x1e019, 0x1e01a}, + {0x1e022, 0x1e022}, + {0x1e025, 0x1e025}, + {0x1e02b, 0x1e7ff}, + {0x1e8c5, 0x1e8c6}, + {0x1e8d7, 0x1e8ff}, + {0x1e94b, 0x1e94f}, + {0x1e95a, 0x1e95d}, + {0x1e960, 0x1edff}, + {0x1ee04, 0x1ee04}, + {0x1ee20, 0x1ee20}, + {0x1ee23, 0x1ee23}, + {0x1ee25, 0x1ee26}, + {0x1ee28, 0x1ee28}, + {0x1ee33, 0x1ee33}, + {0x1ee38, 0x1ee38}, + {0x1ee3a, 0x1ee3a}, + {0x1ee3c, 0x1ee41}, + {0x1ee43, 0x1ee46}, + {0x1ee48, 0x1ee48}, + {0x1ee4a, 0x1ee4a}, + {0x1ee4c, 0x1ee4c}, + {0x1ee50, 0x1ee50}, + {0x1ee53, 0x1ee53}, + {0x1ee55, 0x1ee56}, + {0x1ee58, 0x1ee58}, + {0x1ee5a, 0x1ee5a}, + {0x1ee5c, 0x1ee5c}, + {0x1ee5e, 0x1ee5e}, + {0x1ee60, 0x1ee60}, + {0x1ee63, 0x1ee63}, + {0x1ee65, 0x1ee66}, + {0x1ee6b, 0x1ee6b}, + {0x1ee73, 0x1ee73}, + {0x1ee78, 0x1ee78}, + {0x1ee7d, 0x1ee7d}, + {0x1ee7f, 0x1ee7f}, + {0x1ee8a, 0x1ee8a}, + {0x1ee9c, 0x1eea0}, + {0x1eea4, 0x1eea4}, + {0x1eeaa, 0x1eeaa}, + {0x1eebc, 0x1eeef}, + {0x1eef2, 0x1efff}, + {0x1f02c, 0x1f02f}, + {0x1f094, 0x1f09f}, + {0x1f0af, 0x1f0b0}, + {0x1f0c0, 0x1f0c0}, + {0x1f0d0, 0x1f0d0}, + {0x1f0f6, 0x1f0ff}, + {0x1f10d, 0x1f10f}, + {0x1f12f, 0x1f12f}, + {0x1f16c, 0x1f16f}, + {0x1f1ad, 0x1f1e5}, + {0x1f203, 0x1f20f}, + {0x1f23c, 0x1f23f}, + {0x1f249, 0x1f24f}, + {0x1f252, 0x1f2ff}, + {0x1f6d3, 0x1f6df}, + {0x1f6ed, 0x1f6ef}, + {0x1f6f7, 0x1f6ff}, + {0x1f774, 0x1f77f}, + {0x1f7d5, 0x1f7ff}, + {0x1f80c, 0x1f80f}, + {0x1f848, 0x1f84f}, + {0x1f85a, 0x1f85f}, + {0x1f888, 0x1f88f}, + {0x1f8ae, 0x1f90f}, + {0x1f91f, 0x1f91f}, + {0x1f928, 0x1f92f}, + {0x1f931, 0x1f932}, + {0x1f93f, 0x1f93f}, + {0x1f94c, 0x1f94f}, + {0x1f95f, 0x1f97f}, + {0x1f992, 0x1f9bf}, + {0x1f9c1, 0x1ffff}, + {0x2a6d7, 0x2a6ff}, + {0x2b735, 0x2b73f}, + {0x2b81e, 0x2b81f}, + {0x2cea2, 0x2f7ff}, + {0x2fa1e, 0xe0000}, + {0xe0002, 0xe001f}, + {0xe0080, 0xe00ff}, + {0xe01f0, 0xeffff}, + {0xffffe, 0xfffff}, +}; + +#define WCWIDTH9_ARRAY_SIZE(arr) ((sizeof(arr)/sizeof((arr)[0])) / ((size_t)(!(sizeof(arr) % sizeof((arr)[0]))))) + +static inline bool wcwidth9_intable(const struct wcwidth9_interval *table, size_t n_items, int c) { + int mid, bot, top; + + if (c < table[0].first) { + return false; + } + + bot = 0; + top = (int)(n_items - 1); + while (top >= bot) { + mid = (bot + top) / 2; + + if (table[mid].last < c) { + bot = mid + 1; + } else if (table[mid].first > c) { + top = mid - 1; + } else { + return true; + } + } + + return false; +} + +static inline int wcwidth9(int c) { + if (c == 0) { + return 0; + } + if (c < 0|| c > 0x10ffff) { + return -1; + } + + if (wcwidth9_intable(wcwidth9_nonprint, WCWIDTH9_ARRAY_SIZE(wcwidth9_nonprint), c)) { + return -1; + } + + if (wcwidth9_intable(wcwidth9_combining, WCWIDTH9_ARRAY_SIZE(wcwidth9_combining), c)) { + return 0; + } + + if (wcwidth9_intable(wcwidth9_not_assigned, WCWIDTH9_ARRAY_SIZE(wcwidth9_not_assigned), c)) { + return -1; + } + + if (wcwidth9_intable(wcwidth9_private, WCWIDTH9_ARRAY_SIZE(wcwidth9_private), c)) { + return -3; + } + + if (wcwidth9_intable(wcwidth9_ambiguous, WCWIDTH9_ARRAY_SIZE(wcwidth9_ambiguous), c)) { + return -2; + } + + if (wcwidth9_intable(wcwidth9_doublewidth, WCWIDTH9_ARRAY_SIZE(wcwidth9_doublewidth), c)) { + return 2; + } + + if (wcwidth9_intable(wcwidth9_emoji_width, WCWIDTH9_ARRAY_SIZE(wcwidth9_emoji_width), c)) { + return 2; + } + + return 1; +} + +#endif /* WCWIDTH9_H */ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/zsh.h b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/zsh.h new file mode 100644 index 00000000..8e7f20b2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/zsh.h @@ -0,0 +1,3305 @@ +/* + * zsh.h - standard header file + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +/* A few typical macros */ +#define minimum(a,b) ((a) < (b) ? (a) : (b)) + +/* + * Our longest integer type: will be a 64 bit either if long already is, + * or if we found some alternative such as long long. + */ +#ifdef ZSH_64_BIT_TYPE +typedef ZSH_64_BIT_TYPE zlong; +#if defined(ZLONG_IS_LONG_LONG) && defined(LLONG_MAX) +#define ZLONG_MAX LLONG_MAX +#else +#ifdef ZLONG_IS_LONG_64 +#define ZLONG_MAX LONG_MAX +#else +/* umm... */ +#define ZLONG_MAX ((zlong)9223372036854775807) +#endif +#endif +#ifdef ZSH_64_BIT_UTYPE +typedef ZSH_64_BIT_UTYPE zulong; +#else +typedef unsigned zlong zulong; +#endif +#else +typedef long zlong; +typedef unsigned long zulong; +#define ZLONG_MAX LONG_MAX +#endif + +/* + * Work out how to define large integer constants that will fit + * in a zlong. + */ +#if defined(ZSH_64_BIT_TYPE) || defined(LONG_IS_64_BIT) +/* We have some 64-bit type */ +#ifdef LONG_IS_64_BIT +/* It's long */ +#define ZLONG_CONST(x) x ## l +#else +/* It's long long */ +#ifdef ZLONG_IS_LONG_LONG +#define ZLONG_CONST(x) x ## ll +#else +/* + * There's some 64-bit type, but we don't know what it is. + * We'll just cast it and hope the compiler does the right thing. + */ +#define ZLONG_CONST(x) ((zlong)x) +#endif +#endif +#else +/* We're stuck with long */ +#define ZLONG_CONST(x) (x ## l) +#endif + +/* + * Double float support requires 64-bit alignment, so if longs and + * pointers are less we need to pad out. + */ +#ifndef LONG_IS_64_BIT +# define PAD_64_BIT 1 +#endif + +/* math.c */ +typedef struct { + union { + zlong l; + double d; + } u; + int type; +} mnumber; + +#define MN_INTEGER 1 /* mnumber is integer */ +#define MN_FLOAT 2 /* mnumber is floating point */ +#define MN_UNSET 4 /* mnumber not yet retrieved */ + +typedef struct mathfunc *MathFunc; +typedef mnumber (*NumMathFunc)(char *, int, mnumber *, int); +typedef mnumber (*StrMathFunc)(char *, char *, int); + +struct mathfunc { + MathFunc next; + char *name; + int flags; /* MFF_* flags defined below */ + NumMathFunc nfunc; + StrMathFunc sfunc; + char *module; + int minargs; + int maxargs; + int funcid; +}; + +/* Math function takes a string argument */ +#define MFF_STR 1 +/* Math function has been loaded from library */ +#define MFF_ADDED 2 +/* Math function is implemented by a shell function */ +#define MFF_USERFUNC 4 +/* When autoloading, enable all features in module */ +#define MFF_AUTOALL 8 + + +#define NUMMATHFUNC(name, func, min, max, id) \ + { NULL, name, 0, func, NULL, NULL, min, max, id } +#define STRMATHFUNC(name, func, id) \ + { NULL, name, MFF_STR, NULL, func, NULL, 0, 0, id } + +/* Character tokens are sometimes casted to (unsigned char)'s. * + * Unfortunately, some compilers don't correctly cast signed to * + * unsigned promotions; i.e. (int)(unsigned char)((char) -1) evaluates * + * to -1, instead of 255 like it should. We circumvent the troubles * + * of such shameful delinquency by casting to a larger unsigned type * + * then back down to unsigned char. */ + +#ifdef BROKEN_SIGNED_TO_UNSIGNED_CASTING +# define STOUC(X) ((unsigned char)(unsigned short)(X)) +#else +# define STOUC(X) ((unsigned char)(X)) +#endif + +/* Meta together with the character following Meta denotes the character * + * which is the exclusive or of 32 and the character following Meta. * + * This is used to represent characters which otherwise has special * + * meaning for zsh. These are the characters for which the imeta() test * + * is true: the null character, and the characters from Meta to Marker. */ + +#define Meta ((char) 0x83) + +/* Note that the fourth character in DEFAULT_IFS is Meta * + * followed by a space which denotes the null character. */ + +#define DEFAULT_IFS " \t\n\203 " + +/* As specified in the standard (POSIX 2008) */ + +#define DEFAULT_IFS_SH " \t\n" + +/* + * Character tokens. + * These should match the characters in ztokens, defined in lex.c + */ +#define Pound ((char) 0x84) +#define String ((char) 0x85) +#define Hat ((char) 0x86) +#define Star ((char) 0x87) +#define Inpar ((char) 0x88) +#define Inparmath ((char) 0x89) +#define Outpar ((char) 0x8a) +#define Outparmath ((char) 0x8b) +#define Qstring ((char) 0x8c) +#define Equals ((char) 0x8d) +#define Bar ((char) 0x8e) +#define Inbrace ((char) 0x8f) +#define Outbrace ((char) 0x90) +#define Inbrack ((char) 0x91) +#define Outbrack ((char) 0x92) +#define Tick ((char) 0x93) +#define Inang ((char) 0x94) +#define Outang ((char) 0x95) +#define OutangProc ((char) 0x96) +#define Quest ((char) 0x97) +#define Tilde ((char) 0x98) +#define Qtick ((char) 0x99) +#define Comma ((char) 0x9a) +#define Dash ((char) 0x9b) /* Only in patterns */ +#define Bang ((char) 0x9c) /* Only in patterns */ +/* + * Marks the last of the group above. + * Remaining tokens are even more special. + */ +#define LAST_NORMAL_TOK Bang +/* + * Null arguments: placeholders for single and double quotes + * and backslashes. + */ +#define Snull ((char) 0x9d) +#define Dnull ((char) 0x9e) +#define Bnull ((char) 0x9f) +/* + * Backslash which will be returned to "\" instead of being stripped + * when we turn the string into a printable format. + */ +#define Bnullkeep ((char) 0xa0) +/* + * Null argument that does not correspond to any character. + * This should be last as it does not appear in ztokens and + * is used to initialise the IMETA type in inittyptab(). + */ +#define Nularg ((char) 0xa1) + +/* + * Take care to update the use of IMETA appropriately when adding + * tokens here. + */ +/* + * Marker is used in the following special circumstances: + * - In paramsubst for rc_expand_param. + * - In pattern character arrays as guaranteed not to mark a character in + * a string. + * - In assignments with the ASSPM_KEY_VALUE flag set in order to + * mark that there is a key / value pair following. If this + * comes from [key]=value the Marker is followed by a null; + * if from [key]+=value the Marker is followed by a '+' then a null. + * All the above are local uses --- any case where the Marker has + * escaped beyond the context in question is an error. + */ +#define Marker ((char) 0xa2) + +/* chars that need to be quoted if meant literally */ + +#define SPECCHARS "#$^*()=|{}[]`<>?~;&\n\t \\\'\"" + +/* chars that need to be quoted for pattern matching */ + +#define PATCHARS "#^*()|[]<>?~\\" + +/* + * Check for a possibly tokenized dash. + * + * A dash only needs to be a token in a character range, [a-z], but + * it's difficult in general to ensure that. So it's turned into + * a token at the usual point in the lexer. However, we need + * to check for a literal dash at many points. + */ +#define IS_DASH(x) ((x) == '-' || (x) == Dash) + +/* + * Types of quote. This is used in various places, so care needs + * to be taken when changing them. (Oooh, don't you look surprised.) + * - Passed to quotestring() to indicate style. This is the ultimate + * destiny of most of the other uses of members of the enum. + * - In paramsubst(), to count q's in parameter substitution. + * - In the completion code, where we maintain a stack of quotation types. + */ +enum { + /* + * No quote. Not a valid quote, but useful in the substitution + * and completion code to indicate we're not doing any quoting. + */ + QT_NONE, + /* Backslash: \ */ + QT_BACKSLASH, + /* Single quote: ' */ + QT_SINGLE, + /* Double quote: " */ + QT_DOUBLE, + /* Print-style quote: $' */ + QT_DOLLARS, + /* + * Backtick: ` + * Not understood by many parts of the code; here for a convenience + * in those cases where we need to represent a complete set. + */ + QT_BACKTICK, + /* + * Single quotes, but the default is not to quote unless necessary. + * This is only useful as an argument to quotestring(). + */ + QT_SINGLE_OPTIONAL, + /* + * Only quote pattern characters. + * ${(b)foo} guarantees that ${~foo} matches the string + * contained in foo. + */ + QT_BACKSLASH_PATTERN, + /* + * As QT_BACKSLASH, but a NULL string is shown as ''. + */ + QT_BACKSLASH_SHOWNULL, + /* + * Quoting as produced by quotedzputs(), used for human + * readability of parameter values. + */ + QT_QUOTEDZPUTS +}; + +#define QT_IS_SINGLE(x) ((x) == QT_SINGLE || (x) == QT_SINGLE_OPTIONAL) + +/* + * Lexical tokens: unlike the character tokens above, these never + * appear in strings and don't necessarily represent a single character. + */ + +enum lextok { + NULLTOK, /* 0 */ + SEPER, + NEWLIN, + SEMI, + DSEMI, + AMPER, /* 5 */ + INPAR, + OUTPAR, + DBAR, + DAMPER, + OUTANG, /* 10 */ + OUTANGBANG, + DOUTANG, + DOUTANGBANG, + INANG, + INOUTANG, /* 15 */ + DINANG, + DINANGDASH, + INANGAMP, + OUTANGAMP, + AMPOUTANG, /* 20 */ + OUTANGAMPBANG, + DOUTANGAMP, + DOUTANGAMPBANG, + TRINANG, + BAR, /* 25 */ + BARAMP, + INOUTPAR, + DINPAR, + DOUTPAR, + AMPERBANG, /* 30 */ + SEMIAMP, + SEMIBAR, + DOUTBRACK, + STRING, + ENVSTRING, /* 35 */ + ENVARRAY, + ENDINPUT, + LEXERR, + + /* Tokens for reserved words */ + BANG, /* ! */ + DINBRACK, /* [[ */ /* 40 */ + INBRACE, /* { */ + OUTBRACE, /* } */ + CASE, /* case */ + COPROC, /* coproc */ + DOLOOP, /* do */ /* 45 */ + DONE, /* done */ + ELIF, /* elif */ + ELSE, /* else */ + ZEND, /* end */ + ESAC, /* esac */ /* 50 */ + FI, /* fi */ + FOR, /* for */ + FOREACH, /* foreach */ + FUNC, /* function */ + IF, /* if */ /* 55 */ + NOCORRECT, /* nocorrect */ + REPEAT, /* repeat */ + SELECT, /* select */ + THEN, /* then */ + TIME, /* time */ /* 60 */ + UNTIL, /* until */ + WHILE, /* while */ + TYPESET /* typeset or similar */ +}; + +/* Redirection types. If you modify this, you may also have to modify * + * redirtab in parse.c and getredirs() in text.c and the IS_* macros * + * below. */ + +enum { + REDIR_WRITE, /* > */ + REDIR_WRITENOW, /* >| */ + REDIR_APP, /* >> */ + REDIR_APPNOW, /* >>| */ + REDIR_ERRWRITE, /* &>, >& */ + REDIR_ERRWRITENOW, /* >&| */ + REDIR_ERRAPP, /* >>& */ + REDIR_ERRAPPNOW, /* >>&| */ + REDIR_READWRITE, /* <> */ + REDIR_READ, /* < */ + REDIR_HEREDOC, /* << */ + REDIR_HEREDOCDASH, /* <<- */ + REDIR_HERESTR, /* <<< */ + REDIR_MERGEIN, /* <&n */ + REDIR_MERGEOUT, /* >&n */ + REDIR_CLOSE, /* >&-, <&- */ + REDIR_INPIPE, /* < <(...) */ + REDIR_OUTPIPE /* > >(...) */ +}; +#define REDIR_TYPE_MASK (0x1f) +/* Redir using {var} syntax */ +#define REDIR_VARID_MASK (0x20) +/* Mark here-string that came from a here-document */ +#define REDIR_FROM_HEREDOC_MASK (0x40) + +#define IS_WRITE_FILE(X) ((X)>=REDIR_WRITE && (X)<=REDIR_READWRITE) +#define IS_APPEND_REDIR(X) (IS_WRITE_FILE(X) && ((X) & 2)) +#define IS_CLOBBER_REDIR(X) (IS_WRITE_FILE(X) && ((X) & 1)) +#define IS_ERROR_REDIR(X) ((X)>=REDIR_ERRWRITE && (X)<=REDIR_ERRAPPNOW) +#define IS_READFD(X) (((X)>=REDIR_READWRITE && (X)<=REDIR_MERGEIN) || (X)==REDIR_INPIPE) +#define IS_REDIROP(X) ((X)>=OUTANG && (X)<=TRINANG) + +/* + * Values for the fdtable array. They say under what circumstances + * the fd will be close. The fdtable is an unsigned char, so these are + * #define's rather than an enum. + */ +/* Entry not used. */ +#define FDT_UNUSED 0 +/* + * Entry used internally by the shell, should not be visible to other + * processes. + */ +#define FDT_INTERNAL 1 +/* + * Entry visible to other processes, for example created using + * the {varid}> file syntax. + */ +#define FDT_EXTERNAL 2 +/* + * Entry visible to other processes but controlled by a module. + * The difference from FDT_EXTERNAL is that closing this using + * standard fd syntax will fail as there is some tidying up that + * needs to be done by the module's own mechanism. + */ +#define FDT_MODULE 3 +/* + * Entry used by output from the XTRACE option. + */ +#define FDT_XTRACE 4 +/* + * Entry used for file locking. + */ +#define FDT_FLOCK 5 +/* + * As above, but the fd is not marked for closing on exec, + * so the shell can still exec the last process. + */ +#define FDT_FLOCK_EXEC 6 +/* + * Entry used by a process substition. + * This marker is not tested internally as we associated the file + * descriptor with a job for closing. + * + * This is not used unless PATH_DEV_FD is defined. + */ +#define FDT_PROC_SUBST 7 +/* + * Mask to get the basic FDT type. + */ +#define FDT_TYPE_MASK 15 + +/* + * Bit flag that fd is saved for later restoration. + * Currently this is only use with FDT_INTERNAL. We use this fact so as + * not to have to mask checks against other types. + */ +#define FDT_SAVED_MASK 16 + +/* Flags for input stack */ +#define INP_FREE (1<<0) /* current buffer can be free'd */ +#define INP_ALIAS (1<<1) /* expanding alias or history */ +#define INP_HIST (1<<2) /* expanding history */ +#define INP_CONT (1<<3) /* continue onto previously stacked input */ +#define INP_ALCONT (1<<4) /* stack is continued from alias expn. */ +#define INP_HISTCONT (1<<5) /* stack is continued from history expn. */ +#define INP_LINENO (1<<6) /* update line number */ +#define INP_APPEND (1<<7) /* Append new lines to allow backup */ +#define INP_RAW_KEEP (1<<8) /* Input needed in raw mode even if alias */ + +/* Flags for metafy */ +#define META_REALLOC 0 +#define META_USEHEAP 1 +#define META_STATIC 2 +#define META_DUP 3 +#define META_ALLOC 4 +#define META_NOALLOC 5 +#define META_HEAPDUP 6 +#define META_HREALLOC 7 + +/* Context to save and restore (bit fields) */ +enum { + /* History mechanism */ + ZCONTEXT_HIST = (1<<0), + /* Lexical analyser */ + ZCONTEXT_LEX = (1<<1), + /* Parser */ + ZCONTEXT_PARSE = (1<<2) +}; + +/**************************/ +/* Abstract types for zsh */ +/**************************/ + +typedef struct alias *Alias; +typedef struct asgment *Asgment; +typedef struct builtin *Builtin; +typedef struct cmdnam *Cmdnam; +typedef struct complist *Complist; +typedef struct conddef *Conddef; +typedef struct dirsav *Dirsav; +typedef struct emulation_options *Emulation_options; +typedef struct execcmd_params *Execcmd_params; +typedef struct features *Features; +typedef struct feature_enables *Feature_enables; +typedef struct funcstack *Funcstack; +typedef struct funcwrap *FuncWrap; +typedef struct hashnode *HashNode; +typedef struct hashtable *HashTable; +typedef struct heap *Heap; +typedef struct heapstack *Heapstack; +typedef struct histent *Histent; +typedef struct hookdef *Hookdef; +typedef struct imatchdata *Imatchdata; +typedef struct jobfile *Jobfile; +typedef struct job *Job; +typedef struct linkedmod *Linkedmod; +typedef struct linknode *LinkNode; +typedef union linkroot *LinkList; +typedef struct module *Module; +typedef struct nameddir *Nameddir; +typedef struct options *Options; +typedef struct optname *Optname; +typedef struct param *Param; +typedef struct paramdef *Paramdef; +typedef struct patstralloc *Patstralloc; +typedef struct patprog *Patprog; +typedef struct prepromptfn *Prepromptfn; +typedef struct process *Process; +typedef struct redir *Redir; +typedef struct reswd *Reswd; +typedef struct shfunc *Shfunc; +typedef struct timedfn *Timedfn; +typedef struct value *Value; + +/********************************/ +/* Definitions for linked lists */ +/********************************/ + +/* linked list abstract data type */ + +struct linknode { + LinkNode next; + LinkNode prev; + void *dat; +}; + +struct linklist { + LinkNode first; + LinkNode last; + int flags; +}; + +union linkroot { + struct linklist list; + struct linknode node; +}; + +/* Macros for manipulating link lists */ + +#define firstnode(X) ((X)->list.first) +#define lastnode(X) ((X)->list.last) +#define peekfirst(X) (firstnode(X)->dat) +#define peeklast(X) (lastnode(X)->dat) +#define addlinknode(X,Y) insertlinknode(X,lastnode(X),Y) +#define zaddlinknode(X,Y) zinsertlinknode(X,lastnode(X),Y) +#define uaddlinknode(X,Y) uinsertlinknode(X,lastnode(X),Y) +#define empty(X) (firstnode(X) == NULL) +#define nonempty(X) (firstnode(X) != NULL) +#define getaddrdata(X) (&((X)->dat)) +#define getdata(X) ((X)->dat) +#define setdata(X,Y) ((X)->dat = (Y)) +#define nextnode(X) ((X)->next) +#define prevnode(X) ((X)->prev) +#define pushnode(X,Y) insertlinknode(X,&(X)->node,Y) +#define zpushnode(X,Y) zinsertlinknode(X,&(X)->node,Y) +#define incnode(X) (X = nextnode(X)) +#define decnode(X) (X = prevnode(X)) +#define firsthist() (hist_ring? hist_ring->down->histnum : curhist) +#define setsizednode(X,Y,Z) (firstnode(X)[(Y)].dat = (void *) (Z)) + +/* stack allocated linked lists */ + +#define local_list0(N) union linkroot N +#define init_list0(N) \ + do { \ + (N).list.first = NULL; \ + (N).list.last = &(N).node; \ + (N).list.flags = 0; \ + } while (0) +#define local_list1(N) union linkroot N; struct linknode __n0 +#define init_list1(N,V0) \ + do { \ + (N).list.first = &__n0; \ + (N).list.last = &__n0; \ + (N).list.flags = 0; \ + __n0.next = NULL; \ + __n0.prev = &(N).node; \ + __n0.dat = (void *) (V0); \ + } while (0) + +/*************************************/ +/* Specific elements of linked lists */ +/*************************************/ + +typedef void (*voidvoidfnptr_t) _((void)); + +/* + * Element of the prepromptfns list. + */ +struct prepromptfn { + voidvoidfnptr_t func; +}; + + +/* + * Element of the timedfns list. + */ +struct timedfn { + voidvoidfnptr_t func; + time_t when; +}; + +/********************************/ +/* Definitions for syntax trees */ +/********************************/ + +/* These are control flags that are passed * + * down the execution pipeline. */ +#define Z_TIMED (1<<0) /* pipeline is being timed */ +#define Z_SYNC (1<<1) /* run this sublist synchronously (;) */ +#define Z_ASYNC (1<<2) /* run this sublist asynchronously (&) */ +#define Z_DISOWN (1<<3) /* run this sublist without job control (&|) */ +/* (1<<4) is used for Z_END, see the wordcode definitions */ +/* (1<<5) is used for Z_SIMPLE, see the wordcode definitions */ + +/* + * Condition types. + * + * Careful when changing these: both cond_binary_ops in text.c and + * condstr in cond.c depend on these. (The zsh motto is "two instances + * are better than one". Or something.) + */ + +#define COND_NOT 0 +#define COND_AND 1 +#define COND_OR 2 +#define COND_STREQ 3 +#define COND_STRDEQ 4 +#define COND_STRNEQ 5 +#define COND_STRLT 6 +#define COND_STRGTR 7 +#define COND_NT 8 +#define COND_OT 9 +#define COND_EF 10 +#define COND_EQ 11 +#define COND_NE 12 +#define COND_LT 13 +#define COND_GT 14 +#define COND_LE 15 +#define COND_GE 16 +#define COND_REGEX 17 +#define COND_MOD 18 +#define COND_MODI 19 + +typedef int (*CondHandler) _((char **, int)); + +struct conddef { + Conddef next; /* next in list */ + char *name; /* the condition name */ + int flags; /* see CONDF_* below */ + CondHandler handler; /* handler function */ + int min; /* minimum number of strings */ + int max; /* maximum number of strings */ + int condid; /* for overloading handler functions */ + char *module; /* module to autoload */ +}; + +/* Condition is an infix */ +#define CONDF_INFIX 1 +/* Condition has been loaded from library */ +#define CONDF_ADDED 2 +/* When autoloading, enable all features in library */ +#define CONDF_AUTOALL 4 + +#define CONDDEF(name, flags, handler, min, max, condid) \ + { NULL, name, flags, handler, min, max, condid, NULL } + +/* Flags for redirections */ + +enum { + /* Mark a here-string that came from a here-document */ + REDIRF_FROM_HEREDOC = 1 +}; + +/* tree element for redirection lists */ + +struct redir { + int type; + int flags; + int fd1, fd2; + char *name; + char *varid; + char *here_terminator; + char *munged_here_terminator; +}; + +/* The number of fds space is allocated for * + * each time a multio must increase in size. */ +#define MULTIOUNIT 8 + +/* A multio is a list of fds associated with a certain fd. * + * Thus if you do "foo >bar >ble", the multio for fd 1 will have * + * two fds, the result of open("bar",...), and the result of * + * open("ble",....). */ + +/* structure used for multiple i/o redirection */ +/* one for each fd open */ + +struct multio { + int ct; /* # of redirections on this fd */ + int rflag; /* 0 if open for reading, 1 if open for writing */ + int pipe; /* fd of pipe if ct > 1 */ + int fds[MULTIOUNIT]; /* list of src/dests redirected to/from this fd */ +}; + +/* lvalue for variable assignment/expansion */ + +struct value { + int isarr; + Param pm; /* parameter node */ + int flags; /* flags defined below */ + int start; /* first element of array slice, or -1 */ + int end; /* 1-rel last element of array slice, or -1 */ + char **arr; /* cache for hash turned into array */ +}; + +enum { + VALFLAG_INV = 0x0001, /* We are performing inverse subscripting */ + VALFLAG_EMPTY = 0x0002, /* Subscripted range is empty */ + VALFLAG_SUBST = 0x0004 /* Substitution, so apply padding, case flags */ +}; + +#define MAX_ARRLEN 262144 + +/********************************************/ +/* Definitions for word code */ +/********************************************/ + +typedef unsigned int wordcode; +typedef wordcode *Wordcode; + +typedef struct funcdump *FuncDump; +typedef struct eprog *Eprog; + +struct funcdump { + FuncDump next; /* next in list */ + dev_t dev; /* device */ + ino_t ino; /* indoe number */ + int fd; /* file descriptor */ + Wordcode map; /* pointer to header */ + Wordcode addr; /* mapped region */ + int len; /* length */ + int count; /* reference count */ + char *filename; +}; + +/* + * A note on the use of reference counts in Eprogs. + * + * When an Eprog is created, nref is set to -1 if the Eprog is on the + * heap; then no attempt is ever made to free it. (This information is + * already present in EF_HEAP; we use the redundancy for debugging + * checks.) + * + * Otherwise, nref is initialised to 1. Calling freeprog() decrements + * nref and frees the Eprog if the count is now zero. When the Eprog + * is in use, we call useeprog() at the start and freeprog() at the + * end to increment and decrement the reference counts. If an attempt + * is made to free the Eprog from within, this will then take place + * when execution is finished, typically in the call to freeeprog() + * in execode(). If the Eprog was on the heap, neither useeprog() + * nor freeeprog() has any effect. + */ +struct eprog { + int flags; /* EF_* below */ + int len; /* total block length */ + int npats; /* Patprog cache size */ + int nref; /* number of references: delete when zero */ + Patprog *pats; /* the memory block, the patterns */ + Wordcode prog; /* memory block ctd, the code */ + char *strs; /* memory block ctd, the strings */ + Shfunc shf; /* shell function for autoload */ + FuncDump dump; /* dump file this is in */ +}; + +#define EF_REAL 1 +#define EF_HEAP 2 +#define EF_MAP 4 +#define EF_RUN 8 + +typedef struct estate *Estate; + +struct estate { + Eprog prog; /* the eprog executed */ + Wordcode pc; /* program counter, current pos */ + char *strs; /* strings from prog */ +}; + +typedef struct eccstr *Eccstr; + +struct eccstr { + Eccstr left, right; + char *str; + wordcode offs, aoffs; + int nfunc; + int hashval; +}; + +#define EC_NODUP 0 +#define EC_DUP 1 +#define EC_DUPTOK 2 + +#define WC_CODEBITS 5 + +#define wc_code(C) ((C) & ((wordcode) ((1 << WC_CODEBITS) - 1))) +#define wc_data(C) ((C) >> WC_CODEBITS) +#define wc_bdata(D) ((D) << WC_CODEBITS) +#define wc_bld(C,D) (((wordcode) (C)) | (((wordcode) (D)) << WC_CODEBITS)) + +#define WC_END 0 +#define WC_LIST 1 +#define WC_SUBLIST 2 +#define WC_PIPE 3 +#define WC_REDIR 4 +#define WC_ASSIGN 5 +#define WC_SIMPLE 6 +#define WC_TYPESET 7 +#define WC_SUBSH 8 +#define WC_CURSH 9 +#define WC_TIMED 10 +#define WC_FUNCDEF 11 +#define WC_FOR 12 +#define WC_SELECT 13 +#define WC_WHILE 14 +#define WC_REPEAT 15 +#define WC_CASE 16 +#define WC_IF 17 +#define WC_COND 18 +#define WC_ARITH 19 +#define WC_AUTOFN 20 +#define WC_TRY 21 + +/* increment as necessary */ +#define WC_COUNT 22 + +#define WCB_END() wc_bld(WC_END, 0) + +#define WC_LIST_TYPE(C) wc_data(C) +#define Z_END (1<<4) +#define Z_SIMPLE (1<<5) +#define WC_LIST_FREE (6) /* Next bit available in integer */ +#define WC_LIST_SKIP(C) (wc_data(C) >> WC_LIST_FREE) +#define WCB_LIST(T,O) wc_bld(WC_LIST, ((T) | ((O) << WC_LIST_FREE))) + +#define WC_SUBLIST_TYPE(C) (wc_data(C) & ((wordcode) 3)) +#define WC_SUBLIST_END 0 +#define WC_SUBLIST_AND 1 +#define WC_SUBLIST_OR 2 +#define WC_SUBLIST_FLAGS(C) (wc_data(C) & ((wordcode) 0x1c)) +#define WC_SUBLIST_COPROC 4 +#define WC_SUBLIST_NOT 8 +#define WC_SUBLIST_SIMPLE 16 +#define WC_SUBLIST_FREE (5) /* Next bit available in integer */ +#define WC_SUBLIST_SKIP(C) (wc_data(C) >> WC_SUBLIST_FREE) +#define WCB_SUBLIST(T,F,O) wc_bld(WC_SUBLIST, \ + ((T) | (F) | ((O) << WC_SUBLIST_FREE))) + +#define WC_PIPE_TYPE(C) (wc_data(C) & ((wordcode) 1)) +#define WC_PIPE_END 0 +#define WC_PIPE_MID 1 +#define WC_PIPE_LINENO(C) (wc_data(C) >> 1) +#define WCB_PIPE(T,L) wc_bld(WC_PIPE, ((T) | ((L) << 1))) + +#define WC_REDIR_TYPE(C) ((int)(wc_data(C) & REDIR_TYPE_MASK)) +#define WC_REDIR_VARID(C) ((int)(wc_data(C) & REDIR_VARID_MASK)) +#define WC_REDIR_FROM_HEREDOC(C) ((int)(wc_data(C) & REDIR_FROM_HEREDOC_MASK)) +#define WCB_REDIR(T) wc_bld(WC_REDIR, (T)) +/* Size of redir is 4 words if REDIR_VARID_MASK is set, else 3 */ +#define WC_REDIR_WORDS(C) \ + ((WC_REDIR_VARID(C) ? 4 : 3) + \ + (WC_REDIR_FROM_HEREDOC(C) ? 2 : 0)) + +#define WC_ASSIGN_TYPE(C) (wc_data(C) & ((wordcode) 1)) +#define WC_ASSIGN_TYPE2(C) ((wc_data(C) & ((wordcode) 2)) >> 1) +#define WC_ASSIGN_SCALAR 0 +#define WC_ASSIGN_ARRAY 1 +#define WC_ASSIGN_NEW 0 +/* + * In normal assignment, this indicate += to append. + * In assignment following a typeset, where that's not allowed, + * we overload this to indicate a variable without an + * assignment. + */ +#define WC_ASSIGN_INC 1 +#define WC_ASSIGN_NUM(C) (wc_data(C) >> 2) +#define WCB_ASSIGN(T,A,N) wc_bld(WC_ASSIGN, ((T) | ((A) << 1) | ((N) << 2))) + +#define WC_SIMPLE_ARGC(C) wc_data(C) +#define WCB_SIMPLE(N) wc_bld(WC_SIMPLE, (N)) + +#define WC_TYPESET_ARGC(C) wc_data(C) +#define WCB_TYPESET(N) wc_bld(WC_TYPESET, (N)) + +#define WC_SUBSH_SKIP(C) wc_data(C) +#define WCB_SUBSH(O) wc_bld(WC_SUBSH, (O)) + +#define WC_CURSH_SKIP(C) wc_data(C) +#define WCB_CURSH(O) wc_bld(WC_CURSH, (O)) + +#define WC_TIMED_TYPE(C) wc_data(C) +#define WC_TIMED_EMPTY 0 +#define WC_TIMED_PIPE 1 +#define WCB_TIMED(T) wc_bld(WC_TIMED, (T)) + +#define WC_FUNCDEF_SKIP(C) wc_data(C) +#define WCB_FUNCDEF(O) wc_bld(WC_FUNCDEF, (O)) + +#define WC_FOR_TYPE(C) (wc_data(C) & 3) +#define WC_FOR_PPARAM 0 +#define WC_FOR_LIST 1 +#define WC_FOR_COND 2 +#define WC_FOR_SKIP(C) (wc_data(C) >> 2) +#define WCB_FOR(T,O) wc_bld(WC_FOR, ((T) | ((O) << 2))) + +#define WC_SELECT_TYPE(C) (wc_data(C) & 1) +#define WC_SELECT_PPARAM 0 +#define WC_SELECT_LIST 1 +#define WC_SELECT_SKIP(C) (wc_data(C) >> 1) +#define WCB_SELECT(T,O) wc_bld(WC_SELECT, ((T) | ((O) << 1))) + +#define WC_WHILE_TYPE(C) (wc_data(C) & 1) +#define WC_WHILE_WHILE 0 +#define WC_WHILE_UNTIL 1 +#define WC_WHILE_SKIP(C) (wc_data(C) >> 1) +#define WCB_WHILE(T,O) wc_bld(WC_WHILE, ((T) | ((O) << 1))) + +#define WC_REPEAT_SKIP(C) wc_data(C) +#define WCB_REPEAT(O) wc_bld(WC_REPEAT, (O)) + +#define WC_TRY_SKIP(C) wc_data(C) +#define WCB_TRY(O) wc_bld(WC_TRY, (O)) + +#define WC_CASE_TYPE(C) (wc_data(C) & 7) +#define WC_CASE_HEAD 0 +#define WC_CASE_OR 1 +#define WC_CASE_AND 2 +#define WC_CASE_TESTAND 3 +#define WC_CASE_FREE (3) /* Next bit available in integer */ +#define WC_CASE_SKIP(C) (wc_data(C) >> WC_CASE_FREE) +#define WCB_CASE(T,O) wc_bld(WC_CASE, ((T) | ((O) << WC_CASE_FREE))) + +#define WC_IF_TYPE(C) (wc_data(C) & 3) +#define WC_IF_HEAD 0 +#define WC_IF_IF 1 +#define WC_IF_ELIF 2 +#define WC_IF_ELSE 3 +#define WC_IF_SKIP(C) (wc_data(C) >> 2) +#define WCB_IF(T,O) wc_bld(WC_IF, ((T) | ((O) << 2))) + +#define WC_COND_TYPE(C) (wc_data(C) & 127) +#define WC_COND_SKIP(C) (wc_data(C) >> 7) +#define WCB_COND(T,O) wc_bld(WC_COND, ((T) | ((O) << 7))) + +#define WCB_ARITH() wc_bld(WC_ARITH, 0) + +#define WCB_AUTOFN() wc_bld(WC_AUTOFN, 0) + +/********************************************/ +/* Definitions for job table and job control */ +/********************************************/ + +/* Entry in filelist linked list in job table */ + +struct jobfile { + /* Record to be deleted or closed */ + union { + char *name; /* Name of file to delete */ + int fd; /* File descriptor to close */ + } u; + /* Discriminant */ + int is_fd; +}; + +/* entry in the job table */ + +struct job { + pid_t gleader; /* process group leader of this job */ + pid_t other; /* subjob id (SUPERJOB) + * or subshell pid (SUBJOB) */ + int stat; /* see STATs below */ + char *pwd; /* current working dir of shell when * + * this job was spawned */ + struct process *procs; /* list of processes */ + struct process *auxprocs; /* auxiliary processes e.g multios */ + LinkList filelist; /* list of files to delete when done */ + /* elements are struct jobfile */ + int stty_in_env; /* if STTY=... is present */ + struct ttyinfo *ty; /* the modes specified by STTY */ +}; + +#define STAT_CHANGED (0x0001) /* status changed and not reported */ +#define STAT_STOPPED (0x0002) /* all procs stopped or exited */ +#define STAT_TIMED (0x0004) /* job is being timed */ +#define STAT_DONE (0x0008) /* job is done */ +#define STAT_LOCKED (0x0010) /* shell is finished creating this job, */ + /* may be deleted from job table */ +#define STAT_NOPRINT (0x0020) /* job was killed internally, */ + /* we don't want to show that */ +#define STAT_INUSE (0x0040) /* this job entry is in use */ +#define STAT_SUPERJOB (0x0080) /* job has a subjob */ +#define STAT_SUBJOB (0x0100) /* job is a subjob */ +#define STAT_WASSUPER (0x0200) /* was a super-job, sub-job needs to be */ + /* deleted */ +#define STAT_CURSH (0x0400) /* last command is in current shell */ +#define STAT_NOSTTY (0x0800) /* the tty settings are not inherited */ + /* from this job when it exits. */ +#define STAT_ATTACH (0x1000) /* delay reattaching shell to tty */ +#define STAT_SUBLEADER (0x2000) /* is super-job, but leader is sub-shell */ + +#define STAT_BUILTIN (0x4000) /* job at tail of pipeline is a builtin */ +#define STAT_SUBJOB_ORPHANED (0x8000) + /* STAT_SUBJOB with STAT_SUPERJOB exited */ +#define STAT_DISOWN (0x10000) /* STAT_SUPERJOB with disown pending */ + +#define SP_RUNNING -1 /* fake status for jobs currently running */ + +struct timeinfo { + long ut; /* user space time */ + long st; /* system space time */ +}; + +#define JOBTEXTSIZE 80 + +/* Size to initialise the job table to, and to increment it by when needed. */ +#define MAXJOBS_ALLOC (50) + +/* node in job process lists */ + +#ifdef HAVE_GETRUSAGE +typedef struct rusage child_times_t; +#else +typedef struct timeinfo child_times_t; +#endif + +struct process { + struct process *next; + pid_t pid; /* process id */ + char text[JOBTEXTSIZE]; /* text to print when 'jobs' is run */ + int status; /* return code from waitpid/wait3() */ + child_times_t ti; + struct timeval bgtime; /* time job was spawned */ + struct timeval endtime; /* time job exited */ +}; + +struct execstack { + struct execstack *next; + + pid_t list_pipe_pid; + int nowait; + int pline_level; + int list_pipe_child; + int list_pipe_job; + char list_pipe_text[JOBTEXTSIZE]; + int lastval; + int noeval; + int badcshglob; + pid_t cmdoutpid; + int cmdoutval; + int use_cmdoutval; + pid_t procsubstpid; + int trap_return; + int trap_state; + int trapisfunc; + int traplocallevel; + int noerrs; + int this_noerrexit; + char *underscore; +}; + +struct heredocs { + struct heredocs *next; + int type; + int pc; + char *str; +}; + +struct dirsav { + int dirfd, level; + char *dirname; + dev_t dev; + ino_t ino; +}; + +#define MAX_PIPESTATS 256 + +/*******************************/ +/* Definitions for Hash Tables */ +/*******************************/ + +typedef void *(*VFunc) _((void *)); +typedef void (*FreeFunc) _((void *)); + +typedef unsigned (*HashFunc) _((const char *)); +typedef void (*TableFunc) _((HashTable)); +/* + * Note that this is deliberately "char *", not "const char *", + * since the AddNodeFunc is passed a pointer to a string that + * will be stored and later freed. + */ +typedef void (*AddNodeFunc) _((HashTable, char *, void *)); +typedef HashNode (*GetNodeFunc) _((HashTable, const char *)); +typedef HashNode (*RemoveNodeFunc) _((HashTable, const char *)); +typedef void (*FreeNodeFunc) _((HashNode)); +typedef int (*CompareFunc) _((const char *, const char *)); + +/* type of function that is passed to * + * scanhashtable or scanmatchtable */ +typedef void (*ScanFunc) _((HashNode, int)); +typedef void (*ScanTabFunc) _((HashTable, ScanFunc, int)); + +typedef void (*PrintTableStats) _((HashTable)); + +/* hash table for standard open hashing */ + +struct hashtable { + /* HASHTABLE DATA */ + int hsize; /* size of nodes[] (number of hash values) */ + int ct; /* number of elements */ + HashNode *nodes; /* array of size hsize */ + void *tmpdata; + + /* HASHTABLE METHODS */ + HashFunc hash; /* pointer to hash function for this table */ + TableFunc emptytable; /* pointer to function to empty table */ + TableFunc filltable; /* pointer to function to fill table */ + CompareFunc cmpnodes; /* pointer to function to compare two nodes */ + AddNodeFunc addnode; /* pointer to function to add new node */ + GetNodeFunc getnode; /* pointer to function to get an enabled node */ + GetNodeFunc getnode2; /* pointer to function to get node */ + /* (getnode2 will ignore DISABLED flag) */ + RemoveNodeFunc removenode; /* pointer to function to delete a node */ + ScanFunc disablenode; /* pointer to function to disable a node */ + ScanFunc enablenode; /* pointer to function to enable a node */ + FreeNodeFunc freenode; /* pointer to function to free a node */ + ScanFunc printnode; /* pointer to function to print a node */ + ScanTabFunc scantab; /* pointer to function to scan table */ + +#ifdef HASHTABLE_INTERNAL_MEMBERS + HASHTABLE_INTERNAL_MEMBERS /* internal use in hashtable.c */ +#endif +}; + +/* generic hash table node */ + +struct hashnode { + HashNode next; /* next in hash chain */ + char *nam; /* hash key */ + int flags; /* various flags */ +}; + +/* The flag to disable nodes in a hash table. Currently * + * you can disable builtins, shell functions, aliases and * + * reserved words. */ +#define DISABLED (1<<0) + +/* node in shell option table */ + +struct optname { + struct hashnode node; + int optno; /* option number */ +}; + +/* node in shell reserved word hash table (reswdtab) */ + +struct reswd { + struct hashnode node; + int token; /* corresponding lexer token */ +}; + +/* node in alias hash table (aliastab) */ + +struct alias { + struct hashnode node; + char *text; /* expansion of alias */ + int inuse; /* alias is being expanded */ +}; + +/* bit 0 of flags is the DISABLED flag */ +/* is this alias global? */ +#define ALIAS_GLOBAL (1<<1) +/* is this an alias for suffix handling? */ +#define ALIAS_SUFFIX (1<<2) + +/* structure for foo=bar assignments */ + +struct asgment { + struct linknode node; + char *name; + int flags; + union { + char *scalar; + LinkList array; + } value; +}; + +/* Flags for flags element of asgment */ +enum { + /* Array value */ + ASG_ARRAY = 1, + /* Key / value array pair */ + ASG_KEY_VALUE = 2 +}; + +/* + * Assignment is array? + */ +#define ASG_ARRAYP(asg) ((asg)->flags & ASG_ARRAY) + +/* + * Assignment has value? + * If the assignment is an arrray, then it certainly has a value --- we + * can only tell if there's an expicit assignment. + */ + +#define ASG_VALUEP(asg) (ASG_ARRAYP(asg) || \ + ((asg)->value.scalar != (char *)0)) + +/* node in command path hash table (cmdnamtab) */ + +struct cmdnam { + struct hashnode node; + union { + char **name; /* full pathname for external commands */ + char *cmd; /* file name for hashed commands */ + } + u; +}; + +/* flag for nodes explicitly added to * + * cmdnamtab with hash builtin */ +#define HASHED (1<<1) + +/* node in shell function hash table (shfunctab) */ + +struct shfunc { + struct hashnode node; + char *filename; /* Name of file located in. + For not yet autoloaded file, name + of explicit directory, if not NULL. */ + zlong lineno; /* line number in above file */ + Eprog funcdef; /* function definition */ + Eprog redir; /* redirections to apply */ + Emulation_options sticky; /* sticky emulation definitions, if any */ +}; + +/* Shell function context types. */ + +#define SFC_NONE 0 /* no function running */ +#define SFC_DIRECT 1 /* called directly from the user */ +#define SFC_SIGNAL 2 /* signal handler */ +#define SFC_HOOK 3 /* one of the special functions */ +#define SFC_WIDGET 4 /* user defined widget */ +#define SFC_COMPLETE 5 /* called from completion code */ +#define SFC_CWIDGET 6 /* new style completion widget */ +#define SFC_SUBST 7 /* used to perform substitution task */ + +/* tp in funcstack */ + +enum { + FS_SOURCE, + FS_FUNC, + FS_EVAL +}; + +/* node in function stack */ + +struct funcstack { + Funcstack prev; /* previous in stack */ + char *name; /* name of function/sourced file called */ + char *filename; /* file function resides in */ + char *caller; /* name of caller */ + zlong flineno; /* line number in file */ + zlong lineno; /* line offset from beginning of function */ + int tp; /* type of entry: sourced file, func, eval */ +}; + +/* node in list of function call wrappers */ + +typedef int (*WrapFunc) _((Eprog, FuncWrap, char *)); + +struct funcwrap { + FuncWrap next; + int flags; + WrapFunc handler; + Module module; +}; + +#define WRAPF_ADDED 1 + +#define WRAPDEF(func) \ + { NULL, 0, func, NULL } + +/* + * User-defined hook arrays + */ + +/* Name appended to function name to get hook array */ +#define HOOK_SUFFIX "_functions" +/* Length of that including NUL byte */ +#define HOOK_SUFFIX_LEN 11 + +/* node in builtin command hash table (builtintab) */ + +/* + * Handling of options. + * + * Option strings are standard in that a trailing `:' indicates + * a mandatory argument. In addition, `::' indicates an optional + * argument which must immediately follow the option letter if it is present. + * `:%' indicates an optional numeric argument which may follow + * the option letter or be in the next word; the only test is + * that the next character is a digit, and no actual conversion is done. + */ + +#define MAX_OPS 128 + +/* Macros taking struct option * and char argument */ +/* Option was set as -X */ +#define OPT_MINUS(ops,c) ((ops)->ind[c] & 1) +/* Option was set as +X */ +#define OPT_PLUS(ops,c) ((ops)->ind[c] & 2) +/* + * Option was set any old how, maybe including an argument + * (cheap test when we don't care). Some bits of code + * expect this to be 1 or 0. + */ +#define OPT_ISSET(ops,c) ((ops)->ind[c] != 0) +/* Option has an argument */ +#define OPT_HASARG(ops,c) ((ops)->ind[c] > 3) +/* The argument for the option; not safe if it doesn't have one */ +#define OPT_ARG(ops,c) ((ops)->args[((ops)->ind[c] >> 2) - 1]) +/* Ditto, but safely returns NULL if there is no argument. */ +#define OPT_ARG_SAFE(ops,c) (OPT_HASARG(ops,c) ? OPT_ARG(ops,c) : NULL) + +struct options { + unsigned char ind[MAX_OPS]; + char **args; + int argscount, argsalloc; +}; + +/* Flags to parseargs() */ + +enum { + PARSEARGS_TOPLEVEL = 0x1, /* Call to initialise shell */ + PARSEARGS_LOGIN = 0x2 /* Shell is login shell */ +}; + + +/* + * Handler arguments are: builtin name, null-terminated argument + * list excluding command name, option structure, the funcid element from the + * builtin structure. + */ + +typedef int (*HandlerFunc) _((char *, char **, Options, int)); +typedef int (*HandlerFuncAssign) _((char *, char **, LinkList, Options, int)); +#define NULLBINCMD ((HandlerFunc) 0) + +struct builtin { + struct hashnode node; + HandlerFunc handlerfunc; /* pointer to function that executes this builtin */ + int minargs; /* minimum number of arguments */ + int maxargs; /* maximum number of arguments, or -1 for no limit */ + int funcid; /* xbins (see above) for overloaded handlerfuncs */ + char *optstr; /* string of legal options */ + char *defopts; /* options set by default for overloaded handlerfuncs */ +}; + +#define BUILTIN(name, flags, handler, min, max, funcid, optstr, defopts) \ + { { NULL, name, flags }, handler, min, max, funcid, optstr, defopts } +#define BIN_PREFIX(name, flags) \ + BUILTIN(name, flags | BINF_PREFIX, NULLBINCMD, 0, 0, 0, NULL, NULL) + +/* builtin flags */ +/* DISABLE IS DEFINED AS (1<<0) */ +#define BINF_PLUSOPTS (1<<1) /* +xyz legal */ +#define BINF_PRINTOPTS (1<<2) +#define BINF_ADDED (1<<3) /* is in the builtins hash table */ +#define BINF_MAGICEQUALS (1<<4) /* needs automatic MAGIC_EQUAL_SUBST substitution */ +#define BINF_PREFIX (1<<5) +#define BINF_DASH (1<<6) +#define BINF_BUILTIN (1<<7) +#define BINF_COMMAND (1<<8) +#define BINF_EXEC (1<<9) +#define BINF_NOGLOB (1<<10) +#define BINF_PSPECIAL (1<<11) +/* Builtin option handling */ +#define BINF_SKIPINVALID (1<<12) /* Treat invalid option as argument */ +#define BINF_KEEPNUM (1<<13) /* `[-+]NUM' can be an option */ +#define BINF_SKIPDASH (1<<14) /* Treat `-' as argument (maybe `+') */ +#define BINF_DASHDASHVALID (1<<15) /* Handle `--' even if SKIPINVALD */ +#define BINF_CLEARENV (1<<16) /* new process started with cleared env */ +#define BINF_AUTOALL (1<<17) /* autoload all features at once */ + /* + * Handles options itself. This is only useful if the option string for a + * builtin with an empty option string. It is used to indicate that "--" + * does not terminate options. + */ +#define BINF_HANDLES_OPTS (1<<18) +/* + * Handles the assignement interface. The argv list actually contains + * two nested litsts, the first of normal arguments, and the second of + * assignment structures. + */ +#define BINF_ASSIGN (1<<19) + +/** + * Parameters passed to execcmd(). + * These are not opaque --- they are also used by the pipeline manager. + */ +struct execcmd_params { + LinkList args; /* All command prefixes, arguments & options */ + LinkList redir; /* Redirections */ + Wordcode beg; /* The code at the start of the command */ + Wordcode varspc; /* The code for assignment parsed as such */ + Wordcode assignspc; /* The code for assignment parsed as typeset */ + int type; /* The WC_* type of the command */ + int postassigns; /* The number of assignspc assiguments */ + int htok; /* tokens in parameter list */ +}; + +struct module { + struct hashnode node; + union { + void *handle; + Linkedmod linked; + char *alias; + } u; + LinkList autoloads; + LinkList deps; + int wrapper; +}; + +/* We are in the process of loading the module */ +#define MOD_BUSY (1<<0) +/* + * We are in the process of unloading the module. + * Note this is not needed to indicate a module is actually + * unloaded: for that, the handle (or linked pointer) is set to NULL. + */ +#define MOD_UNLOAD (1<<1) +/* We are in the process of setting up the module */ +#define MOD_SETUP (1<<2) +/* Module is statically linked into the main binary */ +#define MOD_LINKED (1<<3) +/* Module setup has been carried out (and module has not been finished) */ +#define MOD_INIT_S (1<<4) +/* Module boot has been carried out (and module has not been finished) */ +#define MOD_INIT_B (1<<5) +/* Module record is an alias */ +#define MOD_ALIAS (1<<6) + +typedef int (*Module_generic_func) _((void)); +typedef int (*Module_void_func) _((Module)); +typedef int (*Module_features_func) _((Module, char ***)); +typedef int (*Module_enables_func) _((Module, int **)); + +struct linkedmod { + char *name; + Module_void_func setup; + Module_features_func features; + Module_enables_func enables; + Module_void_func boot; + Module_void_func cleanup; + Module_void_func finish; +}; + +/* + * Structure combining all the concrete features available in + * a module and with space for information about abstract features. + */ +struct features { + /* List of builtins provided by the module and the size thereof */ + Builtin bn_list; + int bn_size; + /* List of conditions provided by the module and the size thereof */ + Conddef cd_list; + int cd_size; + /* List of math functions provided by the module and the size thereof */ + MathFunc mf_list; + int mf_size; + /* List of parameters provided by the module and the size thereof */ + Paramdef pd_list; + int pd_size; + /* Number of abstract features */ + int n_abstract; +}; + +/* + * Structure describing enables for one feature. + */ +struct feature_enables { + /* String feature to enable (N.B. no leading +/- allowed) */ + char *str; + /* Optional compiled pattern for str sans +/-, NULL for string match */ + Patprog pat; +}; + +/* C-function hooks */ + +typedef int (*Hookfn) _((Hookdef, void *)); + +struct hookdef { + Hookdef next; + char *name; + Hookfn def; + int flags; + LinkList funcs; +}; + +#define HOOKF_ALL 1 + +#define HOOKDEF(name, func, flags) { NULL, name, (Hookfn) func, flags, NULL } + +/* + * Types used in pattern matching. Most of these longs could probably + * happily be ints. + */ + +struct patprog { + long startoff; /* length before start of programme */ + long size; /* total size from start of struct */ + long mustoff; /* offset to string that must be present */ + long patmlen; /* length of pure string or longest match */ + int globflags; /* globbing flags to set at start */ + int globend; /* globbing flags set after finish */ + int flags; /* PAT_* flags */ + int patnpar; /* number of active parentheses */ + char patstartch; +}; + +struct patstralloc { + int unmetalen; /* Unmetafied length of trial string */ + int unmetalenp; /* Unmetafied length of path prefix. + If 0, no path prefix. */ + char *alloced; /* Allocated string, may be NULL */ + char *progstrunmeta; /* Unmetafied pure string in pattern, cached */ + int progstrunmetalen; /* Length of the foregoing */ +}; + +/* Flags used in pattern matchers (Patprog) and passed down to patcompile */ + +#define PAT_HEAPDUP 0x0000 /* Dummy flag for default behavior */ +#define PAT_FILE 0x0001 /* Pattern is a file name */ +#define PAT_FILET 0x0002 /* Pattern is top level file, affects ~ */ +#define PAT_ANY 0x0004 /* Match anything (cheap "*") */ +#define PAT_NOANCH 0x0008 /* Not anchored at end */ +#define PAT_NOGLD 0x0010 /* Don't glob dots */ +#define PAT_PURES 0x0020 /* Pattern is a pure string: set internally */ +#define PAT_STATIC 0x0040 /* Don't copy pattern to heap as per default */ +#define PAT_SCAN 0x0080 /* Scanning, so don't try must-match test */ +#define PAT_ZDUP 0x0100 /* Copy pattern in real memory */ +#define PAT_NOTSTART 0x0200 /* Start of string is not real start */ +#define PAT_NOTEND 0x0400 /* End of string is not real end */ +#define PAT_HAS_EXCLUDP 0x0800 /* (internal): top-level path1~path2. */ +#define PAT_LCMATCHUC 0x1000 /* equivalent to setting (#l) */ + +/** + * Indexes into the array of active pattern characters. + * This must match the array zpc_chars in pattern.c. + */ +enum zpc_chars { + /* + * These characters both terminate a pattern segment and + * a pure string segment. + */ + ZPC_SLASH, /* / active as file separator */ + ZPC_NULL, /* \0 as string terminator */ + ZPC_BAR, /* | for "or" */ + ZPC_OUTPAR, /* ) for grouping */ + ZPC_TILDE, /* ~ for exclusion (extended glob) */ + ZPC_SEG_COUNT, /* No. of the above characters */ + /* + * These characters terminate a pure string segment. + */ + ZPC_INPAR = ZPC_SEG_COUNT, /* ( for grouping */ + ZPC_QUEST, /* ? as wildcard */ + ZPC_STAR, /* * as wildcard */ + ZPC_INBRACK, /* [ for character class */ + ZPC_INANG, /* < for numeric glob */ + ZPC_HAT, /* ^ for exclusion (extended glob) */ + ZPC_HASH, /* # for repetition (extended glob) */ + ZPC_BNULLKEEP, /* Special backslashed null not removed */ + /* + * These characters are only valid before a parenthesis + */ + ZPC_NO_KSH_GLOB, + ZPC_KSH_QUEST = ZPC_NO_KSH_GLOB, /* ? for ?(...) in KSH_GLOB */ + ZPC_KSH_STAR, /* * for *(...) in KSH_GLOB */ + ZPC_KSH_PLUS, /* + for +(...) in KSH_GLOB */ + ZPC_KSH_BANG, /* ! for !(...) in KSH_GLOB */ + ZPC_KSH_BANG2, /* ! for !(...) in KSH_GLOB, untokenised */ + ZPC_KSH_AT, /* @ for @(...) in KSH_GLOB */ + ZPC_COUNT /* Number of special chararacters */ +}; + +/* + * Structure to save disables special characters for function scope. + */ +struct zpc_disables_save { + struct zpc_disables_save *next; + /* + * Bit vector of ZPC_COUNT disabled characters. + * We'll live dangerously and assume ZPC_COUNT is no greater + * than the number of bits in an unsigned int. + */ + unsigned int disables; +}; + +typedef struct zpc_disables_save *Zpc_disables_save; + +/* + * Special match types used in character classes. These + * are represented as tokens, with Meta added. The character + * class is represented as a metafied string, with only these + * tokens special. Note that an active leading "!" or "^" for + * negation is not part of the string but is flagged in the + * surrounding context. + * + * These types are also used in character and equivalence classes + * in completion matching. + * + * This must be kept ordered by the array colon_stuffs in pattern.c. + */ +/* Special value for first definition */ +#define PP_FIRST 1 +/* POSIX-defined types: [:alpha:] etc. */ +#define PP_ALPHA 1 +#define PP_ALNUM 2 +#define PP_ASCII 3 +#define PP_BLANK 4 +#define PP_CNTRL 5 +#define PP_DIGIT 6 +#define PP_GRAPH 7 +#define PP_LOWER 8 +#define PP_PRINT 9 +#define PP_PUNCT 10 +#define PP_SPACE 11 +#define PP_UPPER 12 +#define PP_XDIGIT 13 +/* Zsh additions: [:IDENT:] etc. */ +#define PP_IDENT 14 +#define PP_IFS 15 +#define PP_IFSSPACE 16 +#define PP_WORD 17 +#define PP_INCOMPLETE 18 +#define PP_INVALID 19 +/* Special value for last definition */ +#define PP_LAST 19 + +/* Unknown type. Not used in a valid token. */ +#define PP_UNKWN 20 +/* Range: token followed by the (possibly multibyte) start and end */ +#define PP_RANGE 21 + +/* + * Argument to get_match_ret() in glob.c + */ +struct imatchdata { + /* Metafied trial string */ + char *mstr; + /* Its length */ + int mlen; + /* Unmetafied string */ + char *ustr; + /* Its length */ + int ulen; + /* Flags (SUB_*) */ + int flags; + /* Replacement string (metafied) */ + char *replstr; + /* + * List of bits of matches to concatenate with replacement string. + * The data is a struct repldata. It is not used in cases like + * ${...//#foo/bar} even though SUB_GLOBAL is set, since the match + * is anchored. It goes on the heap. + */ + LinkList repllist; +}; + +/* Globbing flags: lower 8 bits gives approx count */ +#define GF_LCMATCHUC 0x0100 +#define GF_IGNCASE 0x0200 +#define GF_BACKREF 0x0400 +#define GF_MATCHREF 0x0800 +#define GF_MULTIBYTE 0x1000 /* Use multibyte if supported by build */ + +enum { + /* Valid multibyte character from charref */ + ZMB_VALID, + /* Incomplete multibyte character from charref */ + ZMB_INCOMPLETE, + /* Invalid multibyte character charref */ + ZMB_INVALID +}; + +/* Dummy Patprog pointers. Used mainly in executable code, but the + * pattern code needs to know about it, too. */ + +#define dummy_patprog1 ((Patprog) 1) +#define dummy_patprog2 ((Patprog) 2) + +/* standard node types for get/set/unset union in parameter */ + +/* + * note non-standard const in pointer declaration: structures are + * assumed to be read-only. + */ +typedef const struct gsu_scalar *GsuScalar; +typedef const struct gsu_integer *GsuInteger; +typedef const struct gsu_float *GsuFloat; +typedef const struct gsu_array *GsuArray; +typedef const struct gsu_hash *GsuHash; + +struct gsu_scalar { + char *(*getfn) _((Param)); + void (*setfn) _((Param, char *)); + void (*unsetfn) _((Param, int)); +}; + +struct gsu_integer { + zlong (*getfn) _((Param)); + void (*setfn) _((Param, zlong)); + void (*unsetfn) _((Param, int)); +}; + +struct gsu_float { + double (*getfn) _((Param)); + void (*setfn) _((Param, double)); + void (*unsetfn) _((Param, int)); +}; + +struct gsu_array { + char **(*getfn) _((Param)); + void (*setfn) _((Param, char **)); + void (*unsetfn) _((Param, int)); +}; + +struct gsu_hash { + HashTable (*getfn) _((Param)); + void (*setfn) _((Param, HashTable)); + void (*unsetfn) _((Param, int)); +}; + + +/* node used in parameter hash table (paramtab) */ + +struct param { + struct hashnode node; + + /* the value of this parameter */ + union { + void *data; /* used by special parameter functions */ + char **arr; /* value if declared array (PM_ARRAY) */ + char *str; /* value if declared string (PM_SCALAR) */ + zlong val; /* value if declared integer (PM_INTEGER) */ + zlong *valptr; /* value if special pointer to integer */ + double dval; /* value if declared float + (PM_EFLOAT|PM_FFLOAT) */ + HashTable hash; /* value if declared assoc (PM_HASHED) */ + } u; + + /* + * get/set/unset methods. + * + * Unlike the data union, this points to a single instance + * for every type (although there are special types, e.g. + * tied arrays have a different gsu_scalar struct from the + * normal one). It's really a poor man's vtable. + */ + union { + GsuScalar s; + GsuInteger i; + GsuFloat f; + GsuArray a; + GsuHash h; + } gsu; + + int base; /* output base or floating point prec */ + int width; /* field width */ + char *env; /* location in environment, if exported */ + char *ename; /* name of corresponding environment var */ + Param old; /* old struct for use with local */ + int level; /* if (old != NULL), level of localness */ +}; + +/* structure stored in struct param's u.data by tied arrays */ +struct tieddata { + char ***arrptr; /* pointer to corresponding array */ + int joinchar; /* character used to join arrays */ +}; + +/* flags for parameters */ + +/* parameter types */ +#define PM_SCALAR 0 /* scalar */ +#define PM_ARRAY (1<<0) /* array */ +#define PM_INTEGER (1<<1) /* integer */ +#define PM_EFLOAT (1<<2) /* double with %e output */ +#define PM_FFLOAT (1<<3) /* double with %f output */ +#define PM_HASHED (1<<4) /* association */ + +#define PM_TYPE(X) \ + (X & (PM_SCALAR|PM_INTEGER|PM_EFLOAT|PM_FFLOAT|PM_ARRAY|PM_HASHED)) + +#define PM_LEFT (1<<5) /* left justify, remove leading blanks */ +#define PM_RIGHT_B (1<<6) /* right justify, fill with leading blanks */ +#define PM_RIGHT_Z (1<<7) /* right justify, fill with leading zeros */ +#define PM_LOWER (1<<8) /* all lower case */ + +/* The following are the same since they * + * both represent -u option to typeset */ +#define PM_UPPER (1<<9) /* all upper case */ +#define PM_UNDEFINED (1<<9) /* undefined (autoloaded) shell function */ + +#define PM_READONLY (1<<10) /* readonly */ +#define PM_TAGGED (1<<11) /* tagged */ +#define PM_EXPORTED (1<<12) /* exported */ +#define PM_ABSPATH_USED (1<<12) /* (function): loaded using absolute path */ + +/* The following are the same since they * + * both represent -U option to typeset */ +#define PM_UNIQUE (1<<13) /* remove duplicates */ +#define PM_UNALIASED (1<<13) /* do not expand aliases when autoloading */ + +#define PM_HIDE (1<<14) /* Special behaviour hidden by local */ +#define PM_CUR_FPATH (1<<14) /* (function): can use $fpath with filename */ +#define PM_HIDEVAL (1<<15) /* Value not shown in `typeset' commands */ +#define PM_WARNNESTED (1<<15) /* (function): non-recursive WARNNESTEDVAR */ +#define PM_TIED (1<<16) /* array tied to colon-path or v.v. */ +#define PM_TAGGED_LOCAL (1<<16) /* (function): non-recursive PM_TAGGED */ + +#define PM_KSHSTORED (1<<17) /* function stored in ksh form */ +#define PM_ZSHSTORED (1<<18) /* function stored in zsh form */ + +/* Remaining flags do not correspond directly to command line arguments */ +#define PM_DONTIMPORT_SUID (1<<19) /* do not import if running setuid */ +#define PM_LOADDIR (1<<19) /* (function) filename gives load directory */ +#define PM_SINGLE (1<<20) /* special can only have a single instance */ +#define PM_ANONYMOUS (1<<20) /* (function) anonymous function */ +#define PM_LOCAL (1<<21) /* this parameter will be made local */ +#define PM_SPECIAL (1<<22) /* special builtin parameter */ +#define PM_DONTIMPORT (1<<23) /* do not import this variable */ +#define PM_RESTRICTED (1<<24) /* cannot be changed in restricted mode */ +#define PM_UNSET (1<<25) /* has null value */ +#define PM_REMOVABLE (1<<26) /* special can be removed from paramtab */ +#define PM_AUTOLOAD (1<<27) /* autoloaded from module */ +#define PM_NORESTORE (1<<28) /* do not restore value of local special */ +#define PM_AUTOALL (1<<28) /* autoload all features in module + * when loading: valid only if PM_AUTOLOAD + * is also present. + */ +#define PM_HASHELEM (1<<29) /* is a hash-element */ +#define PM_NAMEDDIR (1<<30) /* has a corresponding nameddirtab entry */ + +/* The option string corresponds to the first of the variables above */ +#define TYPESET_OPTSTR "aiEFALRZlurtxUhHTkz" + +/* These typeset options take an optional numeric argument */ +#define TYPESET_OPTNUM "LRZiEF" + +/* Flags for extracting elements of arrays and associative arrays */ +#define SCANPM_WANTVALS (1<<0) /* Return value includes hash values */ +#define SCANPM_WANTKEYS (1<<1) /* Return value includes hash keys */ +#define SCANPM_WANTINDEX (1<<2) /* Return value includes array index */ +#define SCANPM_MATCHKEY (1<<3) /* Subscript matched against key */ +#define SCANPM_MATCHVAL (1<<4) /* Subscript matched against value */ +#define SCANPM_MATCHMANY (1<<5) /* Subscript matched repeatedly, return all */ +#define SCANPM_ASSIGNING (1<<6) /* Assigning whole array/hash */ +#define SCANPM_KEYMATCH (1<<7) /* keys of hash treated as patterns */ +#define SCANPM_DQUOTED (1<<8) /* substitution was double-quoted + * (only used for testing early end of + * subscript) + */ +#define SCANPM_ARRONLY (1<<9) /* value is array but we don't + * necessarily want to match multiple + * elements + */ +#define SCANPM_CHECKING (1<<10) /* Check if set, no need to create */ +/* "$foo[@]"-style substitution + * Only sign bit is significant + */ +#define SCANPM_ISVAR_AT ((int)(((unsigned int)-1)<<15)) + +/* + * Flags for doing matches inside parameter substitutions, i.e. + * ${...#...} and friends. This could be an enum, but so + * could a lot of other things. + */ + +#define SUB_END 0x0001 /* match end instead of beginning, % or %% */ +#define SUB_LONG 0x0002 /* % or # doubled, get longest match */ +#define SUB_SUBSTR 0x0004 /* match a substring */ +#define SUB_MATCH 0x0008 /* include the matched portion */ +#define SUB_REST 0x0010 /* include the unmatched portion */ +#define SUB_BIND 0x0020 /* index of beginning of string */ +#define SUB_EIND 0x0040 /* index of end of string */ +#define SUB_LEN 0x0080 /* length of match */ +#define SUB_ALL 0x0100 /* match complete string */ +#define SUB_GLOBAL 0x0200 /* global substitution ${..//all/these} */ +#define SUB_DOSUBST 0x0400 /* replacement string needs substituting */ +#define SUB_RETFAIL 0x0800 /* return status 0 if no match */ +#define SUB_START 0x1000 /* force match at start with SUB_END + * and no SUB_SUBSTR */ +#define SUB_LIST 0x2000 /* no substitution, return list of matches */ + +/* + * Structure recording multiple matches inside a test string. + * b and e are the beginning and end of the match. + * replstr is the replacement string, if any. + */ +struct repldata { + int b, e; /* beginning and end of chunk to replace */ + char *replstr; /* replacement string to use */ +}; +typedef struct repldata *Repldata; + +/* + * Flags to zshtokenize. + */ +enum { + /* Do glob substitution */ + ZSHTOK_SUBST = 0x0001, + /* Use sh-style globbing */ + ZSHTOK_SHGLOB = 0x0002 +}; + +/* Flags as the second argument to prefork */ +enum { + /* argument handled like typeset foo=bar */ + PREFORK_TYPESET = 0x01, + /* argument handled like the RHS of foo=bar */ + PREFORK_ASSIGN = 0x02, + /* single word substitution */ + PREFORK_SINGLE = 0x04, + /* explicitly split nested substitution */ + PREFORK_SPLIT = 0x08, + /* SHWORDSPLIT in parameter expn */ + PREFORK_SHWORDSPLIT = 0x10, + /* SHWORDSPLIT forced off in nested subst */ + PREFORK_NOSHWORDSPLIT = 0x20, + /* Prefork is part of a parameter subexpression */ + PREFORK_SUBEXP = 0x40, + /* Prefork detected an assignment list with [key]=value syntax, + * Only used on return from prefork, not meaningful passed down. + * Also used as flag to globlist. + */ + PREFORK_KEY_VALUE = 0x80, + /* No untokenise: used only as flag to globlist */ + PREFORK_NO_UNTOK = 0x100 +}; + +/* + * Bit flags passed back from multsub() to paramsubst(). + * Some flags go from a nested parmsubst() through the enclosing + * stringsubst() and prefork(). + */ +enum { + /* + * Set if the string had whitespace at the start + * that should cause word splitting against any preceeding string. + */ + MULTSUB_WS_AT_START = 1, + /* + * Set if the string had whitespace at the end + * that should cause word splitting against any following string. + */ + MULTSUB_WS_AT_END = 2, + /* + * Set by nested paramsubst() to indicate the return + * value is a parameter name, rather than a value. + */ + MULTSUB_PARAM_NAME = 4 +}; + +/* + * Structure for adding parameters in a module. + * The flags should declare the type; note PM_SCALAR is zero. + * + * Special hashes are recognized by getnfn so the PM_HASHED + * is optional. These get slightly non-standard attention: + * the function createspecialhash is used to create them. + * + * The get/set/unset attribute may be NULL; in that case the + * parameter is assigned methods suitable for handling the + * tie variable var, if that is not NULL, else standard methods. + * + * pm is set when the parameter is added to the parameter table + * and serves as a flag that the parameter has been added. + */ +struct paramdef { + char *name; + int flags; + void *var; /* tied internal variable, if any */ + const void *gsu; /* get/set/unset structure, if special */ + GetNodeFunc getnfn; /* function to get node, if special hash */ + ScanTabFunc scantfn; /* function to scan table, if special hash */ + Param pm; /* structure inserted into param table */ +}; + +/* + * Shorthand for common uses of adding parameters, with no special + * hash properties. + */ +#define PARAMDEF(name, flags, var, gsu) \ + { name, flags, (void *) var, (void *) gsu, \ + NULL, NULL, NULL \ + } +/* + * Note that the following definitions are appropriate for defining + * parameters that reference a variable (var). Hence the get/set/unset + * methods used will assume var needs dereferencing to get the value. + */ +#define INTPARAMDEF(name, var) \ + { name, PM_INTEGER, (void *) var, NULL, NULL, NULL, NULL } +#define STRPARAMDEF(name, var) \ + { name, PM_SCALAR, (void *) var, NULL, NULL, NULL, NULL } +#define ARRPARAMDEF(name, var) \ + { name, PM_ARRAY, (void *) var, NULL, NULL, NULL, NULL } +/* + * The following is appropriate for a module function that behaves + * in a special fashion. Parameters used in a module that don't + * have special behaviour shouldn't be declared in a table but + * should just be added with the standard parameter functions. + * + * These parameters are not marked as removable, since they + * shouldn't be loaded as local parameters, unlike the special + * Zle parameters that are added and removed on each call to Zle. + * We add the PM_REMOVABLE flag when removing the feature corresponding + * to the parameter. + */ +#define SPECIALPMDEF(name, flags, gsufn, getfn, scanfn) \ + { name, flags | PM_SPECIAL | PM_HIDE | PM_HIDEVAL, \ + NULL, gsufn, getfn, scanfn, NULL } + +/* + * Flags for assignsparam and assignaparam. + */ +enum { + /* Add to rather than override value */ + ASSPM_AUGMENT = 1 << 0, + /* Test for warning if creating global variable in function */ + ASSPM_WARN_CREATE = 1 << 1, + /* Test for warning if using nested variable in function */ + ASSPM_WARN_NESTED = 1 << 2, + ASSPM_WARN = (ASSPM_WARN_CREATE|ASSPM_WARN_NESTED), + /* Import from environment, so exercise care evaluating value */ + ASSPM_ENV_IMPORT = 1 << 3, + /* Array is key / value pairs. + * This is normal for associative arrays but variant behaviour for + * normal arrays. + */ + ASSPM_KEY_VALUE = 1 << 4 +}; + +/* node for named directory hash table (nameddirtab) */ + +struct nameddir { + struct hashnode node; + char *dir; /* the directory in full */ + int diff; /* strlen(.dir) - strlen(.nam) */ +}; + +/* flags for named directories */ +/* DISABLED is defined (1<<0) */ +#define ND_USERNAME (1<<1) /* nam is actually a username */ +#define ND_NOABBREV (1<<2) /* never print as abbrev (PWD or OLDPWD) */ + +/* Storage for single group/name mapping */ +typedef struct { + /* Name of group */ + char *name; + /* Group identifier */ + gid_t gid; +} groupmap; +typedef groupmap *Groupmap; + +/* Storage for a set of group/name mappings */ +typedef struct { + /* The set of name to gid mappings */ + Groupmap array; + /* A count of the valid entries in groupmap. */ + int num; +} groupset; +typedef groupset *Groupset; + +/* flags for controlling printing of hash table nodes */ +#define PRINT_NAMEONLY (1<<0) +#define PRINT_TYPE (1<<1) +#define PRINT_LIST (1<<2) +#define PRINT_KV_PAIR (1<<3) +#define PRINT_INCLUDEVALUE (1<<4) +#define PRINT_TYPESET (1<<5) +#define PRINT_LINE (1<<6) + +/* flags for printing for the whence builtin */ +#define PRINT_WHENCE_CSH (1<<7) +#define PRINT_WHENCE_VERBOSE (1<<8) +#define PRINT_WHENCE_SIMPLE (1<<9) +#define PRINT_WHENCE_FUNCDEF (1<<10) +#define PRINT_WHENCE_WORD (1<<11) + +/* Return values from loop() */ + +enum loop_return { + /* Loop executed OK */ + LOOP_OK, + /* Loop executed no code */ + LOOP_EMPTY, + /* Loop encountered an error */ + LOOP_ERROR +}; + +/* Return values from source() */ + +enum source_return { + /* Source ran OK */ + SOURCE_OK = 0, + /* File not found */ + SOURCE_NOT_FOUND = 1, + /* Internal error sourcing file */ + SOURCE_ERROR = 2 +}; + +enum noerrexit_bits { + /* Suppress ERR_EXIT and traps: global */ + NOERREXIT_EXIT = 1, + /* Suppress ERR_RETURN: per function call */ + NOERREXIT_RETURN = 2, + /* NOERREXIT only needed on way down */ + NOERREXIT_UNTIL_EXEC = 4, + /* Force exit on SIGINT */ + NOERREXIT_SIGNAL = 8 +}; + +/***********************************/ +/* Definitions for history control */ +/***********************************/ + +/* history entry */ + +struct histent { + struct hashnode node; + + Histent up; /* previous line (moving upward) */ + Histent down; /* next line (moving downward) */ + char *zle_text; /* the edited history line, + * a metafied, NULL-terminated string, + * i.e the same format as the original + * entry + */ + time_t stim; /* command started time (datestamp) */ + time_t ftim; /* command finished time */ + short *words; /* Position of words in history */ + /* line: as pairs of start, end */ + int nwords; /* Number of words in history line */ + zlong histnum; /* A sequential history number */ +}; + +#define HIST_MAKEUNIQUE 0x00000001 /* Kill this new entry if not unique */ +#define HIST_OLD 0x00000002 /* Command is already written to disk*/ +#define HIST_READ 0x00000004 /* Command was read back from disk*/ +#define HIST_DUP 0x00000008 /* Command duplicates a later line */ +#define HIST_FOREIGN 0x00000010 /* Command came from another shell */ +#define HIST_TMPSTORE 0x00000020 /* Kill when user enters another cmd */ +#define HIST_NOWRITE 0x00000040 /* Keep internally but don't write */ + +#define GETHIST_UPWARD (-1) +#define GETHIST_DOWNWARD 1 +#define GETHIST_EXACT 0 + +/* Parts of the code where history expansion is disabled * + * should be within a pair of STOPHIST ... ALLOWHIST */ + +#define STOPHIST (stophist += 4); +#define ALLOWHIST (stophist -= 4); + +#define HISTFLAG_DONE 1 +#define HISTFLAG_NOEXEC 2 +#define HISTFLAG_RECALL 4 +#define HISTFLAG_SETTY 8 + +#define HFILE_APPEND 0x0001 +#define HFILE_SKIPOLD 0x0002 +#define HFILE_SKIPDUPS 0x0004 +#define HFILE_SKIPFOREIGN 0x0008 +#define HFILE_FAST 0x0010 +#define HFILE_NO_REWRITE 0x0020 +#define HFILE_USE_OPTIONS 0x8000 + +/* + * Flags argument to bufferwords() used + * also by lexflags variable. + */ +/* + * Kick the lexer into special string-analysis + * mode without parsing. Any bit set in + * the flags has this effect, but this + * has otherwise all the default effects. + */ +#define LEXFLAGS_ACTIVE 0x0001 +/* + * Being used from zle. This is slightly more intrusive + * (=> grotesquely non-modular) than use from within + * the main shell, so it's a separate flag. + */ +#define LEXFLAGS_ZLE 0x0002 +/* + * Parse comments and treat each comment as a single string + */ +#define LEXFLAGS_COMMENTS_KEEP 0x0004 +/* + * Parse comments and strip them. + */ +#define LEXFLAGS_COMMENTS_STRIP 0x0008 +/* + * Either of the above + */ +#define LEXFLAGS_COMMENTS (LEXFLAGS_COMMENTS_KEEP|LEXFLAGS_COMMENTS_STRIP) +/* + * Treat newlines as whitespace + */ +#define LEXFLAGS_NEWLINE 0x0010 + +/******************************************/ +/* Definitions for programable completion */ +/******************************************/ + +/* Nothing special. */ +#define IN_NOTHING 0 +/* In command position. */ +#define IN_CMD 1 +/* In a mathematical environment. */ +#define IN_MATH 2 +/* In a condition. */ +#define IN_COND 3 +/* In a parameter assignment (e.g. `foo=bar'). */ +#define IN_ENV 4 +/* In a parameter name in an assignment. */ +#define IN_PAR 5 + + +/******************************/ +/* Definition for zsh options */ +/******************************/ + +/* Possible values of emulation */ + +#define EMULATE_CSH (1<<1) /* C shell */ +#define EMULATE_KSH (1<<2) /* Korn shell */ +#define EMULATE_SH (1<<3) /* Bourne shell */ +#define EMULATE_ZSH (1<<4) /* `native' mode */ + +/* Test for a shell emulation. Use this rather than emulation directly. */ +#define EMULATION(X) (emulation & (X)) + +/* Return only base shell emulation field. */ +#define SHELL_EMULATION() (emulation & ((1<<5)-1)) + +/* Additional flags */ + +#define EMULATE_FULLY (1<<5) /* "emulate -R" in effect */ +/* + * Higher bits are used in options.c, record lowest unused bit... + */ +#define EMULATE_UNUSED (1<<6) + +/* option indices */ + +enum { + OPT_INVALID, + ALIASESOPT, + ALIASFUNCDEF, + ALLEXPORT, + ALWAYSLASTPROMPT, + ALWAYSTOEND, + APPENDHISTORY, + AUTOCD, + AUTOCONTINUE, + AUTOLIST, + AUTOMENU, + AUTONAMEDIRS, + AUTOPARAMKEYS, + AUTOPARAMSLASH, + AUTOPUSHD, + AUTOREMOVESLASH, + AUTORESUME, + BADPATTERN, + BANGHIST, + BAREGLOBQUAL, + BASHAUTOLIST, + BASHREMATCH, + BEEP, + BGNICE, + BRACECCL, + BSDECHO, + CASEGLOB, + CASEMATCH, + CBASES, + CDABLEVARS, + CHASEDOTS, + CHASELINKS, + CHECKJOBS, + CHECKRUNNINGJOBS, + CLOBBER, + APPENDCREATE, + COMBININGCHARS, + COMPLETEALIASES, + COMPLETEINWORD, + CORRECT, + CORRECTALL, + CONTINUEONERROR, + CPRECEDENCES, + CSHJUNKIEHISTORY, + CSHJUNKIELOOPS, + CSHJUNKIEQUOTES, + CSHNULLCMD, + CSHNULLGLOB, + DEBUGBEFORECMD, + EMACSMODE, + EQUALS, + ERREXIT, + ERRRETURN, + EXECOPT, + EXTENDEDGLOB, + EXTENDEDHISTORY, + EVALLINENO, + FLOWCONTROL, + FORCEFLOAT, + FUNCTIONARGZERO, + GLOBOPT, + GLOBALEXPORT, + GLOBALRCS, + GLOBASSIGN, + GLOBCOMPLETE, + GLOBDOTS, + GLOBSTARSHORT, + GLOBSUBST, + HASHCMDS, + HASHDIRS, + HASHEXECUTABLESONLY, + HASHLISTALL, + HISTALLOWCLOBBER, + HISTBEEP, + HISTEXPIREDUPSFIRST, + HISTFCNTLLOCK, + HISTFINDNODUPS, + HISTIGNOREALLDUPS, + HISTIGNOREDUPS, + HISTIGNORESPACE, + HISTLEXWORDS, + HISTNOFUNCTIONS, + HISTNOSTORE, + HISTREDUCEBLANKS, + HISTSAVEBYCOPY, + HISTSAVENODUPS, + HISTSUBSTPATTERN, + HISTVERIFY, + HUP, + IGNOREBRACES, + IGNORECLOSEBRACES, + IGNOREEOF, + INCAPPENDHISTORY, + INCAPPENDHISTORYTIME, + INTERACTIVE, + INTERACTIVECOMMENTS, + KSHARRAYS, + KSHAUTOLOAD, + KSHGLOB, + KSHOPTIONPRINT, + KSHTYPESET, + KSHZEROSUBSCRIPT, + LISTAMBIGUOUS, + LISTBEEP, + LISTPACKED, + LISTROWSFIRST, + LISTTYPES, + LOCALLOOPS, + LOCALOPTIONS, + LOCALPATTERNS, + LOCALTRAPS, + LOGINSHELL, + LONGLISTJOBS, + MAGICEQUALSUBST, + MAILWARNING, + MARKDIRS, + MENUCOMPLETE, + MONITOR, + MULTIBYTE, + MULTIFUNCDEF, + MULTIOS, + NOMATCH, + NOTIFY, + NULLGLOB, + NUMERICGLOBSORT, + OCTALZEROES, + OVERSTRIKE, + PATHDIRS, + PATHSCRIPT, + PIPEFAIL, + POSIXALIASES, + POSIXARGZERO, + POSIXBUILTINS, + POSIXCD, + POSIXIDENTIFIERS, + POSIXJOBS, + POSIXSTRINGS, + POSIXTRAPS, + PRINTEIGHTBIT, + PRINTEXITVALUE, + PRIVILEGED, + PROMPTBANG, + PROMPTCR, + PROMPTPERCENT, + PROMPTSP, + PROMPTSUBST, + PUSHDIGNOREDUPS, + PUSHDMINUS, + PUSHDSILENT, + PUSHDTOHOME, + RCEXPANDPARAM, + RCQUOTES, + RCS, + RECEXACT, + REMATCHPCRE, + RESTRICTED, + RMSTARSILENT, + RMSTARWAIT, + SHAREHISTORY, + SHFILEEXPANSION, + SHGLOB, + SHINSTDIN, + SHNULLCMD, + SHOPTIONLETTERS, + SHORTLOOPS, + SHWORDSPLIT, + SINGLECOMMAND, + SINGLELINEZLE, + SOURCETRACE, + SUNKEYBOARDHACK, + TRANSIENTRPROMPT, + TRAPSASYNC, + TYPESETSILENT, + UNSET, + VERBOSE, + VIMODE, + WARNCREATEGLOBAL, + WARNNESTEDVAR, + XTRACE, + USEZLE, + DVORAK, + OPT_SIZE +}; + +/* + * Size required to fit an option number. + * If OPT_SIZE goes above 256 this will need to expand. + */ +typedef unsigned char OptIndex; + +#undef isset +#define isset(X) (opts[X]) +#define unset(X) (!opts[X]) + +#define interact (isset(INTERACTIVE)) +#define jobbing (isset(MONITOR)) +#define islogin (isset(LOGINSHELL)) + +/* + * Record of emulation and options that need to be set + * for a full "emulate". + */ +struct emulation_options { + /* The emulation itself */ + int emulation; + /* The number of options in on_opts. */ + int n_on_opts; + /* The number of options in off_opts. */ + int n_off_opts; + /* + * Array of options to be turned on. + * Only options specified explicitly in the emulate command + * are recorded. Null if n_on_opts is zero. + */ + OptIndex *on_opts; + /* Array of options to be turned off, similar. */ + OptIndex *off_opts; +}; + +/***********************************************/ +/* Definitions for terminal and display control */ +/***********************************************/ + +/* tty state structure */ + +struct ttyinfo { +#ifdef HAVE_TERMIOS_H + struct termios tio; +#else +# ifdef HAVE_TERMIO_H + struct termio tio; +# else + struct sgttyb sgttyb; + int lmodes; + struct tchars tchars; + struct ltchars ltchars; +# endif +#endif +#ifdef TIOCGWINSZ + struct winsize winsize; +#endif +}; + +#ifndef __INTERIX +/* defines for whether tabs expand to spaces */ +#if defined(HAVE_TERMIOS_H) || defined(HAVE_TERMIO_H) +#define SGTTYFLAG shttyinfo.tio.c_oflag +#else /* we're using sgtty */ +#define SGTTYFLAG shttyinfo.sgttyb.sg_flags +#endif +# ifdef TAB3 +#define SGTABTYPE TAB3 +# else +# ifdef OXTABS +#define SGTABTYPE OXTABS +# else +# ifdef XTABS +#define SGTABTYPE XTABS +# endif +# endif +# endif +#endif + +/* flags for termflags */ + +#define TERM_BAD 0x01 /* terminal has extremely basic capabilities */ +#define TERM_UNKNOWN 0x02 /* unknown terminal type */ +#define TERM_NOUP 0x04 /* terminal has no up capability */ +#define TERM_SHORT 0x08 /* terminal is < 3 lines high */ +#define TERM_NARROW 0x10 /* terminal is < 3 columns wide */ + +/* interesting termcap strings */ + +#define TCCLEARSCREEN 0 +#define TCLEFT 1 +#define TCMULTLEFT 2 +#define TCRIGHT 3 +#define TCMULTRIGHT 4 +#define TCUP 5 +#define TCMULTUP 6 +#define TCDOWN 7 +#define TCMULTDOWN 8 +#define TCDEL 9 +#define TCMULTDEL 10 +#define TCINS 11 +#define TCMULTINS 12 +#define TCCLEAREOD 13 +#define TCCLEAREOL 14 +#define TCINSLINE 15 +#define TCDELLINE 16 +#define TCNEXTTAB 17 +#define TCBOLDFACEBEG 18 +#define TCSTANDOUTBEG 19 +#define TCUNDERLINEBEG 20 +#define TCALLATTRSOFF 21 +#define TCSTANDOUTEND 22 +#define TCUNDERLINEEND 23 +#define TCHORIZPOS 24 +#define TCUPCURSOR 25 +#define TCDOWNCURSOR 26 +#define TCLEFTCURSOR 27 +#define TCRIGHTCURSOR 28 +#define TCSAVECURSOR 29 +#define TCRESTRCURSOR 30 +#define TCBACKSPACE 31 +#define TCFGCOLOUR 32 +#define TCBGCOLOUR 33 +#define TC_COUNT 34 + +#define tccan(X) (tclen[X]) + +/* + * Text attributes for displaying in ZLE + */ + +#define TXTBOLDFACE 0x0001 +#define TXTSTANDOUT 0x0002 +#define TXTUNDERLINE 0x0004 +#define TXTFGCOLOUR 0x0008 +#define TXTBGCOLOUR 0x0010 + +#define TXT_ATTR_ON_MASK 0x001F + +#define txtisset(X) (txtattrmask & (X)) +#define txtset(X) (txtattrmask |= (X)) +#define txtunset(X) (txtattrmask &= ~(X)) + +#define TXTNOBOLDFACE 0x0020 +#define TXTNOSTANDOUT 0x0040 +#define TXTNOUNDERLINE 0x0080 +#define TXTNOFGCOLOUR 0x0100 +#define TXTNOBGCOLOUR 0x0200 + +#define TXT_ATTR_OFF_MASK 0x03E0 +/* Bits to shift off right to get on */ +#define TXT_ATTR_OFF_ON_SHIFT 5 +#define TXT_ATTR_OFF_FROM_ON(attr) \ + (((attr) & TXT_ATTR_ON_MASK) << TXT_ATTR_OFF_ON_SHIFT) +#define TXT_ATTR_ON_FROM_OFF(attr) \ + (((attr) & TXT_ATTR_OFF_MASK) >> TXT_ATTR_OFF_ON_SHIFT) +/* + * Indicates to zle_refresh.c that the character entry is an + * index into the list of multiword symbols. + */ +#define TXT_MULTIWORD_MASK 0x0400 + +/* Mask for colour to use in foreground */ +#define TXT_ATTR_FG_COL_MASK 0x000FF000 +/* Bits to shift the foreground colour */ +#define TXT_ATTR_FG_COL_SHIFT (12) +/* Mask for colour to use in background */ +#define TXT_ATTR_BG_COL_MASK 0x0FF00000 +/* Bits to shift the background colour */ +#define TXT_ATTR_BG_COL_SHIFT (20) + +/* Flag to use termcap AF sequence to set colour, if available */ +#define TXT_ATTR_FG_TERMCAP 0x10000000 +/* Flag to use termcap AB sequence to set colour, if available */ +#define TXT_ATTR_BG_TERMCAP 0x20000000 + +/* Things to turn on, including values for the colour elements */ +#define TXT_ATTR_ON_VALUES_MASK \ + (TXT_ATTR_ON_MASK|TXT_ATTR_FG_COL_MASK|TXT_ATTR_BG_COL_MASK|\ + TXT_ATTR_FG_TERMCAP|TXT_ATTR_BG_TERMCAP) + +/* Mask out everything to do with setting a foreground colour */ +#define TXT_ATTR_FG_ON_MASK \ + (TXTFGCOLOUR|TXT_ATTR_FG_COL_MASK|TXT_ATTR_FG_TERMCAP) + +/* Mask out everything to do with setting a background colour */ +#define TXT_ATTR_BG_ON_MASK \ + (TXTBGCOLOUR|TXT_ATTR_BG_COL_MASK|TXT_ATTR_BG_TERMCAP) + +/* Mask out everything to do with activating colours */ +#define TXT_ATTR_COLOUR_ON_MASK \ + (TXT_ATTR_FG_ON_MASK|TXT_ATTR_BG_ON_MASK) + +#define txtchangeisset(T,X) ((T) & (X)) +#define txtchangeget(T,A) (((T) & A ## _MASK) >> A ## _SHIFT) +#define txtchangeset(T, X, Y) ((void)(T && (*T &= ~(Y), *T |= (X)))) + +/* + * For outputting sequences to change colour: specify foreground + * or background. + */ +#define COL_SEQ_FG (0) +#define COL_SEQ_BG (1) +#define COL_SEQ_COUNT (2) + +/* + * Flags to testcap() and set_colour_attribute (which currently only + * handles TSC_PROMPT). + */ +enum { + /* Raw output: use stdout rather than shout */ + TSC_RAW = 0x0001, + /* Output to current prompt buffer: only used when assembling prompt */ + TSC_PROMPT = 0x0002, + /* Mask to get the output mode */ + TSC_OUTPUT_MASK = 0x0003, + /* Change needs reset of other attributes */ + TSC_DIRTY = 0x0004 +}; + +/****************************************/ +/* Definitions for the %_ prompt escape */ +/****************************************/ + +#define CMDSTACKSZ 256 + +#define CS_FOR 0 +#define CS_WHILE 1 +#define CS_REPEAT 2 +#define CS_SELECT 3 +#define CS_UNTIL 4 +#define CS_IF 5 +#define CS_IFTHEN 6 +#define CS_ELSE 7 +#define CS_ELIF 8 +#define CS_MATH 9 +#define CS_COND 10 +#define CS_CMDOR 11 +#define CS_CMDAND 12 +#define CS_PIPE 13 +#define CS_ERRPIPE 14 +#define CS_FOREACH 15 +#define CS_CASE 16 +#define CS_FUNCDEF 17 +#define CS_SUBSH 18 +#define CS_CURSH 19 +#define CS_ARRAY 20 +#define CS_QUOTE 21 +#define CS_DQUOTE 22 +#define CS_BQUOTE 23 +#define CS_CMDSUBST 24 +#define CS_MATHSUBST 25 +#define CS_ELIFTHEN 26 +#define CS_HEREDOC 27 +#define CS_HEREDOCD 28 +#define CS_BRACE 29 +#define CS_BRACEPAR 30 +#define CS_ALWAYS 31 + +/* Increment as necessary */ +#define CS_COUNT 32 + +/********************* + * Memory management * + *********************/ + +/* + * A Heapid is a type for identifying, uniquely up to the point where + * the count of new identifiers wraps. all heaps that are or + * (importantly) have been valid. Each valid heap is given an + * identifier, and every time we push a heap we save the old identifier + * and give the heap a new identifier so that when the heap is popped + * or freed we can spot anything using invalid memory from the popped + * heap. + * + * We could make this unsigned long long if we wanted a big range. + */ +typedef unsigned int Heapid; + +#ifdef ZSH_HEAP_DEBUG + +/* printf format specifier corresponding to Heapid */ +#define HEAPID_FMT "%x" + +/* Marker that memory is permanently allocated */ +#define HEAPID_PERMANENT (UINT_MAX) + +/* + * Heap debug verbosity. + * Bits to be 'or'ed into the variable also called heap_debug_verbosity. + */ +enum heap_debug_verbosity { + /* Report when we push a heap */ + HDV_PUSH = 0x01, + /* Report when we pop a heap */ + HDV_POP = 0x02, + /* Report when we create a new heap from which to allocate */ + HDV_CREATE = 0x04, + /* Report every time we free a complete heap */ + HDV_FREE = 0x08, + /* Report when we temporarily install a new set of heaps */ + HDV_NEW = 0x10, + /* Report when we restore an old set of heaps */ + HDV_OLD = 0x20, + /* Report when we temporarily switch heaps */ + HDV_SWITCH = 0x40, + /* + * Report every time we allocate memory from the heap. + * This is very verbose, and arguably not very useful: we + * would expect to allocate memory from a heap we create. + * For much debugging heap_debug_verbosity = 0x7f should be sufficient. + */ + HDV_ALLOC = 0x80 +}; + +#define HEAP_ERROR(heap_id) \ + fprintf(stderr, "%s:%d: HEAP DEBUG: invalid heap: " HEAPID_FMT ".\n", \ + __FILE__, __LINE__, heap_id) +#endif + +/* heappush saves the current heap state using this structure */ + +struct heapstack { + struct heapstack *next; /* next one in list for this heap */ + size_t used; +#ifdef ZSH_HEAP_DEBUG + Heapid heap_id; +#endif +}; + +/* A zsh heap. */ + +struct heap { + struct heap *next; /* next one */ + size_t size; /* size of heap */ + size_t used; /* bytes used from the heap */ + struct heapstack *sp; /* used by pushheap() to save the value used */ + +#ifdef ZSH_HEAP_DEBUG + unsigned int heap_id; +#endif + +/* Uncomment the following if the struct needs padding to 64-bit size. */ +/* Make sure sizeof(heap) is a multiple of 8 +#if defined(PAD_64_BIT) && !defined(__GNUC__) + size_t dummy; +#endif +*/ +#define arena(X) ((char *) (X) + sizeof(struct heap)) +} +#if defined(PAD_64_BIT) && defined(__GNUC__) + __attribute__ ((aligned (8))) +#endif +; + +# define NEWHEAPS(h) do { Heap _switch_oldheaps = h = new_heaps(); do +# define OLDHEAPS while (0); old_heaps(_switch_oldheaps); } while (0); + +# define SWITCHHEAPS(o, h) do { o = switch_heaps(h); do +# define SWITCHBACKHEAPS(o) while (0); switch_heaps(o); } while (0); + +/****************/ +/* Debug macros */ +/****************/ + +#ifdef DEBUG +#define STRINGIFY_LITERAL(x) # x +#define STRINGIFY(x) STRINGIFY_LITERAL(x) +#define ERRMSG(x) (__FILE__ ":" STRINGIFY(__LINE__) ": " x) +# define DPUTS(X,Y) if (!(X)) {;} else dputs(ERRMSG(Y)) +# define DPUTS1(X,Y,Z1) if (!(X)) {;} else dputs(ERRMSG(Y), Z1) +# define DPUTS2(X,Y,Z1,Z2) if (!(X)) {;} else dputs(ERRMSG(Y), Z1, Z2) +# define DPUTS3(X,Y,Z1,Z2,Z3) if (!(X)) {;} else dputs(ERRMSG(Y), Z1, Z2, Z3) +#else +# define DPUTS(X,Y) +# define DPUTS1(X,Y,Z1) +# define DPUTS2(X,Y,Z1,Z2) +# define DPUTS3(X,Y,Z1,Z2,Z3) +#endif + +/**************************/ +/* Signal handling macros */ +/**************************/ + +/* These used in the sigtrapped[] array */ + +#define ZSIG_TRAPPED (1<<0) /* Signal is trapped */ +#define ZSIG_IGNORED (1<<1) /* Signal is ignored */ +#define ZSIG_FUNC (1<<2) /* Trap is a function, not an eval list */ +/* Mask to get the above flags */ +#define ZSIG_MASK (ZSIG_TRAPPED|ZSIG_IGNORED|ZSIG_FUNC) +/* No. of bits to shift local level when storing in sigtrapped */ +#define ZSIG_ALIAS (1<<3) /* Trap is stored under an alias */ +#define ZSIG_SHIFT 4 + +/* + * State of traps, stored in trap_state. + */ +enum trap_state { + /* Traps are not active; trap_return is not useful. */ + TRAP_STATE_INACTIVE, + /* + * Traps are set but haven't triggered; trap_return gives + * minus function depth. + */ + TRAP_STATE_PRIMED, + /* + * Trap has triggered to force a return; trap_return givens + * return value. + */ + TRAP_STATE_FORCE_RETURN +}; + +#define IN_EVAL_TRAP() \ + (intrap && !trapisfunc && traplocallevel == locallevel) + +/* + * Bits in the errflag variable. + */ +enum errflag_bits { + /* + * Standard internal error bit. + */ + ERRFLAG_ERROR = 1, + /* + * User interrupt. + */ + ERRFLAG_INT = 2, + /* + * Hard error --- return to top-level prompt in interactive + * shell. In non-interactive shell we'll typically already + * have exited. This is reset by "errflag = 0" in + * loop(toplevel = 1, ...). + */ + ERRFLAG_HARD = 4 +}; + +/***********/ +/* Sorting */ +/***********/ + +typedef int (*CompareFn) _((const void *, const void *)); + +enum { + SORTIT_ANYOLDHOW = 0, /* Defaults */ + SORTIT_IGNORING_CASE = 1, + SORTIT_NUMERICALLY = 2, + SORTIT_BACKWARDS = 4, + /* + * Ignore backslashes that quote another character---which may + * be another backslash; the second backslash is active. + */ + SORTIT_IGNORING_BACKSLASHES = 8, + /* + * Ignored by strmetasort(); used by paramsubst() to indicate + * there is some sorting to do. + */ + SORTIT_SOMEHOW = 16, +}; + +/* + * Element of array passed to qsort(). + */ +struct sortelt { + /* The original string. */ + char *orig; + /* The string used for comparison. */ + const char *cmp; + /* + * The length of the string if passed down to the sort algorithm. + * Used to sort the lengths together with the strings. + */ + int origlen; + /* + * The length of the string, if needed, else -1. + * The length is only needed if there are embededded nulls. + */ + int len; +}; + +typedef struct sortelt *SortElt; + +/*********************************************************/ +/* Structures to save and restore for individual modules */ +/*********************************************************/ + +/* History */ +struct hist_stack { + int histactive; + int histdone; + int stophist; + int hlinesz; + zlong defev; + char *hline; + char *hptr; + short *chwords; + int chwordlen; + int chwordpos; + int (*hgetc) _((void)); + void (*hungetc) _((int)); + void (*hwaddc) _((int)); + void (*hwbegin) _((int)); + void (*hwabort) _((void)); + void (*hwend) _((void)); + void (*addtoline) _((int)); + unsigned char *cstack; + int csp; + int hist_keep_comment; +}; + +/* + * State of a lexical token buffer. + * + * It would be neater to include the pointer to the start of the buffer, + * however the current code structure means that the standard instance + * of this, tokstr, is visible in lots of places, so that's not + * convenient. + */ + +struct lexbufstate { + /* + * Next character to be added. + * Set to NULL when the buffer is to be visible from elsewhere. + */ + char *ptr; + /* Allocated buffer size */ + int siz; + /* Length in use */ + int len; +}; + +/* Lexical analyser */ +struct lex_stack { + int dbparens; + int isfirstln; + int isfirstch; + int lexflags; + enum lextok tok; + char *tokstr; + char *zshlextext; + struct lexbufstate lexbuf; + int lex_add_raw; + char *tokstr_raw; + struct lexbufstate lexbuf_raw; + int lexstop; + zlong toklineno; +}; + +/* Parser */ +struct parse_stack { + struct heredocs *hdocs; + + int incmdpos; + int aliasspaceflag; + int incond; + int inredir; + int incasepat; + int isnewlin; + int infor; + int inrepeat_; + int intypeset; + + int eclen, ecused, ecnpats; + Wordcode ecbuf; + Eccstr ecstrs; + int ecsoffs, ecssub, ecnfunc; +}; + +/************************/ +/* Flags to casemodifiy */ +/************************/ + +enum { + CASMOD_NONE, /* dummy for tests */ + CASMOD_UPPER, + CASMOD_LOWER, + CASMOD_CAPS +}; + +/*******************************************/ +/* Flags to third argument of getkeystring */ +/*******************************************/ + +/* + * By default handles some subset of \-escapes. The following bits + * turn on extra features. + */ +enum { + /* + * Handle octal where the first digit is non-zero e.g. \3, \33, \333 + * Otherwise \0333 etc. is handled, i.e. one of \0123 or \123 will + * work, but not both. + */ + GETKEY_OCTAL_ESC = (1 << 0), + /* + * Handle Emacs-like key sequences \C-x etc. + * Also treat \E like \e and use backslashes to escape the + * next character if not special, i.e. do all the things we + * don't do with the echo builtin. + */ + GETKEY_EMACS = (1 << 1), + /* Handle ^X etc. */ + GETKEY_CTRL = (1 << 2), + /* Handle \c (uses misc arg to getkeystring()) */ + GETKEY_BACKSLASH_C = (1 << 3), + /* Do $'...' quoting (len arg to getkeystring() not used) */ + GETKEY_DOLLAR_QUOTE = (1 << 4), + /* Handle \- (uses misc arg to getkeystring()) */ + GETKEY_BACKSLASH_MINUS = (1 << 5), + /* Parse only one character (len arg to getkeystring() not used) */ + GETKEY_SINGLE_CHAR = (1 << 6), + /* + * If beyond offset in misc arg, add 1 to it for each character removed. + * Yes, I know that doesn't seem to make much sense. + * It's for use in completion, comprenez? + */ + GETKEY_UPDATE_OFFSET = (1 << 7), + /* + * When replacing numeric escapes for printf format strings, % -> %% + */ + GETKEY_PRINTF_PERCENT = (1 << 8) +}; + +/* + * Standard combinations used within the shell. + * Note GETKEYS_... instead of GETKEY_...: this is important in some cases. + */ +/* echo builtin */ +#define GETKEYS_ECHO (GETKEY_BACKSLASH_C) +/* printf format string: \123 -> S, \0123 -> NL 3, \045 -> %% */ +#define GETKEYS_PRINTF_FMT \ + (GETKEY_OCTAL_ESC|GETKEY_BACKSLASH_C|GETKEY_PRINTF_PERCENT) +/* printf argument: \123 -> \123, \0123 -> S */ +#define GETKEYS_PRINTF_ARG (GETKEY_BACKSLASH_C) +/* Full print without -e */ +#define GETKEYS_PRINT (GETKEY_OCTAL_ESC|GETKEY_BACKSLASH_C|GETKEY_EMACS) +/* bindkey */ +#define GETKEYS_BINDKEY (GETKEY_OCTAL_ESC|GETKEY_EMACS|GETKEY_CTRL) +/* $'...' */ +#define GETKEYS_DOLLARS_QUOTE (GETKEY_OCTAL_ESC|GETKEY_EMACS|GETKEY_DOLLAR_QUOTE) +/* Single character for math processing */ +#define GETKEYS_MATH \ + (GETKEY_OCTAL_ESC|GETKEY_EMACS|GETKEY_CTRL|GETKEY_SINGLE_CHAR) +/* Used to process separators etc. with print-style escapes */ +#define GETKEYS_SEP (GETKEY_OCTAL_ESC|GETKEY_EMACS) +/* Used for suffix removal */ +#define GETKEYS_SUFFIX \ + (GETKEY_OCTAL_ESC|GETKEY_EMACS|GETKEY_CTRL|GETKEY_BACKSLASH_MINUS) + +/**********************************/ +/* Flags to third argument of zle */ +/**********************************/ + +#define ZLRF_HISTORY 0x01 /* OK to access the history list */ +#define ZLRF_NOSETTY 0x02 /* Don't set tty before return */ +#define ZLRF_IGNOREEOF 0x04 /* Ignore an EOF from the keyboard */ + +/***************************/ +/* Context of zleread call */ +/***************************/ + +enum { + ZLCON_LINE_START, /* Command line at PS1 */ + ZLCON_LINE_CONT, /* Command line at PS2 */ + ZLCON_SELECT, /* Select loop */ + ZLCON_VARED /* Vared command */ +}; + +/****************/ +/* Entry points */ +/****************/ + +/* compctl entry point pointers */ + +typedef int (*CompctlReadFn) _((char *, char **, Options, char *)); + +/* ZLE entry point pointer */ + +typedef char * (*ZleEntryPoint)(int cmd, va_list ap); + +/* Commands to pass to entry point */ + +enum { + ZLE_CMD_GET_LINE, + ZLE_CMD_READ, + ZLE_CMD_ADD_TO_LINE, + ZLE_CMD_TRASH, + ZLE_CMD_RESET_PROMPT, + ZLE_CMD_REFRESH, + ZLE_CMD_SET_KEYMAP, + ZLE_CMD_GET_KEY, + ZLE_CMD_SET_HIST_LINE +}; + +/***************************************/ +/* Hooks in core. */ +/***************************************/ + +#define EXITHOOK (zshhooks + 0) +#define BEFORETRAPHOOK (zshhooks + 1) +#define AFTERTRAPHOOK (zshhooks + 2) + +#ifdef MULTIBYTE_SUPPORT +/* Final argument to mb_niceformat() */ +enum { + NICEFLAG_HEAP = 1, /* Heap allocation where needed */ + NICEFLAG_QUOTE = 2, /* Result will appear in $'...' */ + NICEFLAG_NODUP = 4, /* Leave allocated */ +}; + +/* Metafied input */ +#define nicezputs(str, outs) (void)mb_niceformat((str), (outs), NULL, 0) +#define MB_METACHARINIT() mb_charinit() +typedef wint_t convchar_t; +#define MB_METACHARLENCONV(str, cp) mb_metacharlenconv((str), (cp)) +#define MB_METACHARLEN(str) mb_metacharlenconv(str, NULL) +#define MB_METASTRLEN(str) mb_metastrlenend(str, 0, NULL) +#define MB_METASTRWIDTH(str) mb_metastrlenend(str, 1, NULL) +#define MB_METASTRLEN2(str, widthp) mb_metastrlenend(str, widthp, NULL) +#define MB_METASTRLEN2END(str, widthp, eptr) \ + mb_metastrlenend(str, widthp, eptr) + +/* Unmetafined input */ +#define MB_CHARINIT() mb_charinit() +#define MB_CHARLENCONV(str, len, cp) mb_charlenconv((str), (len), (cp)) +#define MB_CHARLEN(str, len) mb_charlenconv((str), (len), NULL) + +/* + * We replace broken implementations with one that uses Unicode + * characters directly as wide characters. In principle this is only + * likely to work if __STDC_ISO_10646__ is defined, since that's pretty + * much what the definition tells us. However, we happen to know this + * works on MacOS which doesn't define that. + */ +#ifdef ENABLE_UNICODE9 +#define WCWIDTH(wc) u9_wcwidth(wc) +#else +#define WCWIDTH(wc) wcwidth(wc) +#endif +/* + * Note WCWIDTH_WINT() takes wint_t, typically as a convchar_t. + * It's written to use the wint_t from mb_metacharlenconv() without + * further tests. + * + * This version has a non-multibyte definition that simply returns + * 1. We never expose WCWIDTH() in the non-multibyte world since + * it's just a proxy for wcwidth() itself. + */ +#define WCWIDTH_WINT(wc) zwcwidth(wc) + +#define MB_INCOMPLETE ((size_t)-2) +#define MB_INVALID ((size_t)-1) + +/* + * MB_CUR_MAX is the maximum number of bytes that a single wide + * character will convert into. We use it to keep strings + * sufficiently long. It should always be defined, but if it isn't + * just assume we are using Unicode which requires 6 characters. + * (Note that it's not necessarily defined to a constant.) + */ +#ifndef MB_CUR_MAX +#define MB_CUR_MAX 6 +#endif + +/* Convert character or string to wide character or string */ +#define ZWC(c) L ## c +#define ZWS(s) L ## s + +/* + * Test for a combining character. + * + * wc is assumed to be a wchar_t (i.e. we don't need zwcwidth). + * + * Pedantic note: in Unicode, a combining character need not be + * zero length. However, we are concerned here about display; + * we simply need to know whether the character will be displayed + * on top of another one. We use "combining character" in this + * sense throughout the shell. I am not aware of a way of + * detecting the Unicode trait in standard libraries. + */ +#define IS_COMBINING(wc) (wc != 0 && WCWIDTH(wc) == 0) +/* + * Test for the base of a combining character. + * + * We assume a combining character can be successfully displayed with + * any non-space printable character, which is what a graphic character + * is, as long as it has non-zero width. We need to avoid all forms of + * space because the shell will split words on any whitespace. + */ +#define IS_BASECHAR(wc) (iswgraph(wc) && WCWIDTH(wc) > 0) + +#else /* not MULTIBYTE_SUPPORT */ + +#define MB_METACHARINIT() +typedef int convchar_t; +#define MB_METACHARLENCONV(str, cp) metacharlenconv((str), (cp)) +#define MB_METACHARLEN(str) (*(str) == Meta ? 2 : 1) +#define MB_METASTRLEN(str) ztrlen(str) +#define MB_METASTRWIDTH(str) ztrlen(str) +#define MB_METASTRLEN2(str, widthp) ztrlen(str) +#define MB_METASTRLEN2END(str, widthp, eptr) ztrlenend(str, eptr) + +#define MB_CHARINIT() +#define MB_CHARLENCONV(str, len, cp) charlenconv((str), (len), (cp)) +#define MB_CHARLEN(str, len) ((len) ? 1 : 0) + +#define WCWIDTH_WINT(c) (1) + +/* Leave character or string as is. */ +#define ZWC(c) c +#define ZWS(s) s + +#endif /* MULTIBYTE_SUPPORT */ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/zsh.mdd b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/zsh.mdd new file mode 100644 index 00000000..d95f5d51 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/zsh.mdd @@ -0,0 +1,147 @@ +name=zsh/main +link=static +load=yes +# load=static should replace use of alwayslink +functions='Functions/Chpwd/* Functions/Exceptions/* Functions/Math/* Functions/Misc/* Functions/MIME/* Functions/Prompts/* Functions/VCS_Info/* Functions/VCS_Info/Backends/*' + +nozshdep=1 +alwayslink=1 + +# autofeatures not specified because of alwayslink + +objects="signames.o builtin.o module.o lex.o exec.o mem.o \ +string.o parse.o hashtable.o init.o input.o loop.o utils.o params.o options.o \ +signals.o pattern.o prompt.o compat.o jobs.o glob.o" + +headers="../config.h zsh_system.h zsh.h sigcount.h signals.h \ +prototypes.h hashtable.h ztype.h" +hdrdeps="zshcurses.h zshterm.h" + +:<<\Make +@CONFIG_MK@ + +# If we're using gcc as the preprocessor, get rid of the additional +# lines generated by the preprocessor as they can confuse the script. +# We don't need these in other cases either, but can't necessarily rely +# on the option to remove them being the same. +signames.c: signames1.awk signames2.awk ../config.h @SIGNAL_H@ + $(AWK) -f $(sdir)/signames1.awk @SIGNAL_H@ >sigtmp.c + case "`$(CPP) --version &1`" in \ + *"Free Software Foundation"*) \ + $(CPP) -P sigtmp.c >sigtmp.out;; \ + *) \ + $(CPP) sigtmp.c >sigtmp.out;; \ + esac + $(AWK) -f $(sdir)/signames2.awk sigtmp.out > $@ + rm -f sigtmp.c sigtmp.out + +sigcount.h: signames.c + grep 'define.*SIGCOUNT' signames.c > $@ + +init.o: bltinmods.list zshpaths.h zshxmods.h + +init.o params.o parse.o: version.h + +params.o: patchlevel.h + +version.h: $(sdir_top)/Config/version.mk zshcurses.h zshterm.h + echo '#define ZSH_VERSION "'$(VERSION)'"' > $@ + +patchlevel.h: FORCE + @if [ -f $(sdir)/$@.release ]; then \ + cp -f $(sdir)/$@.release $@; \ + else \ + echo '#define ZSH_PATCHLEVEL "'`cd $(sdir) && git describe --tags --long`'"' > $@.tmp; \ + cmp $@ $@.tmp >/dev/null 2>&1 && rm -f $@.tmp || mv $@.tmp $@; \ + fi +FORCE: + +zshcurses.h: ../config.h + @if test x$(ZSH_CURSES_H) != x; then \ + echo "#include <$(ZSH_CURSES_H)>" >zshcurses.h; \ + else \ + echo >zshcurses.h; \ + fi + +zshterm.h: ../config.h + @if test x$(ZSH_TERM_H) != x; then \ + echo "#include <$(ZSH_TERM_H)>" >zshterm.h; \ + else \ + echo >zshterm.h; \ + fi + +zshpaths.h: Makemod $(CONFIG_INCS) + @echo '#define MODULE_DIR "'$(MODDIR)'"' > zshpaths.h.tmp + @if test x$(sitescriptdir) != xno; then \ + echo '#define SITESCRIPT_DIR "'$(sitescriptdir)'"' >> zshpaths.h.tmp; \ + fi + @if test x$(scriptdir) != xno; then \ + echo '#define SCRIPT_DIR "'$(scriptdir)'"' >> zshpaths.h.tmp; \ + fi + @if test x$(sitefndir) != xno; then \ + echo '#define SITEFPATH_DIR "'$(sitefndir)'"' >> zshpaths.h.tmp; \ + fi + @if test x$(fixed_sitefndir) != x; then \ + echo '#define FIXED_FPATH_DIR "'$(fixed_sitefndir)'"' >> zshpaths.h.tmp; \ + fi + @if test x$(fndir) != xno; then \ + echo '#define FPATH_DIR "'$(fndir)'"' >> zshpaths.h.tmp; \ + if test x$(FUNCTIONS_SUBDIRS) != x && \ + test x$(FUNCTIONS_SUBDIRS) != xno; then \ + fpath_tmp="`grep ' functions=.' \ + $(dir_top)/config.modules | sed -e '/^#/d' -e '/ link=no/d' \ + -e 's/^.* functions=//'`"; \ + fpath_tmp=`for f in $$fpath_tmp; do \ + echo $$f | sed -e 's%^Functions/%%' -e 's%/[^/]*$$%%' -e 's%/\*%%'; \ + done | grep -v Scripts | sort | uniq`; \ + fpath_tmp=`echo $$fpath_tmp | sed 's/ /\", \"/g'`; \ + echo "#define FPATH_SUBDIRS { \"$$fpath_tmp\" }" \ + >>zshpaths.h.tmp; \ + fi; \ + fi + @if test x$(additionalfpath) != x; then \ + fpath_tmp="`echo $(additionalfpath) | sed -e 's:,:\", \":g'`"; \ + echo "#define ADDITIONAL_FPATH { \"$$fpath_tmp\" }" >> zshpaths.h.tmp; \ + fi + @if cmp -s zshpaths.h zshpaths.h.tmp; then \ + rm -f zshpaths.h.tmp; \ + echo "\`zshpaths.h' is up to date." ; \ + else \ + mv -f zshpaths.h.tmp zshpaths.h; \ + echo "Updated \`zshpaths.h'." ; \ + fi + +bltinmods.list: modules.stamp mkbltnmlst.sh $(dir_top)/config.modules + srcdir='$(sdir)' CFMOD='$(dir_top)/config.modules' \ + $(SHELL) $(sdir)/mkbltnmlst.sh $@ + +zshxmods.h: $(dir_top)/config.modules + @echo "Creating \`$@'." + @( \ + for q_mod in `grep ' load=yes' $(dir_top)/config.modules | \ + grep ' link=static' | sed -e '/^#/d' -e 's/ .*//' \ + -e 's/^name=//' -e 's,Q,Qq,g;s,_,Qu,g;s,/,Qs,g'`; do \ + test x$q_mod = xzshQsmain && continue; \ + echo "#define LINKED_XMOD_$$q_mod 1"; \ + done; \ + for q_mod in `grep ' load=yes' $(dir_top)/config.modules | \ + grep ' link=dynamic' | sed -e '/^#/d' -e 's/ .*//' \ + -e 's/^name=//' -e 's,Q,Qq,g;s,_,Qu,g;s,/,Qs,g'`; do \ + test x$q_mod = x && continue; \ + echo "#ifdef DYNAMIC"; \ + echo "# define UNLINKED_XMOD_$$q_mod 1"; \ + echo "#endif"; \ + done; \ + ) > $@ + +clean-here: clean.zsh +clean.zsh: + rm -f sigcount.h signames.c bltinmods.list version.h zshpaths.h zshxmods.h + +# This is not properly part of this module, but it is built as if it were. +main.o: main.c zsh.mdh main.epro + $(CC) -c -I. -I$(sdir_top)/Src $(CPPFLAGS) $(DEFS) $(CFLAGS) -o $@ $(sdir)/main.c + +main.syms: $(PROTODEPS) +proto.zsh: main.epro +Make diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/zsh.rc b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/zsh.rc new file mode 100644 index 00000000..93c82ba1 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/zsh.rc @@ -0,0 +1,8 @@ +// Use this file as follows +// +// myapp.exe : myapp.o myapp.res +// gcc -mwindows myapp.o myapp.res -o $@ +// +// myapp.res : myapp.rc resource.h +// windres $< -O coff -o $@ +IDR_MAINFRAME ICON DISCARDABLE "zsh.ico" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/zsh_system.h b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/zsh_system.h new file mode 100644 index 00000000..8289ee97 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/zsh_system.h @@ -0,0 +1,900 @@ +/* + * system.h - system configuration header file + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#if 0 +/* + * Setting _XPG_IV here is actually wrong and is not needed + * with currently supported versions (5.43C20 and above) + */ +#ifdef sinix +# define _XPG_IV 1 +#endif +#endif + +#if defined(__linux) || defined(__GNU__) || defined(__GLIBC__) || defined(LIBC_MUSL) || defined(__CYGWIN__) +/* + * Turn on numerous extensions. + * This is in order to get the functions for manipulating /dev/ptmx. + */ +#define _GNU_SOURCE 1 +#endif +#ifdef LIBC_MUSL +#define _POSIX_C_SOURCE 200809L +#endif + +/* NeXT has half-implemented POSIX support * + * which currently fools configure */ +#ifdef __NeXT__ +# undef HAVE_TERMIOS_H +# undef HAVE_SYS_UTSNAME_H +#endif + +#ifndef ZSH_NO_XOPEN +# ifdef ZSH_CURSES_SOURCE +# define _XOPEN_SOURCE_EXTENDED 1 +# else +# ifdef MULTIBYTE_SUPPORT +/* + * Needed for wcwidth() which is part of XSI. + * Various other uses of the interface mean we can't get away with just + * _XOPEN_SOURCE. + */ +# define _XOPEN_SOURCE_EXTENDED 1 +# endif /* MULTIBYTE_SUPPORT */ +# endif /* ZSH_CURSES_SOURCE */ +#endif /* ZSH_NO_XOPEN */ + +/* + * Solaris by default zeroes all elements of the tm structure in + * strptime(). Unfortunately that gives us no way of telling whether + * the tm_isdst element has been set from the input pattern. If it + * hasn't we want it to be -1 (undetermined) on input to mktime(). So + * we stop strptime() zeroing the struct tm and instead set all the + * elements ourselves. + * + * This is likely to be harmless everywhere else. + */ +#define _STRPTIME_DONTZERO + +#ifdef PROTOTYPES +# define _(Args) Args +#else +# define _(Args) () +#endif + +#ifndef HAVE_ALLOCA +# define alloca zhalloc +#else +# ifdef __GNUC__ +# define alloca __builtin_alloca +# else +# if HAVE_ALLOCA_H +# include +# else +# ifdef _AIX + # pragma alloca +# else +# ifndef alloca +char *alloca _((size_t)); +# endif +# endif +# endif +# endif +#endif + +/* + * libc.h in an optional package for Debian Linux is broken (it + * defines dup() as a synonym for dup2(), which has a different + * number of arguments), so just include it for next. + */ +#ifdef __NeXT__ +# ifdef HAVE_LIBC_H +# include +# endif +#endif + +#ifdef HAVE_SYS_TYPES_H +# include +#endif + +#ifdef HAVE_UNISTD_H +# include +#endif + +#ifdef HAVE_STDDEF_H +/* + * Seen on Solaris 8 with gcc: stddef defines offsetof, which clashes + * with system.h's definition of the symbol unless we include this + * first. Otherwise, this will be hooked in by wchar.h, too late + * for comfort. + */ +#include +#endif + +#include +#include +#include +#include +#include + +#ifdef HAVE_PWD_H +# include +#endif + +#ifdef HAVE_GRP_H +# include +#endif + +#ifdef HAVE_DIRENT_H +# include +#else /* !HAVE_DIRENT_H */ +# ifdef HAVE_SYS_NDIR_H +# include +# endif +# ifdef HAVE_SYS_DIR_H +# include +# endif +# ifdef HAVE_NDIR_H +# include +# endif +# define dirent direct +# undef HAVE_STRUCT_DIRENT_D_INO +# undef HAVE_STRUCT_DIRENT_D_STAT +# ifdef HAVE_STRUCT_DIRECT_D_INO +# define HAVE_STRUCT_DIRENT_D_INO HAVE_STRUCT_DIRECT_D_INO +# endif +# ifdef HAVE_STRUCT_DIRECT_D_STAT +# define HAVE_STRUCT_DIRENT_D_STAT HAVE_STRUCT_DIRECT_D_STAT +# endif +#endif /* !HAVE_DIRENT_H */ + +#ifdef HAVE_STDLIB_H +# ifdef ZSH_MEM + /* malloc and calloc are macros in GNU's stdlib.h unless the + * the __MALLOC_0_RETURNS_NULL macro is defined */ +# define __MALLOC_0_RETURNS_NULL +# endif +# include +#endif + +/* + * Stuff with variable arguments. We use definitions to make the + * same code work with varargs (the original K&R-style, just to + * be maximally compatible) and stdarg (which all modern systems + * should have). + * + * Ideally this should somehow be merged with the tricks performed + * with "_" in makepro.awk, but I don't understand makepro.awk. + * Currently we simply rely on the fact that makepro.awk has been + * hacked to leave alone argument lists that already contains VA_ALIST + * except for removing the VA_DCL and turning VA_ALIST into VA_ALIST_PROTO. + */ +#ifdef HAVE_STDARG_H +# include +# define VA_ALIST1(x) x, ... +# define VA_ALIST2(x,y) x, y, ... +# define VA_ALIST_PROTO1(x) VA_ALIST1(x) +# define VA_ALIST_PROTO2(x,y) VA_ALIST2(x,y) +# define VA_DCL +# define VA_DEF_ARG(x) +# define VA_START(ap,x) va_start(ap, x) +# define VA_GET_ARG(ap,x,t) +#else +# if HAVE_VARARGS_H +# include +# define VA_ALIST1(x) va_alist +# define VA_ALIST2(x,y) va_alist +/* + * In prototypes, assume K&R form and remove the variable list. + * This is about the best we can do without second-guessing the way + * varargs works on this system. The _ trick should be able to + * do this for us but we've turned it off here. + */ +# define VA_ALIST_PROTO1(x) +# define VA_ALIST_PROTO2(x,y) +# define VA_DCL va_dcl +# define VA_DEF_ARG(x) x +# define VA_START(ap,x) va_start(ap); +# define VA_GET_ARG(ap,x,t) (x = va_arg(ap, t)) +# else +# error "Your system has neither stdarg.h or varargs.h." +# endif +#endif + +#ifdef HAVE_ERRNO_H +# include +#endif + +#ifdef TIME_WITH_SYS_TIME +# include +# include +#else +# ifdef HAVE_SYS_TIME_H +# include +# else +# include +# endif +#endif + +/* This is needed by some old SCO unices */ +#if !defined(HAVE_STRUCT_TIMEZONE) && !defined(ZSH_OOT_MODULE) +struct timezone { + int tz_minuteswest; + int tz_dsttime; +}; +#endif + +/* Used to provide compatibility with clock_gettime() */ +#if !defined(HAVE_STRUCT_TIMESPEC) && !defined(ZSH_OOT_MODULE) +struct timespec { + time_t tv_sec; + long tv_nsec; +}; +#endif + +/* There's more than one non-standard way to get at this data */ +#if !defined(HAVE_STRUCT_DIRENT_D_INO) && defined(HAVE_STRUCT_DIRENT_D_STAT) +# define d_ino d_stat.st_ino +# define HAVE_STRUCT_DIRENT_D_INO HAVE_STRUCT_DIRENT_D_STAT +#endif /* !HAVE_STRUCT_DIRENT_D_INO && HAVE_STRUCT_DIRENT_D_STAT */ + +/* Sco needs the following include for struct utimbuf * + * which is strange considering we do not use that * + * anywhere in the code */ +#ifdef __sco +# include +#endif + +#ifdef HAVE_SYS_TIMES_H +# include +#endif + +#if STDC_HEADERS || HAVE_STRING_H +# include +/* An ANSI string.h and pre-ANSI memory.h might conflict. */ +# if !STDC_HEADERS && HAVE_MEMORY_H +# include +# endif /* not STDC_HEADERS and HAVE_MEMORY_H */ +#else /* not STDC_HEADERS and not HAVE_STRING_H */ +# include +/* memory.h and strings.h conflict on some systems. */ +#endif /* not STDC_HEADERS and not HAVE_STRING_H */ + +#ifdef HAVE_LOCALE_H +# include +#endif + +#ifdef HAVE_LIMITS_H +# include +#endif + +#ifdef USE_STACK_ALLOCATION +#ifdef HAVE_VARIABLE_LENGTH_ARRAYS +# define VARARR(X,Y,Z) X (Y)[Z] +#else +# define VARARR(X,Y,Z) X *(Y) = (X *) alloca(sizeof(X) * (Z)) +#endif +#else +# define VARARR(X,Y,Z) X *(Y) = (X *) zhalloc(sizeof(X) * (Z)) +#endif + +/* we should handle unlimited sizes from pathconf(_PC_PATH_MAX) */ +/* but this is too much trouble */ +#ifndef PATH_MAX +# ifdef MAXPATHLEN +# define PATH_MAX MAXPATHLEN +# else +# ifdef _POSIX_PATH_MAX +# define PATH_MAX _POSIX_PATH_MAX +# else + /* so we will just pick something */ +# define PATH_MAX 1024 +# endif +# endif +#endif + +/* + * The number of file descriptors we'll allocate initially. + * We will reallocate later if necessary. + */ +#define ZSH_INITIAL_OPEN_MAX 64 +#ifndef OPEN_MAX +# ifdef NOFILE +# define OPEN_MAX NOFILE +# else + /* so we will just pick something */ +# define OPEN_MAX ZSH_INITIAL_OPEN_MAX +# endif +#endif +#ifndef HAVE_SYSCONF +# define zopenmax() ((long) (OPEN_MAX > ZSH_INITIAL_OPEN_MAX ? \ + ZSH_INITIAL_OPEN_MAX : OPEN_MAX)) +#endif + +#ifdef HAVE_FCNTL_H +# include +#else +# include +#endif + +/* The following will only be defined if is POSIX. * + * So we don't have to worry about union wait. But some machines * + * (NeXT) include from other include files, so we * + * need to undef and then redefine the wait macros if * + * is not POSIX. */ + +#ifdef HAVE_SYS_WAIT_H +# include +#else +# undef WIFEXITED +# undef WEXITSTATUS +# undef WIFSIGNALED +# undef WTERMSIG +# undef WCOREDUMP +# undef WIFSTOPPED +# undef WSTOPSIG +#endif + +/* missing macros for wait/waitpid/wait3 */ +#ifndef WIFEXITED +# define WIFEXITED(X) (((X)&0377)==0) +#endif +#ifndef WEXITSTATUS +# define WEXITSTATUS(X) (((X)>>8)&0377) +#endif +#ifndef WIFSIGNALED +# define WIFSIGNALED(X) (((X)&0377)!=0&&((X)&0377)!=0177) +#endif +#ifndef WTERMSIG +# define WTERMSIG(X) ((X)&0177) +#endif +#ifndef WCOREDUMP +# define WCOREDUMP(X) ((X)&0200) +#endif +#ifndef WIFSTOPPED +# define WIFSTOPPED(X) (((X)&0377)==0177) +#endif +#ifndef WSTOPSIG +# define WSTOPSIG(X) (((X)>>8)&0377) +#endif + +#ifdef HAVE_SYS_SELECT_H +# ifndef TIME_H_SELECT_H_CONFLICTS +# include +# endif +#elif defined(SELECT_IN_SYS_SOCKET_H) +# include +#endif + +#if defined(__APPLE__) && defined(HAVE_SELECT) +/* + * Prefer select() to poll() on MacOS X since poll() is known + * to be problematic in 10.4 + */ +#undef HAVE_POLL +#undef HAVE_POLL_H +#endif + +#ifdef HAVE_SYS_FILIO_H +# include +#endif + +#ifdef HAVE_TERMIOS_H +# ifdef __sco + /* termios.h includes sys/termio.h instead of sys/termios.h; * + * hence the declaration for struct termios is missing */ +# include +# else +# include +# endif +# ifdef _POSIX_VDISABLE +# define VDISABLEVAL _POSIX_VDISABLE +# else +# define VDISABLEVAL 0 +# endif +# define HAS_TIO 1 +#else /* not TERMIOS */ +# ifdef HAVE_TERMIO_H +# include +# define VDISABLEVAL -1 +# define HAS_TIO 1 +# else /* not TERMIOS and TERMIO */ +# include +# endif /* HAVE_TERMIO_H */ +#endif /* HAVE_TERMIOS_H */ + +#if defined(GWINSZ_IN_SYS_IOCTL) || defined(IOCTL_IN_SYS_IOCTL) +# include +#endif +#ifdef WINSIZE_IN_PTEM +# include +# include +#endif + +#ifdef HAVE_SYS_PARAM_H +# include +#endif + +#ifdef HAVE_SYS_UTSNAME_H +# include +#endif + +#define DEFAULT_WORDCHARS "*?_-.[]~=/&;!#$%^(){}<>" +#define DEFAULT_TIMEFMT "%J %U user %S system %P cpu %*E total" + +/* Posix getpgrp takes no argument, while the BSD version * + * takes the process ID as an argument */ +#ifdef GETPGRP_VOID +# define GETPGRP() getpgrp() +#else +# define GETPGRP() getpgrp(0) +#endif + +#ifndef HAVE_GETLOGIN +# define getlogin() cuserid(NULL) +#endif + +#ifdef HAVE_SETPGID +# define setpgrp setpgid +#endif + +/* can we set the user/group id of a process */ + +#ifndef HAVE_SETUID +# ifdef HAVE_SETREUID +# define setuid(X) setreuid(X,X) +# define setgid(X) setregid(X,X) +# define HAVE_SETUID +# endif +#endif + +/* can we set the effective user/group id of a process */ + +#ifndef HAVE_SETEUID +# ifdef HAVE_SETREUID +# define seteuid(X) setreuid(-1,X) +# define setegid(X) setregid(-1,X) +# define HAVE_SETEUID +# else +# ifdef HAVE_SETRESUID +# define seteuid(X) setresuid(-1,X,-1) +# define setegid(X) setresgid(-1,X,-1) +# define HAVE_SETEUID +# endif +# endif +#endif + +#ifdef HAVE_SYS_RESOURCE_H +# include +# if defined(__hpux) && !defined(RLIMIT_CPU) +/* HPUX does have the BSD rlimits in the kernel. Officially they are * + * unsupported but quite a few of them like RLIMIT_CORE seem to work. * + * All the following are in the but made visible * + * only for the kernel. */ +# define RLIMIT_CPU 0 +# define RLIMIT_FSIZE 1 +# define RLIMIT_DATA 2 +# define RLIMIT_STACK 3 +# define RLIMIT_CORE 4 +# define RLIMIT_RSS 5 +# define RLIMIT_NOFILE 6 +# define RLIMIT_OPEN_MAX RLIMIT_NOFILE +# define RLIM_NLIMITS 7 +# define RLIM_INFINITY 0x7fffffff +# endif +#endif + +/* we use the SVR4 constant instead of the BSD one */ +#if !defined(RLIMIT_NOFILE) && defined(RLIMIT_OFILE) +# define RLIMIT_NOFILE RLIMIT_OFILE +#endif +#if !defined(RLIMIT_VMEM) && defined(RLIMIT_AS) +# define RLIMIT_VMEM RLIMIT_AS +#endif + +#ifdef HAVE_SYS_CAPABILITY_H +# include +#endif + +/* DIGBUFSIZ is the length of a buffer which can hold the -LONG_MAX-1 * + * (or with ZSH_64_BIT_TYPE maybe -LONG_LONG_MAX-1) * + * converted to printable decimal form including the sign and the * + * terminating null character. Below 0.30103 > lg 2. * + * BDIGBUFSIZE is for a number converted to printable binary form. */ +#define DIGBUFSIZE ((int)(((sizeof(zlong) * 8) - 1) * 30103/100000) + 3) +#define BDIGBUFSIZE ((int)((sizeof(zlong) * 8) + 4)) + +/* If your stat macros are broken, we will * + * just undefine them. */ + +#ifdef STAT_MACROS_BROKEN +# undef S_ISBLK +# undef S_ISCHR +# undef S_ISDIR +# undef S_ISDOOR +# undef S_ISFIFO +# undef S_ISLNK +# undef S_ISMPB +# undef S_ISMPC +# undef S_ISNWK +# undef S_ISOFD +# undef S_ISOFL +# undef S_ISREG +# undef S_ISSOCK +#endif /* STAT_MACROS_BROKEN. */ + +/* If you are missing the stat macros, we * + * define our own */ + +#ifndef S_IFMT +# define S_IFMT 0170000 +#endif + +#if !defined(S_ISBLK) && defined(S_IFBLK) +# define S_ISBLK(m) (((m) & S_IFMT) == S_IFBLK) +#endif +#if !defined(S_ISCHR) && defined(S_IFCHR) +# define S_ISCHR(m) (((m) & S_IFMT) == S_IFCHR) +#endif +#if !defined(S_ISDIR) && defined(S_IFDIR) +# define S_ISDIR(m) (((m) & S_IFMT) == S_IFDIR) +#endif +#if !defined(S_ISDOOR) && defined(S_IFDOOR) /* Solaris */ +# define S_ISDOOR(m) (((m) & S_IFMT) == S_IFDOOR) +#endif +#if !defined(S_ISFIFO) && defined(S_IFIFO) +# define S_ISFIFO(m) (((m) & S_IFMT) == S_IFIFO) +#endif +#if !defined(S_ISLNK) && defined(S_IFLNK) +# define S_ISLNK(m) (((m) & S_IFMT) == S_IFLNK) +#endif +#if !defined(S_ISMPB) && defined(S_IFMPB) /* V7 */ +# define S_ISMPB(m) (((m) & S_IFMT) == S_IFMPB) +#endif +#if !defined(S_ISMPC) && defined(S_IFMPC) /* V7 */ +# define S_ISMPC(m) (((m) & S_IFMT) == S_IFMPC) +#endif +#if !defined(S_ISNWK) && defined(S_IFNWK) /* HP/UX */ +# define S_ISNWK(m) (((m) & S_IFMT) == S_IFNWK) +#endif +#if !defined(S_ISOFD) && defined(S_IFOFD) /* Cray */ +# define S_ISOFD(m) (((m) & S_IFMT) == S_IFOFD) +#endif +#if !defined(S_ISOFL) && defined(S_IFOFL) /* Cray */ +# define S_ISOFL(m) (((m) & S_IFMT) == S_IFOFL) +#endif +#if !defined(S_ISREG) && defined(S_IFREG) +# define S_ISREG(m) (((m) & S_IFMT) == S_IFREG) +#endif +#if !defined(S_ISSOCK) && defined(S_IFSOCK) +# define S_ISSOCK(m) (((m) & S_IFMT) == S_IFSOCK) +#endif + +/* We will pretend to have all file types on any system. */ + +#ifndef S_ISBLK +# define S_ISBLK(m) ((void)(m), 0) +#endif +#ifndef S_ISCHR +# define S_ISCHR(m) ((void)(m), 0) +#endif +#ifndef S_ISDIR +# define S_ISDIR(m) ((void)(m), 0) +#endif +#ifndef S_ISDOOR +# define S_ISDOOR(m) ((void)(m), 0) +#endif +#ifndef S_ISFIFO +# define S_ISFIFO(m) ((void)(m), 0) +#endif +#ifndef S_ISLNK +# define S_ISLNK(m) ((void)(m), 0) +#endif +#ifndef S_ISMPB +# define S_ISMPB(m) ((void)(m), 0) +#endif +#ifndef S_ISMPC +# define S_ISMPC(m) ((void)(m), 0) +#endif +#ifndef S_ISNWK +# define S_ISNWK(m) ((void)(m), 0) +#endif +#ifndef S_ISOFD +# define S_ISOFD(m) ((void)(m), 0) +#endif +#ifndef S_ISOFL +# define S_ISOFL(m) ((void)(m), 0) +#endif +#ifndef S_ISREG +# define S_ISREG(m) ((void)(m), 0) +#endif +#ifndef S_ISSOCK +# define S_ISSOCK(m) ((void)(m), 0) +#endif + +/* file mode permission bits */ + +#ifndef S_ISUID +# define S_ISUID 04000 +#endif +#ifndef S_ISGID +# define S_ISGID 02000 +#endif +#ifndef S_ISVTX +# define S_ISVTX 01000 +#endif +#ifndef S_IRUSR +# define S_IRUSR 00400 +#endif +#ifndef S_IWUSR +# define S_IWUSR 00200 +#endif +#ifndef S_IXUSR +# define S_IXUSR 00100 +#endif +#ifndef S_IRGRP +# define S_IRGRP 00040 +#endif +#ifndef S_IWGRP +# define S_IWGRP 00020 +#endif +#ifndef S_IXGRP +# define S_IXGRP 00010 +#endif +#ifndef S_IROTH +# define S_IROTH 00004 +#endif +#ifndef S_IWOTH +# define S_IWOTH 00002 +#endif +#ifndef S_IXOTH +# define S_IXOTH 00001 +#endif +#ifndef S_IRWXU +# define S_IRWXU (S_IRUSR|S_IWUSR|S_IXUSR) +#endif +#ifndef S_IRWXG +# define S_IRWXG (S_IRGRP|S_IWGRP|S_IXGRP) +#endif +#ifndef S_IRWXO +# define S_IRWXO (S_IROTH|S_IWOTH|S_IXOTH) +#endif +#ifndef S_IRUGO +# define S_IRUGO (S_IRUSR|S_IRGRP|S_IROTH) +#endif +#ifndef S_IWUGO +# define S_IWUGO (S_IWUSR|S_IWGRP|S_IWOTH) +#endif +#ifndef S_IXUGO +# define S_IXUGO (S_IXUSR|S_IXGRP|S_IXOTH) +#endif + +#ifndef HAVE_LSTAT +# define lstat stat +#endif + +#ifndef HAVE_READLINK +# define readlink(PATH, BUF, BUFSZ) \ + ((void)(PATH), (void)(BUF), (void)(BUFSZ), errno = ENOSYS, -1) +#endif + +#ifndef F_OK /* missing macros for access() */ +# define F_OK 0 +# define X_OK 1 +# define W_OK 2 +# define R_OK 4 +#endif + +#ifndef HAVE_LCHOWN +# define lchown chown +#endif + +#ifndef HAVE_MEMCPY +# define memcpy memmove +#endif + +#ifndef HAVE_MEMMOVE +# ifndef memmove +static char *zmmv; +# define memmove(dest, src, len) (bcopy((src), zmmv = (dest), (len)), zmmv) +# endif +#endif + +#ifndef offsetof +# define offsetof(TYPE, MEM) ((char *)&((TYPE *)0)->MEM - (char *)(TYPE *)0) +#endif + +extern char **environ; + +/* + * We always need setenv and unsetenv in pairs, because + * we don't know how to do memory management on the values set. + */ +#if defined(HAVE_SETENV) && defined(HAVE_UNSETENV) && !defined(__APPLE__) +# define USE_SET_UNSET_ENV +#endif + + +/* These variables are sometimes defined in, * + * and needed by, the termcap library. */ +#if MUST_DEFINE_OSPEED +extern char PC, *BC, *UP; +extern short ospeed; +#endif + +#ifndef O_NOCTTY +# define O_NOCTTY 0 +#endif + +#ifdef _LARGEFILE_SOURCE +#ifdef HAVE_FSEEKO +#define fseek fseeko +#endif +#ifdef HAVE_FTELLO +#define ftell ftello +#endif +#endif + +/* Can't support job control without working tcsetgrp() */ +#ifdef BROKEN_TCSETPGRP +#undef JOB_CONTROL +#endif /* BROKEN_TCSETPGRP */ + +#ifdef BROKEN_KILL_ESRCH +#undef ESRCH +#define ESRCH EINVAL +#endif /* BROKEN_KILL_ESRCH */ + +/* Can we do locale stuff? */ +#undef USE_LOCALE +#if defined(CONFIG_LOCALE) && defined(HAVE_SETLOCALE) && defined(LC_ALL) +# define USE_LOCALE 1 +#endif /* CONFIG_LOCALE && HAVE_SETLOCALE && LC_ALL */ + +#ifndef MAILDIR_SUPPORT +#define mailstat(X,Y) stat(X,Y) +#endif + +#ifdef __CYGWIN__ +# include +# define IS_DIRSEP(c) ((c) == '/' || (c) == '\\') +#else +# define IS_DIRSEP(c) ((c) == '/') +#endif + +#if defined(__GNUC__) && (!defined(__APPLE__) || defined(__clang__)) +/* Does the OS X port of gcc still gag on __attribute__? */ +#define UNUSED(x) x __attribute__((__unused__)) +#else +#define UNUSED(x) x +#endif + +/* + * The MULTIBYTE_SUPPORT configure-define specifies that we want to enable + * complete Unicode conversion between wide characters and multibyte strings. + */ +#if defined MULTIBYTE_SUPPORT \ + || (defined HAVE_WCHAR_H && defined HAVE_WCTOMB && defined __STDC_ISO_10646__) +/* + * If MULTIBYTE_SUPPORT is not defined, these includes provide a subset of + * Unicode support that makes the \u and \U printf escape sequences work. + */ + +#if defined(__hpux) && !defined(_INCLUDE__STDC_A1_SOURCE) +#define _INCLUDE__STDC_A1_SOURCE +#endif + +# include +# include +#endif +#ifdef HAVE_LANGINFO_H +# include +# ifdef HAVE_ICONV +# include +# endif +#endif + +#if defined(HAVE_INITGROUPS) && !defined(DISABLE_DYNAMIC_NSS) +# define USE_INITGROUPS +#endif + +#if defined(HAVE_GETGRGID) && !defined(DISABLE_DYNAMIC_NSS) +# define USE_GETGRGID +#endif + +#if defined(HAVE_GETGRNAM) && !defined(DISABLE_DYNAMIC_NSS) +# define USE_GETGRNAM +#endif + +#if defined(HAVE_GETPWENT) && !defined(DISABLE_DYNAMIC_NSS) +# define USE_GETPWENT +#endif + +#if defined(HAVE_GETPWNAM) && !defined(DISABLE_DYNAMIC_NSS) +# define USE_GETPWNAM +#endif + +#if defined(HAVE_GETPWUID) && !defined(DISABLE_DYNAMIC_NSS) +# define USE_GETPWUID +#endif + +#ifdef HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC +# define GET_ST_ATIME_NSEC(st) (st).st_atim.tv_nsec +#elif HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC +# define GET_ST_ATIME_NSEC(st) (st).st_atimespec.tv_nsec +#elif HAVE_STRUCT_STAT_ST_ATIMENSEC +# define GET_ST_ATIME_NSEC(st) (st).st_atimensec +#endif +#ifdef HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC +# define GET_ST_MTIME_NSEC(st) (st).st_mtim.tv_nsec +#elif HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC +# define GET_ST_MTIME_NSEC(st) (st).st_mtimespec.tv_nsec +#elif HAVE_STRUCT_STAT_ST_MTIMENSEC +# define GET_ST_MTIME_NSEC(st) (st).st_mtimensec +#endif +#ifdef HAVE_STRUCT_STAT_ST_CTIM_TV_NSEC +# define GET_ST_CTIME_NSEC(st) (st).st_ctim.tv_nsec +#elif HAVE_STRUCT_STAT_ST_CTIMESPEC_TV_NSEC +# define GET_ST_CTIME_NSEC(st) (st).st_ctimespec.tv_nsec +#elif HAVE_STRUCT_STAT_ST_CTIMENSEC +# define GET_ST_CTIME_NSEC(st) (st).st_ctimensec +#endif + +#if defined(HAVE_TGETENT) && !defined(ZSH_NO_TERM_HANDLING) +# if defined(ZSH_HAVE_CURSES_H) && defined(ZSH_HAVE_TERM_H) +# define USES_TERM_H 1 +# else +# ifdef HAVE_TERMCAP_H +# define USES_TERMCAP_H 1 +# endif +# endif + +# ifdef USES_TERM_H +# ifdef HAVE_TERMIO_H +# include +# endif +# ifdef ZSH_HAVE_CURSES_H +# include "zshcurses.h" +# endif +# include "zshterm.h" +# else +# ifdef USES_TERMCAP_H +# include +# endif +# endif +#endif + +#ifdef HAVE_SRAND_DETERMINISTIC +# define srand srand_deterministic +#endif + +#ifdef ZSH_VALGRIND +# include "valgrind/valgrind.h" +# include "valgrind/memcheck.h" +#endif diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/ztype.h b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/ztype.h new file mode 100644 index 00000000..ae723677 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Src/ztype.h @@ -0,0 +1,89 @@ +/* + * ztype.h - character classification macros + * + * This file is part of zsh, the Z shell. + * + * Copyright (c) 1992-1997 Paul Falstad + * All rights reserved. + * + * Permission is hereby granted, without written agreement and without + * license or royalty fees, to use, copy, modify, and distribute this + * software and to distribute modified versions of this software for any + * purpose, provided that the above copyright notice and the following + * two paragraphs appear in all copies of this software. + * + * In no event shall Paul Falstad or the Zsh Development Group be liable + * to any party for direct, indirect, special, incidental, or consequential + * damages arising out of the use of this software and its documentation, + * even if Paul Falstad and the Zsh Development Group have been advised of + * the possibility of such damage. + * + * Paul Falstad and the Zsh Development Group specifically disclaim any + * warranties, including, but not limited to, the implied warranties of + * merchantability and fitness for a particular purpose. The software + * provided hereunder is on an "as is" basis, and Paul Falstad and the + * Zsh Development Group have no obligation to provide maintenance, + * support, updates, enhancements, or modifications. + * + */ + +#define IDIGIT (1 << 0) +#define IALNUM (1 << 1) +#define IBLANK (1 << 2) +#define INBLANK (1 << 3) +#define ITOK (1 << 4) +#define ISEP (1 << 5) +#define IALPHA (1 << 6) +#define IIDENT (1 << 7) +#define IUSER (1 << 8) +#define ICNTRL (1 << 9) +#define IWORD (1 << 10) +#define ISPECIAL (1 << 11) +#define IMETA (1 << 12) +#define IWSEP (1 << 13) +#define INULL (1 << 14) +#define IPATTERN (1 << 15) +#define zistype(X,Y) (typtab[STOUC(X)] & Y) +#define idigit(X) zistype(X,IDIGIT) +#define ialnum(X) zistype(X,IALNUM) +#define iblank(X) zistype(X,IBLANK) /* blank, not including \n */ +#define inblank(X) zistype(X,INBLANK) /* blank or \n */ +#define itok(X) zistype(X,ITOK) +#define isep(X) zistype(X,ISEP) +#define ialpha(X) zistype(X,IALPHA) +#define iident(X) zistype(X,IIDENT) +#define iuser(X) zistype(X,IUSER) /* username char */ +#define icntrl(X) zistype(X,ICNTRL) +#define iword(X) zistype(X,IWORD) +#define ispecial(X) zistype(X,ISPECIAL) +#define imeta(X) zistype(X,IMETA) +#define iwsep(X) zistype(X,IWSEP) +#define inull(X) zistype(X,INULL) +#define ipattern(X) zistype(X,IPATTERN) + +/* + * Bit flags for typtab_flags --- preserved after + * shell initialisation. + */ +#define ZTF_INIT (0x0001) /* One-off initialisation done */ +#define ZTF_INTERACT (0x0002) /* Shell interative and reading from stdin */ +#define ZTF_SP_COMMA (0x0004) /* Treat comma as a special characters */ +#define ZTF_BANGCHAR (0x0008) /* Treat bangchar as a special character */ + +#ifdef MULTIBYTE_SUPPORT +#define WC_ZISTYPE(X,Y) wcsitype((X),(Y)) +# ifdef ENABLE_UNICODE9 +# define WC_ISPRINT(X) u9_iswprint(X) +# else +# define WC_ISPRINT(X) iswprint(X) +# endif +#else +#define WC_ZISTYPE(X,Y) zistype((X),(Y)) +#define WC_ISPRINT(X) isprint(X) +#endif + +#if defined(__APPLE__) && defined(BROKEN_ISPRINT) +#define ZISPRINT(c) isprint_ascii(c) +#else +#define ZISPRINT(c) isprint(c) +#endif diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/.cvsignore b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/.cvsignore new file mode 100644 index 00000000..855d7290 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/.cvsignore @@ -0,0 +1,3 @@ +Makefile +*.tmp +*.swp diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/.distfiles b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/.distfiles new file mode 100644 index 00000000..f03668b3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/.distfiles @@ -0,0 +1,2 @@ +DISTFILES_SRC=' +' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A01grammar.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A01grammar.ztst new file mode 100644 index 00000000..e4b6870d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A01grammar.ztst @@ -0,0 +1,790 @@ +# +# This file contains tests corresponding to the `Shell Grammar' texinfo node. +# + +%prep + + mkdir basic.tmp && cd basic.tmp + + touch foo bar + echo "'" >unmatched_quote.txt + +%test +# +# Tests for `Simple Commands and Pipelines' +# + + # Test skipping early to ensure we run the remainder... + if [[ -n $ZTST_test_skip ]]; then + ZTST_skip="Test system verification for skipping" + else + print "This is standard output" + print "This is standard error" >&2 + false + fi +1:Test skipping if ZTST_test_skip is set +>This is standard output +?This is standard error + + echo foo | cat | sed 's/foo/bar/' +0:Basic pipeline handling +>bar + + false | true +0:Exit status of pipeline with builtins (true) + + true | false +1:Exit status of pipeline with builtins (false) + + false + $nonexistent_variable +0:Executing command that evaluates to empty resets status + + false + sleep 1 & + print $? + # a tidy test is a happy test + wait $! +0:Starting background command resets status +>0 + + false + . /dev/null +0:Sourcing empty file resets status + + fn() { local foo; read foo; print $foo; } + coproc fn + print -p coproc test output + read -p bar + print $bar +0:Basic coprocess handling +>coproc test output + + true | false && print true || print false +0:Basic sublist (i) +>false + + false | true && print true || print false +0:Basic sublist (ii) +>true + + (cd /NonExistentDirectory >&/dev/null) || print false +0:Basic subshell list with error +>false + + { cd /NonExistentDirectory >&/dev/null } || print false +0:Basic current shell list with error +>false + +# +# Tests for `Precommand Modifiers' +# + - $ZTST_testdir/../Src/zsh -fc "[[ \$0 = \"-$ZTST_testdir/../Src/zsh\" ]]" +0:`-' precommand modifier + + echo f* + noglob echo f* +0:`noglob' precommand modifier +>foo +>f* + + (exec /bin/sh; echo bar) +0:`exec' precommand modifier + + (exec -l $ZTST_testdir/../Src/zsh -fc 'echo $0' | sed 's%/.*/%%' ) +0:`exec' with -l option +>-zsh + + (exec -a /bin/SPLATTER /bin/sh -c 'echo $0') +0:`exec' with -a option +>/bin/SPLATTER + + (exec -a/bin/SPLOOSH /bin/sh -c 'echo $0') +0:`exec' with -a option, no space +>/bin/SPLOOSH + + (export FOO=bar; exec -c /bin/sh -c 'echo x${FOO}x') +0:`exec' with -c option +>xx + + cat() { echo Function cat executed; } + command cat && unfunction cat +0:`command' precommand modifier +External command cat executed + + command -pv cat + command -pv echo + command -p -V cat + command -p -V -- echo +0:command -p in combination +*>*/cat +>echo +>cat is /*/cat +>echo is a shell builtin + + cd() { echo Not cd at all; } + builtin cd . && unfunction cd +0:`builtin' precommand modifier + +# +# Tests for `Complex Commands' +# + + if true; then + print true-1 + elif true; then + print true-2 + else + print false + fi +0:`if ...' (i) +>true-1 + + if false; then + print true-1 + elif true; then + print true-2 + else + print false + fi +0:`if ...' (ii) +>true-2 + + if false; then + print true-1 + elif false; then + print true-2 + else + print false + fi +0:`if ...' (iii) +>false + + if true; + : + fi +1d:`if ...' (iv) +?(eval):3: parse error near `fi' + + for name in word to term; do + print $name + done +0:`for' loop +>word +>to +>term + + for name + in word to term; do + print $name + done +0:`for' loop with newline before in keyword +>word +>to +>term + + for (( name = 0; name < 3; name++ )); do + print $name + done +0:arithmetic `for' loop +>0 +>1 +>2 + + for (( $(true); ; )); do break; done + for (( ; $(true); )); do break; done + for (( ; ; $(true) )); do break; done + for (( ; $((1)); )); do break; done +0:regression test, nested cmdsubst in arithmetic `for' loop + + for keyvar valvar in key1 val1 key2 val2; do + print key=$keyvar val=$valvar + done +0:enhanced `for' syntax with two loop variables +>key=key1 val=val1 +>key=key2 val=val2 + + for keyvar valvar stuffvar in keyA valA stuffA keyB valB stuffB; do + print key=$keyvar val=$valvar stuff=$stuffvar + done +0:enhanced `for' syntax with three loop variables +>key=keyA val=valA stuff=stuffA +>key=keyB val=valB stuff=stuffB + + for in in in in in stop; do + print in=$in + done +0:compatibility of enhanced `for' syntax with standard syntax +>in=in +>in=in +>in=in +>in=stop + + name=0 + while (( name < 3 )); do + print $name + (( name++ )) + done +0:`while' loop +>0 +>1 +>2 + + name=0 + until (( name == 3 )); do + print $name + (( name++ )) + done +0:`until' loop +>0 +>1 +>2 + + repeat 3 do + echo over and over + done +0:`repeat' loop +>over and over +>over and over +>over and over + + word=Trinity + case $word in + Michaelmas) print 0 + ;; + Hilary) print 1 + ;; + Trinity) print 2 + ;; + *) print 3 + ;; + esac +0:`case', old syntax +>2 + + word=Trinity + case $word in + (Michaelmas) print 0 + ;; + (Hilary) print 1 + ;; + (Trinity) print 2 + ;; + (*) print 3 + ;; + esac +0:`case', new syntax +>2 + + word=Hilary + case $word in + (Michaelmas) print 0 + ;; + (Hilary) print 1 + ;& + (Trinity) print 2 + ;& + (*) print 3 + ;; + esac +0:`case', new syntax, cascaded +>1 +>2 +>3 + + case whatever in + (*) print yeah, right ;& + esac + print but well +0:'case', redundant final ";&" +>yeah, right +>but well + +## Select now reads from stdin if the shell is not interactive. +## Its own output goes to stderr. + (COLUMNS=80 LINES=3 + PS3="input> " + select name in one two three; do + print $name + done) +0:`select' loop +<2 +?1) one 2) two 3) three +?input> input> +>two + + function name1 name2 () { print This is $0; } + name2 + name1 name2() { print This is still $0; } + name2 +0:`function' keyword +>This is name2 +>This is still name2 + + (time cat) >&/dev/null +0:`time' keyword (status only) + + if [[ -f foo && -d . && -n $ZTST_testdir ]]; then + true + else + false + fi +0:basic [[ ... ]] test + +# +# Current shell execution with try/always form. +# We put those with errors in subshells so that any unhandled error doesn't +# propagate. +# + + { + print The try block. + } always { + print The always block. + } + print After the always block. +0:Basic `always' syntax +>The try block. +>The always block. +>After the always block. + + ({ + print Position one. + print ${*this is an error*} + print Position two. + } always { + if (( TRY_BLOCK_ERROR )); then + print An error occurred. + else + print No error occurred. + fi + } + print Position three) +1:Always block with error not reset +>Position one. +>An error occurred. +?(eval):3: bad substitution + + ({ + print Stelle eins. + print ${*voici une erreur} + print Posizione due. + } always { + if (( TRY_BLOCK_ERROR )); then + print Erratum factum est. Retro ponetur. + (( TRY_BLOCK_ERROR = 0 )) + else + print unray touay foay anguageslay + fi + } + print Status after always block is $?.) +0:Always block with error reset +>Stelle eins. +>Erratum factum est. Retro ponetur. +>Status after always block is 1. +?(eval):3: bad substitution + + fn() { { return } always { echo always 1 }; echo not executed } + fn + fn() { { echo try 2 } always { return }; echo not executed } + fn +0:Always block interaction with return +>always 1 +>try 2 + +# Outputting of structures from the wordcode is distinctly non-trivial, +# we probably ought to have more like the following... + fn1() { { echo foo; } } + fn2() { { echo foo; } always { echo bar; } } + fn3() { ( echo foo; ) } + functions fn1 fn2 fn3 +0:Output of syntactic structures with and without always blocks +>fn1 () { +> { +> echo foo +> } +>} +>fn2 () { +> { +> echo foo +> } always { +> echo bar +> } +>} +>fn3 () { +> ( +> echo foo +> ) +>} + + +# +# Tests for `Alternate Forms For Complex Commands' +# + + if (true) { print true-1 } elif (true) { print true-2 } else { print false } + if (false) { print true-1 } elif (true) { print true-2 } else { print false } + if (false) { print true-1 } elif (false) { print true-2 } else { print false } +0:Alternate `if' with braces +>true-1 +>true-2 +>false + + if { true } print true + if { false } print false +0:Short form of `if' +>true + + eval "if" +1:Short form of `if' can't be too short +?(eval):1: parse error near `if' + + for name ( word1 word2 word3 ) print $name +0:Form of `for' with parentheses. +>word1 +>word2 +>word3 + + for name in alpha beta gamma; print $name +0:Short form of `for' +>alpha +>beta +>gamma + + for (( val = 2; val < 10; val *= val )) print $val +0:Short arithmetic `for' +>2 +>4 + + foreach name ( verbiage words periphrasis ) + print $name + end +0:Csh-like `for' +>verbiage +>words +>periphrasis + +# see comment with braces used in if loops + val=0; + while (( val < 2 )) { print $((val++)); } +0:Alternative `while' +>0 +>1 + + val=2; + until (( val == 0 )) { print $((val--)); } +0:Alternative `until' +>2 +>1 + + repeat 3 print Hip hip hooray +0:Short `repeat' +>Hip hip hooray +>Hip hip hooray +>Hip hip hooray + + case bravo { + (alpha) print schmalpha + ;; + (bravo) print schmavo + ;; + (charlie) print schmarlie + ;; + } +0:`case' with braces +>schmavo + + for word in artichoke bladderwort chrysanthemum Zanzibar + case $word in + (*der*) print $word contains the forbidden incantation der + ;; + (a*) print $word begins with a + ;& + ([[:upper:]]*) print $word either begins with a or an upper case letter + ;| + ([[:lower:]]*) print $word begins with a lower case letter + ;| + (*e*) print $word contains an e + ;; + esac +0:`case' with mixed ;& and ;| +>artichoke begins with a +>artichoke either begins with a or an upper case letter +>artichoke begins with a lower case letter +>artichoke contains an e +>bladderwort contains the forbidden incantation der +>chrysanthemum begins with a lower case letter +>chrysanthemum contains an e +>Zanzibar either begins with a or an upper case letter + + print -u $ZTST_fd 'This test hangs the shell when it fails...' + name=0 +# The number 4375 here is chosen to produce more than 16384 bytes of output + while (( name < 4375 )); do + print -n $name + (( name++ )) + done < /dev/null | { read name; print done } +0:Bug regression: `while' loop with redirection and pipeline +>done + +# This used to be buggy and print X at the end of each iteration. + for f in 1 2 3 4; do + print $f || break + done && print X +0:Handling of ||'s and &&'s with a for loop in between +>1 +>2 +>3 +>4 +>X + +# Same bug for &&, used to print `no' at the end of each iteration + for f in 1 2 3 4; do + false && print strange + done || print no +0:Handling of &&'s and ||'s with a for loop in between +>no + + $ZTST_testdir/../Src/zsh -f unmatched_quote.txt +1:Parse error with file causes non-zero exit status +?unmatched_quote.txt:2: unmatched ' + + $ZTST_testdir/../Src/zsh -f value +>not#comment + + . ./nonexistent +127: Attempt to "." non-existent file. +?(eval):.:1: no such file or directory: ./nonexistent + + echo '[[' >bad_syntax + . ./bad_syntax +126: Attempt to "." file with bad syntax. +?./bad_syntax:2: parse error near `\n' +# ` + + echo 'false' >dot_false + . ./dot_false + print $? + echo 'true' >dot_true + . ./dot_true + print $? +0:Last status of successfully executed "." file is retained +>1 +>0 + + echo 'echo $?' >dot_status + false + . ./dot_status +0:"." file sees status from previous command +>1 + + mkdir test_path_script + print "#!/bin/sh\necho Found the script." >test_path_script/myscript + chmod u+x test_path_script/myscript + path=($PWD/test_path_script $path) + export PATH + $ZTST_testdir/../Src/zsh -f -o pathscript myscript +0:PATHSCRIPT option +>Found the script. + + $ZTST_testdir/../Src/zsh -f myscript +127q:PATHSCRIPT option not used. +?$ZTST_testdir/../Src/zsh: can't open input file: myscript +# ' + + $ZTST_testdir/../Src/zsh -fc 'echo $0; echo $1' myargzero myargone +0:$0 is traditionally if bizarrely set to the first argument with -c +>myargzero +>myargone + + (setopt shglob + eval ' + if ! (echo success1); then echo failure1; fi + if !(echo success2); then echo failure2; fi + print -l one two | while(read foo)do(print read it)done + ') +0:Parentheses in shglob +>success1 +>success2 +>read it +>read it + + ( + mywrap() { echo BEGIN; true; echo END } + mytest() { { exit 3 } always { mywrap }; print Exited before this } + mytest + print Exited before this, too + ) +3:Exit and always block with functions: simple +>BEGIN +>END + + ( + mytrue() { echo mytrue; return 0 } + mywrap() { echo BEGIN; mytrue; echo END } + mytest() { { exit 4 } always { mywrap }; print Exited before this } + mytest + print Exited before this, too + ) +4:Exit and always block with functions: nested +>BEGIN +>mytrue +>END + + (emulate sh -c ' + fn() { + case $1 in + ( one | two | three ) + print Matched $1 + ;; + ( fo* | fi* | si* ) + print Pattern matched $1 + ;; + ( []x | a[b]* ) + print Character class matched $1 + ;; + esac + } + ' + which fn + fn one + fn two + fn three + fn four + fn five + fn six + fn abecedinarian + fn xylophone) +0: case word handling in sh emulation (SH_GLOB parentheses) +>fn () { +> case $1 in +> (one | two | three) print Matched $1 ;; +> (fo* | fi* | si*) print Pattern matched $1 ;; +> ([]x | a[b]*) print Character class matched $1 ;; +> esac +>} +>Matched one +>Matched two +>Matched three +>Pattern matched four +>Pattern matched five +>Pattern matched six +>Character class matched abecedinarian + + case grumph in + ( no | (grumph) ) + print 1 OK + ;; + esac + case snruf in + ( fleer | (|snr(|[au]f)) ) + print 2 OK + ;; + esac +0: case patterns within words +>1 OK +>2 OK + + case horrible in + ([a-m])(|[n-z])rr(|ib(um|le|ah))) + print It worked + ;; + esac + case "a string with separate words" in + (*with separate*)) + print That worked, too + ;; + esac +0:Unbalanced parentheses and spaces with zsh pattern +>It worked +>That worked, too + + case horrible in + (([a-m])(|[n-z])rr(|ib(um|le|ah))) + print It worked + ;; + esac + case "a string with separate words" in + (*with separate*) + print That worked, too + ;; + esac +0:Balanced parentheses and spaces with zsh pattern +>It worked +>That worked, too + + fn() { + typeset ac_file="the else branch" + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) break;; + *) + ;; + esac + print Stuff here + } + which fn + fn +0:Long case with parsed alternatives turned back into text +>fn () { +> typeset ac_file="the else branch" +> case $ac_file in +> (*.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj) ;; +> (*.*) break ;; +> (*) ;; +> esac +> print Stuff here +>} +>Stuff here + + (exit 37) + case $? in + (37) echo $? + ;; + esac +0:case retains exit status for execution of cases +>37 + + false + case stuff in + (nomatch) foo + ;; + esac + echo $? +0:case sets exit status to zero if no patterns are matched +>0 + + case match in + (match) true; false; (exit 37) + ;; + esac + echo $? +0:case keeps exit status of last command executed in compound-list +>37 + + x=1 + x=2 | echo $x + echo $x +0:Assignment-only current shell commands in LHS of pipelin +>1 +>1 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A02alias.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A02alias.ztst new file mode 100644 index 00000000..e68e93e0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A02alias.ztst @@ -0,0 +1,139 @@ +# To get the "command not found" message when aliasing is suppressed +# we need, er, a command that isn't found. +# The other aliases are only ever used as aliases. + +%prep + alias ThisCommandDefinitelyDoesNotExist=echo + + alias -g bar=echo + + alias '\bar=echo' + +%test + ThisCommandDefinitelyDoesNotExist ThisCommandDefinitelyDoesNotExist +0:Basic aliasing +>ThisCommandDefinitelyDoesNotExist + + bar bar +0:Global aliasing +>echo + + \ThisCommandDefinitelyDoesNotExist ThisCommandDefinitelyDoesNotExist +127:Not aliasing +?(eval):1: command not found: ThisCommandDefinitelyDoesNotExist + + \bar \bar +0:Aliasing with a backslash +>bar + + (alias '!=echo This command has the argument' + eval 'print Without + ! true' + setopt posixaliases + eval 'print With + ! true') +1:POSIX_ALIASES option +>Without +>This command has the argument true +>With + + print -u $ZTST_fd 'This test hangs the shell when it fails...' + alias cat='LC_ALL=C cat' + cat <(echo foo | cat) +0:Alias expansion works at the end of parsed strings +>foo + + alias -g '&&=(){ return $?; } && ' + alias not_the_print_command=print + eval 'print This is output + && print And so is this + && { print And this too; false; } + && print But not this + && print Nor this + true + && not_the_print_command And aliases are expanded' +0:We can now alias special tokens. Woo hoo. +>This is output +>And so is this +>And this too +>And aliases are expanded + + $ZTST_testdir/../Src/zsh -fis <<<' + unsetopt PROMPT_SP + PROMPT="" PS2="" PS3="" PS4="" RPS1="" RPS2="" + exec 2>&1 + alias \{=echo + { begin + {end + fc -l -2' 2>/dev/null +0:Aliasing reserved tokens +>begin +>end +*>*5*{ begin +*>*6*{end + + $ZTST_testdir/../Src/zsh -fis <<<' + unsetopt PROMPT_SP + PROMPT="" PS2="" PS3="" PS4="" RPS1="" RPS2="" + exec 2>&1 + alias -g S=\" + echo S a string S " + fc -l -1' 2>/dev/null +0:Global aliasing quotes +> a string S +*>*5*echo S a string S " +# " +# Note there is a trailing space on the "> a string S " line + + ( + unalias -a + alias + ) +0:unalias -a + + alias -s foo=print + type bar.foo; type -w bar.foo + unalias -as +0:unalias -as +>foo is a suffix alias for print +>foo: suffix alias + + aliases[x=y]=z + alias -L | grep x=y + echo $pipestatus[1] +0:printing invalid aliases warns +>0 +?(eval):2: invalid alias 'x=y' encountered while printing aliases +# Currently, 'alias -L' returns 0 in this case. Perhaps it should return 1. + + alias -s mysuff='print -r "You said it.";' + eval 'thingummy.mysuff' +127:No endless loop with suffix alias in command position +>You said it. +?(eval):1: command not found: thingummy.mysuff + + alias +x; alias -z +1:error message has the correct sign +?(eval):alias:1: bad option: +x +?(eval):alias:1: bad option: -z + + # Usual issue that aliases aren't expanded until we + # trigger a new parse... + (alias badalias=notacommand + eval 'badalias() { print does not work; }') +1:ALIAS_FUNC_DEF off by default. +?(eval):1: defining function based on alias `badalias' +?(eval):1: parse error near `()' + + (alias goodalias=isafunc + setopt ALIAS_FUNC_DEF + eval 'goodalias() { print does now work; }' + isafunc) +0:ALIAS_FUNC_DEF causes the icky behaviour to be avaliable +>does now work + + (alias thisisokthough='thisworks() { print That worked; }' + eval thisisokthough + thisworks) +0:NO_ALIAS_FUNC_DEF works if the alias is a complete definition +>That worked diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A03quoting.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A03quoting.ztst new file mode 100644 index 00000000..da3ce359 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A03quoting.ztst @@ -0,0 +1,80 @@ +%test + print 'single quotes' "double quotes" `echo backquotes` +0:Simple use of quotes +>single quotes double quotes backquotes + + foo=text + print -r '$foo\\\' "$foo\$foo\\\"\``echo bar`\`\"" `print -r $foo\\\`` +0:Quoting inside quotes +>$foo\\\ text$foo\"`bar`" text` + + print -r $'\'ut queant laxis\'\n"resonare fibris"' +0:$'-style quotes +>'ut queant laxis' +>"resonare fibris" + + print -r $'\'a \\\' is \'a backslash\' is \'a \\\'' +0:$'-style quotes with backslashed backslashes +>'a \' is 'a backslash' is 'a \' + + chars=$(print -r $'BS\\MBS\M-\\') + for (( i = 1; i <= $#chars; i++ )); do + char=$chars[$i] + print $(( [#16] #char )) + done +0:$'-style quote with metafied backslash +>16#42 +>16#53 +>16#5C +>16#4D +>16#42 +>16#53 +>16#DC + + print -r '''' + setopt rcquotes +# We need to set rcquotes here for the next example since it is +# needed while parsing. +0:No RC_QUOTES with single quotes +> + + print -r '''' + unsetopt rcquotes +0:Yes RC_QUOTES with single quotes +>' +# ' Deconfuse Emacs quoting rules + + print '<\u0041>' + printf '%s\n' $'<\u0042>' + print '<\u0043>' + printf '%s\n' $'<\u0044>' +0:\u in both print and printf +> +> +> +> + + null1="$(print -r a$'b\0c'd)" + null2="$(setopt posixstrings; print -r a$'b\0c'd)" + for string in $null1 $null2; do + print ":" + for (( i = 1; i <= $#string; i++ )); do + char=$string[$i] + print $(( [#16] #char )) + done + done +0:Embedded null characters in $'...' strings. +>: +>16#61 +>16#62 +>16#0 +>16#63 +>16#64 +>: +>16#61 +>16#62 +>16#64 + + () { print $# } '' "" $'' +0:$'' should not be elided, in common with other empty quotes +>3 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A04redirect.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A04redirect.ztst new file mode 100644 index 00000000..d7fe22fb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A04redirect.ztst @@ -0,0 +1,588 @@ +# Tests corresponding to the `Redirection' texinfo node. + +%prep + mkdir redir.tmp && cd redir.tmp + + myfd=99 + (echo >&$myfd) 2>msg + bad_fd_msg="${$(redir && cat redir +0:'>' and '<' redirection +>This is file redir + + rm -f redir + print 'This is still file redir' <>redir >&0 && cat <>redir +0:'<>' redirection +>This is still file redir + + rm -f redir + print 'With a bar' >|redir && cat redir +0:'>|' redirection +>With a bar + + rm -f redir + print 'With a bang' >!redir && cat redir +0:'>!' redirection +>With a bang + + rm -f redir + print 'Line 1' >>redir && print 'Line 2' >>redir && cat redir +0:'>>' redirection +>Line 1 +>Line 2 + + rm -f redir + print 'Line a' >>|redir && print 'Line b' >>!redir +0:'>>|' and '>>!' redirection + + foo=bar + cat <<' HERE' + $foo + HERE + eval "$(print 'cat < $foo +>bar + + cat <<-HERE +# note tabs at the start of the following lines + $foo$foo + HERE +0:Here-documents stripping tabs +>barbar + + cat <<-$'$HERE '`$(THERE) `'$((AND)) '"\EVERYWHERE" # +# tabs again. sorry about the max miller. + Here's a funny thing. Here is a funny thing. + I went home last night. There's a funny thing. + Man walks into a $foo. Ouch, it's an iron $foo. + $HERE `$(THERE) `$((AND)) \EVERYWHERE +0:Here-documents don't perform shell expansion on the initial word +>Here's a funny thing. Here is a funny thing. +>I went home last night. There's a funny thing. +>Man walks into a $foo. Ouch, it's an iron $foo. + + cat <<-$'\x45\x4e\x44\t\x44\x4f\x43' +# tabs again + This message is unfathomable. + END DOC +0:Here-documents do perform $'...' expansion on the initial word +>This message is unfathomable. + + cat <<<"This is a line with a $foo in it" +0:'<<<' redirection +>This is a line with a bar in it + + cat <<<$'a\nb\nc' +0:here-strings with $'...' quoting +>a +>b +>c + +# The following tests check that output of parsed here-documents works. +# This isn't completely trivial because we convert the here-documents +# internally to here-strings. So we check again that we can output +# the reevaluated here-strings correctly. Hence there are three slightly +# different stages. We don't care how the output actually looks, so +# we don't test that. + heretest() { + print First line + cat <<-HERE + $foo$foo met celeste 'but with extra' "stuff to test quoting" + HERE + print Last line + } + heretest + eval "$(functions heretest)" + heretest + eval "$(functions heretest)" + heretest +0:Re-evaluation of function output with here document, unquoted +>First line +>barbar met celeste 'but with extra' "stuff to test quoting" +>Last line +>First line +>barbar met celeste 'but with extra' "stuff to test quoting" +>Last line +>First line +>barbar met celeste 'but with extra' "stuff to test quoting" +>Last line + + heretest() { + print First line + cat <<' HERE' + $foo$foo met celeste 'but with extra' "stuff to test quoting" + HERE + print Last line + } + heretest + eval "$(functions heretest)" + heretest + eval "$(functions heretest)" + heretest +0:Re-evaluation of function output with here document, quoted +>First line +> $foo$foo met celeste 'but with extra' "stuff to test quoting" +>Last line +>First line +> $foo$foo met celeste 'but with extra' "stuff to test quoting" +>Last line +>First line +> $foo$foo met celeste 'but with extra' "stuff to test quoting" +>Last line + + read -r line <<' HERE' + HERE +1:No input, not even newline, from empty here document. + + # + # exec tests: perform these in subshells so if they fail the + # shell won't exit. + # + (exec 3>redir && print hello >&3 && print goodbye >&3 && cat redir) +0:'>&' redirection +>hello +>goodbye + + (exec 3hello +>goodbye + + ({exec 3<&- } 2>/dev/null + exec 3<&- + read foo <&-) +1:'<&-' redirection with numeric fd (no error message on failure) + + (exec {varid}<&0 + exec {varid}<&- + print About to close a second time >&2 + read {varid}<&-) +1:'<&-' redirection with fd in variable (error message on failure) +?About to close a second time +*?\(eval\):*: failed to close file descriptor * + + print foo >&- +0:'>&-' redirection + + (exec >&- + print foo) +0:'>&-' with attempt to use closed fd +*?\(eval\):2: write error:* + + fn() { local foo; read foo; print $foo; } + coproc fn + print test output >&p + read bar <&p + print $bar +0:'>&p' and '<&p' redirection +>test output + + ( print Output; print Error >& 2 ) >&errout && cat errout +0:'>&FILE' handling +>Output +>Error + + rm -f errout + ( print Output2; print Error2 >& 2 ) &>errout && cat errout +0:'&>FILE' handling +>Output2 +>Error2 + + rm -f errout + ( print Output3; print Error3 >& 2 ) >&|errout && cat errout + ( print Output4; print Error4 >& 2 ) >&!errout && cat errout + ( print Output5; print Error5 >& 2 ) &>|errout && cat errout + ( print Output6; print Error6 >& 2 ) &>!errout && + ( print Output7; print Error7 >& 2 ) >>&errout && + ( print Output8; print Error8 >& 2 ) &>>errout && + ( print Output9; print Error9 >& 2 ) >>&|errout && + ( print Output10; print Error10 >& 2 ) &>>|errout && + ( print Output11; print Error11 >& 2 ) >>&!errout && + ( print Output12; print Error12 >& 2 ) &>>!errout && cat errout +0:'>&|', '>&!', '&>|', '&>!' redirection +>Output3 +>Error3 +>Output4 +>Error4 +>Output5 +>Error5 +>Output6 +>Error6 +>Output7 +>Error7 +>Output8 +>Error8 +>Output9 +>Error9 +>Output10 +>Error10 +>Output11 +>Error11 +>Output12 +>Error12 + + rm -f errout + ( print Output; print Error 1>&2 ) 1>errout 2>&1 && cat errout +0:'Combining > with >& (1)' +>Output +>Error + + rm -f errout + ( print Output; print Error 1>&2 ) 2>&1 1>errout && print errout: && + cat errout +0:'Combining > with >& (2)' +>Error +>errout: +>Output + + rm -f errout + print doo be doo be doo >foo >bar + print "foo: $(foo: doo be doo be doo +>bar: doo be doo be doo + + rm -f foo bar + print dont be dont be dont >foo | sed 's/dont/wont/g' >bar +0:setup file+pipe multio + + print "foo: $(foo: dont be dont be dont +>bar: wont be wont be wont + + rm -f * + touch out1 out2 + print All files >* + print * + print "out1: $(out1 out2 +>out1: All files +>out2: All files + + print This is out1 >out1 + print This is out2 >out2 +0:setup multio for input + +# Currently, This is out1 +>This is out2 + + cat out1 | sed s/out/bout/ This is bout1 +>This is bout2 + + unset NULLCMD + >out1 +1:null redir with NULLCMD unset +?(eval):2: redirection with no command + + echo this should still work >out1 + print "$(this should still work + + READNULLCMD=cat + print cat input >out1 + out1 + [[ ! -s out1 ]] || print out1 is not empty +0:null redir with NULLCMD=: +out1 + cat input + + NULLCMD=cat + >out1 + cat out1 +0:null redir with NULLCMD=cat +input + + (myfd= + exec {myfd}>logfile + if [[ -z $myfd ]]; then + print "Ooops, failed to set myfd to a file descriptor." >&2 + else + print This is my logfile. >&$myfd + print Examining contents of logfile... + cat logfile + fi) +0:Using {fdvar}> syntax to open a new file descriptor +>Examining contents of logfile... +>This is my logfile. + + (setopt noclobber + exec {myfd}>logfile2 + echo $myfd + exec {myfd}>logfile3) | read myfd + (( ! ${pipestatus[1]} )) +1q:NO_CLOBBER prevents overwriting parameter with allocated fd +?(eval):4: can't clobber parameter myfd containing file descriptor $myfd + + (setopt noclobber + exec {myfd}>logfile2b + print First open >&$myfd + rm -f logfile2b # prevent normal file no_clobberation + myotherfd="${myfd}+0" + exec {myotherfd}>logfile2b + print Overwritten >&$myotherfd) + cat logfile2b +0:NO_CLOBBER doesn't complain about any other expression +>Overwritten + + (exec {myfd}>logfile4 + echo $myfd + exec {myfd}>&- + print This message should disappear >&$myfd) | read myfd + (( ! ${pipestatus[1]} )) +1q:Closing file descriptor using brace syntax +?(eval):4: $myfd:$bad_fd_msg + + typeset -r myfd + echo This should not appear {myfd}>nologfile +1:Error opening file descriptor using readonly variable +?(eval):2: can't allocate file descriptor to readonly parameter myfd + + (typeset +r myfd + exec {myfd}>newlogfile + typeset -r myfd + exec {myfd}>&-) +1:Error closing file descriptor using readonly variable +?(eval):4: can't close file descriptor from readonly parameter myfd + +# This tests the here-string to filename optimisation; we can't +# test that it's actually being optimised, but we can test that it +# still works. + cat =(<<<$'This string has been replaced\nby a file containing it.\n') +0:Optimised here-string to filename +>This string has been replaced +>by a file containing it. + + print This f$'\x69'le contains d$'\x61'ta. >redirfile + print redirection: + catoutfile + print output: + cat outfile + print append: + cat>>outfileredirection: +>output: +>This file contains data. +>append: +>more output: +>This file contains data. +>This file contains data. + + $ZTST_testdir/../Src/zsh -fc 'exec >/nonexistent/nonexistent + echo output' +0:failed exec redir, no POSIX_BUILTINS +>output +?zsh:1: no such file or directory: /nonexistent/nonexistent + + $ZTST_testdir/../Src/zsh -f -o POSIX_BUILTINS -c ' + exec >/nonexistent/nonexistent + echo output' +1:failed exec redir, POSIX_BUILTINS +?zsh:2: no such file or directory: /nonexistent/nonexistent + + $ZTST_testdir/../Src/zsh -f -o POSIX_BUILTINS -c ' + set >/nonexistent/nonexistent + echo output' +1:failed special builtin redir, POSIX_BUILTINS +?zsh:2: no such file or directory: /nonexistent/nonexistent + + $ZTST_testdir/../Src/zsh -f -o POSIX_BUILTINS -c ' + command set >/nonexistent/nonexistent + echo output' +0:failed special builtin redir with command prefix, POSIX_BUILTINS +>output +?zsh:2: no such file or directory: /nonexistent/nonexistent + + $ZTST_testdir/../Src/zsh -f -o POSIX_BUILTINS -c ' + echo >/nonexistent/nonexistent + echo output' +0:failed unspecial builtin redir, POSIX_BUILTINS +>output +?zsh:2: no such file or directory: /nonexistent/nonexistent + + $ZTST_testdir/../Src/zsh -f -o POSIX_BUILTINS -c ' + . /nonexistent/nonexistent + echo output' +1:failed dot, POSIX_BUILTINS +?zsh:.:2: no such file or directory: /nonexistent/nonexistent + + $ZTST_testdir/../Src/zsh -f -c ' + . /nonexistent/nonexistent + echo output' +0:failed dot, NO_POSIX_BUILTINS +>output +?zsh:.:2: no such file or directory: /nonexistent/nonexistent + + $ZTST_testdir/../Src/zsh -f -o CONTINUE_ON_ERROR <<<' + readonly foo + foo=bar set output + echo output' +0:failed assignment on posix special, CONTINUE_ON_ERROR +>output +?zsh: read-only variable: foo + + $ZTST_testdir/../Src/zsh -f <<<' + readonly foo + foo=bar set output + echo output' +1:failed assignment on posix special, NO_CONTINUE_ON_ERROR +?zsh: read-only variable: foo + + $ZTST_testdir/../Src/zsh -f -o CONTINUE_ON_ERROR <<<' + readonly foo + foo=bar echo output + echo output' +0:failed assignment on non-posix-special, CONTINUE_ON_ERROR +>output +?zsh: read-only variable: foo + + [input1 + () { + local var + read var + print I just read $var + } output1 + print Nothing output yet + cat output1 +0:anonymous function redirections are applied immediately +>Nothing output yet +>I just read any old rubbish + + redirfn() { + local var + read var + print I want to tell you about $var + print Also, this might be an error >&2 + } output2 2>&1 + print something I heard on the radio >input2 + redirfn + print No output until after this + cat output2 +0:redirections with normal function definition +>No output until after this +>I want to tell you about something I heard on the radio +>Also, this might be an error + + which redirfn +0:text output of function with redirections +>redirfn () { +> local var +> read var +> print I want to tell you about $var +> print Also, this might be an error >&2 +>} < input2 > output2 2>&1 + + 1func 2func 3func() { print Ich heisse $0 } >output3 + for i in 1 2 3; do + f=${i}func + print Running $f + $f + cat output3 + unfunction $f + done +0:multiply named functions with redirection +>Running 1func +>Ich heisse 1func +>Running 2func +>Ich heisse 2func +>Running 3func +>Ich heisse 3func + + redirfn2() { print The latest output; } >&3 + redirfn2 3>output4 + print No output yet + cat output4 +0:Redirections in both function definition and command line +>No output yet +>The latest output + +# This relies on the fact that the test harness always loads +# the zsh/parameter module. + print $functions[redirfn] +0:Output from $functions[] for definition with redirection +>{ +> local var +> read var +> print I want to tell you about $var +> print Also, this might be an error >&2 +>} < input2 > output2 2>&1 + + noredirfn() { print This rather boring function has no redirection.; } + print $functions[noredirfn] +0:Output from $functions[] for definition with no redirection +> print This rather boring function has no redirection. + + (x=43 + x=$(print This should appear, really >&2; print Not used) exec >test.log + print x=$x) + cat test.log +0:Assignment with exec used for redirection: no POSIX_BUILTINS +>x=43 +?This should appear, really + + (setopt POSIX_BUILTINS + x=45 + x=$(print This should appear, too >&2; print And this) exec >test.log + print x=$x) + cat test.log +0:Assignment with exec used for redirection: POSIX_BUILTINS +>x=And this +?This should appear, too + + fn-two-heres() { +# tabs below + cat <<-x <<-y + foo + x + bar + y + } + which -x2 fn-two-heres + fn-two-heres + eval "$(which -x2 fn-two-heres)" + fn-two-heres + print $functions[fn-two-heres] +0:Two here-documents in a line are shown correctly. +>fn-two-heres () { +> cat <foo +>x +>bar +>y +>} +>foo +>bar +>foo +>bar +> cat <foo +>x +>bar +>y diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A05execution.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A05execution.ztst new file mode 100644 index 00000000..0804691a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A05execution.ztst @@ -0,0 +1,312 @@ +%prep + + storepath=($path) + + mkdir command.tmp command.tmp/dir1 command.tmp/dir2 + + cd command.tmp + + print '#!/bin/sh\necho This is top' >tstcmd + + print '#!/bin/sh\necho This is dir1' >dir1/tstcmd + + print '#!/bin/sh\necho This is dir2' >dir2/tstcmd + + chmod 755 tstcmd dir1/tstcmd dir2/tstcmd + +%test + ./tstcmd +0:./prog execution +>This is top + + path=($ZTST_testdir/command.tmp/dir1 + $ZTST_testdir/command.tmp/dir2 + .) + tstcmd + path=($storepath) +0:path (1) +>This is dir1 + + path=(. command.tmp/dir{1,2}) + tstcmd + path=($storepath) +0:path (2) +>This is top + + functst() { print $# arguments:; print -l $*; } + functst "Eines Morgens" "als Gregor Samsa" + functst "" + functst "aus unrhigen Trumen erwachte" + foo="fand er sich in seinem Bett" + bar= + rod="zu einem ungeheuren Ungeziefer verwandelt." + functst $foo $bar $rod +# set up alias for next test + alias foo='print This is alias one' +0:function argument passing +>2 arguments: +>Eines Morgens +>als Gregor Samsa +>1 arguments: +> +>1 arguments: +>aus unrhigen Trumen erwachte +>2 arguments: +>fand er sich in seinem Bett +>zu einem ungeheuren Ungeziefer verwandelt. + + alias foo='print This is alias two' + fn() { foo; } + fn +0:Aliases in functions +>This is alias one + + foo='Global foo' + traptst() { local foo="Local foo"; trap 'print $foo' EXIT; } + traptst +0:EXIT trap environment +>Global foo + + functst() { return 0; print Ha ha; return 1; } + functst +0:return (1) + + functst() { return 1; print Ho ho; return 0; } + functst +1:return (2) + + unfunction functst + fpath=(.) + print "print This is functst." >functst + autoload functst + functst +0:autoloading (1) +>This is functst. + + unfunction functst + print "functst() { print This, too, is functst; }; print Hello." >functst + typeset -fu functst + functst + functst +0:autoloading with initialization +>Hello. +>This, too, is functst + + unfunction functst + print "print Yet another version" >functst + functst() { autoload -X; } + functst +0:autoloading via -X +>Yet another version + + chpwd() { print Changed to $PWD; } + cd . + unfunction chpwd +0q:chpwd +>Changed to $ZTST_testdir/command.tmp + + chpwd() { print chpwd: changed to $PWD; } + chpwdfn1() { print chpwdfn1: changed to $PWD; } + chpwdfn2() { print chpwdfn2: changed to $PWD; } + chpwd_functions=(chpwdfn1 '' chpwdnonexistentfn chpwdfn2) + cd . + unfunction chpwd + unset chpwd_functions +0q:chpwd_functions +>chpwd: changed to $ZTST_testdir/command.tmp +>chpwdfn1: changed to $ZTST_testdir/command.tmp +>chpwdfn2: changed to $ZTST_testdir/command.tmp + +# Hard to test periodic, precmd and preexec non-interactively. + + fn() { TRAPEXIT() { print Exit; }; } + fn +0:TRAPEXIT +>Exit + + unsetopt DEBUG_BEFORE_CMD + unfunction fn + print 'TRAPDEBUG() { + print Line $LINENO + } + : + unfunction TRAPDEBUG + ' > fn + autoload fn + fn + rm fn +0:TRAPDEBUG +>Line 1 +>Line 1 + + unsetopt DEBUG_BEFORE_CMD + unfunction fn + print 'trap '\''print Line $LINENO'\'' DEBUG + : + trap - DEBUG + ' > fn + autoload fn + fn + rm fn +0:trap DEBUG +>Line 1 +>Line 2 + + TRAPZERR() { print Command failed; } + true + false + true + false + unfunction TRAPZERR +0:TRAPZERR +>Command failed +>Command failed + + trap 'print Command failed again.' ZERR + true + false + true + false + trap - ZERR +0:trap ZERR +>Command failed again. +>Command failed again. + + false + sleep 1000 & + print $? + kill $! +0:Status reset by starting a backgrounded command +>0 + + { setopt MONITOR } 2>/dev/null + [[ -o MONITOR ]] || print -u $ZTST_fd 'Unable to change MONITOR option' + repeat 2048; do (return 2 | + return 1 | + while true; do + false + break + done; + print "${pipestatus[@]}") + ZTST_hashmark + done | sort | uniq -c | sed 's/^ *//' +0:Check whether '$pipestatus[]' behaves. +>2048 2 1 0 +F:This test checks for a bug in '$pipestatus[]' handling. If it breaks then +F:the bug is still there or it reappeared. See workers-29973 for details. + + { setopt MONITOR } 2>/dev/null + externFunc() { awk >/dev/null 2>&1; true; } + false | true | false | true | externFunc + echo $pipestatus +0:Check $pipestatus with a known difficult case +>1 0 1 0 0 +F:This similar test was triggering a reproducible failure with pipestatus. + + { unsetopt MONITOR } 2>/dev/null + coproc { read -et 5 || { print -u $ZTST_fd KILLED; kill -HUP -$$ } } + print -u $ZTST_fd 'This test takes 5 seconds to fail...' + { printf "%d\n" {1..20000} } 2>/dev/null | ( read -e ) + hang(){ printf "%d\n" {2..20000} | cat }; hang 2>/dev/null | ( read -e ) + print -p done + read -et 6 -p +0:Bug regression: piping a shell construct to an external process may hang +>1 +>2 +>done +F:This test checks for a file descriptor leak that could cause the left +F:side of a pipe to block on write after the right side has exited + + { setopt MONITOR } 2>/dev/null + if [[ -o MONITOR ]] + then + ( while :; do print "This is a line"; done ) | () : & + sleep 1 + jobs -l + else + print -u $ZTST_fd "Skipping pipe leak test, requires MONITOR option" + print "[0] 0 0" + fi +0:Bug regression: piping to anonymous function; piping to backround function +*>\[<->\] <-> <-> +F:This test checks for two different bugs, a parser segfault piping to an +F:anonymous function, and a descriptor leak when backgrounding a pipeline + + print "autoload_redir() { print Autoloaded ksh style; } >autoload.log" >autoload_redir + autoload -Uk autoload_redir + autoload_redir + print No output yet + cat autoload.log + functions autoload_redir +0: +>No output yet +>Autoloaded ksh style +>autoload_redir () { +> print Autoloaded ksh style +>} > autoload.log + +# This tests that we record the status of processes that have already exited +# for when we wait for them. +# +# Actually, we don't guarantee here that the jobs have already exited, but +# the order of the waits means it's highly likely we do need to recall a +# previous status, barring accidents which shouldn't happen very often. In +# other words, we rely on the test working repeatedly rather than just +# once. The monitor option is irrelevant to the logic, so we'll make +# our job easier by turning it off. + { unsetopt MONITOR } 2>/dev/null + (exit 1) & + one=$! + (exit 2) & + two=$! + (exit 3) & + three=$! + wait $three + print $? + wait $two + print $? + wait $one + print $? +0:The status of recently exited background jobs is recorded +>3 +>2 +>1 + +# Regression test for workers/34060 (patch in 34065) + setopt ERR_EXIT NULL_GLOB + if false; then :; else echo if:$?; fi + if false; then :; else for x in _*_; do :; done; echo for:$?; fi +0:False "if" condition handled correctly by "for" loops with ERR_EXIT +>if:1 +>for:0 + +# Regression test for workers/34065 (uses setopt from preceding test) + select x; do :; done; echo $? + select x in; do :; done; echo $? + select x in _*_; do :; done; echo $? + unsetopt ERR_EXIT NULL_GLOB +0:The status of "select" is zero when the loop body does not execute +>0 +>0 +>0 + +# Regression test for workers/36392 + print -u $ZTST_fd 'This test takes 3 seconds and hangs the shell when it fails...' + callfromchld() { true && { print CHLD } } + TRAPCHLD() { callfromchld } + sleep 2 & sleep 3; print OK +0:Background job exit does not affect reaping foreground job +>CHLD +>OK + +# Regression test for workers/39839 and workers/39844 + () { if return 11; then :; fi }; echo $? + () { while return 13; do :; done }; echo $? + () { until return 17; do :; done }; echo $? + () { until false; do return 19; done }; echo $? +0:"return" in "if" or "while" conditional +>11 +>13 +>17 +>19 + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A06assign.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A06assign.ztst new file mode 100644 index 00000000..bf39aee7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A06assign.ztst @@ -0,0 +1,631 @@ +# Tests of parameter assignments + +%prep + mkdir assign.tmp && cd assign.tmp + + touch tmpfile1 tmpfile2 + +%test + + typeset -A assoc + assoc=(one 1 two 2 odd) +1:assign to association with odd no. of values +?(eval):2: bad set of key/value pairs for associative array + +# tests of array element assignment + + array=(1 2 3 4 5) + array[1]=42 + print $array +0:Replacement of array element +>42 2 3 4 5 + + array=(1 2 3 4 5) + array[1]=(42 43) + print $array +0:Replacement of array element with array +>42 43 2 3 4 5 + + array=(1 2 3 4 5) + array[1,2]=(42 43) + print $array +0:Replacement of start of array +>42 43 3 4 5 + + array=(1 2 3 4 5) + array[1,4]=(42 43) + print $array +0:Replacement of start of array with shorter slice +>42 43 5 + + array=(1 2 3 4 5) + array[1,6]=(42 43) + print $array +0:Replacement of array by extending slice +>42 43 + + array=(1 2 3 4 5) + array[3]=(42 43) + print $array +0:Replacement of middle element with array +>1 2 42 43 4 5 + + array=(1 2 3 4 5) + array[3,4]=(42 43 44) + print $array +0:Replacement of slice in middle +>1 2 42 43 44 5 + + array=(1 2 3 4 5) + array[7,8]=(42 43) + print $array + # check that [6] was left empty... + array[6]=41 + print $array +0:Appending by replacing elements off the end +>1 2 3 4 5 42 43 +>1 2 3 4 5 41 42 43 + + array=(1 2 3 4 5) + array[-1]=42 + print $array +0:Replacement of last element of array, negative indices +>1 2 3 4 42 + + array=(1 2 3 4 5) + array[-1]=(42 43) + print $array +0:Replacement of last element of array with array, negative indices +>1 2 3 4 42 43 + + array=(1 2 3 4 5) + array[-3,-2]=(42 43 44) + print $array +0:Replacement of middle of array, negative indices +>1 2 42 43 44 5 + + array=(1 2 3 4 5) + array[-5,-1]=(42 43) + print $array +0:Replacement of entire array, negative indices +>42 43 + + array=(1 2 3 4 5) + array[-7,-1]=(42 43) + print $array +0:Replacement of more than entire array, negative indices +>42 43 + + array=(1 2 3 4 5) + array[-7]=42 + print $array +0:Replacement of element off start of array. +>42 1 2 3 4 5 + + array=(1 2 3 4 5) + array[-7]=42 + array[-6]=43 + print $array +0:Replacement off start doesn't leave gaps. Hope this is right. +>43 1 2 3 4 5 + + array=(1 2 3 4 5) + array[1,-1]=(42 43) + print $array + array[-3,3]=(1 2 3 4 5) + print $array +0:Replacement of entire array, mixed indices +>42 43 +>1 2 3 4 5 + + array=(1 2 3 4 5) + array[-7,7]=(42 43) + print $array +0:Replacement of more than entire array, mixed indices +>42 43 + + array=(1 2 3 4 5) + array[3,-2]=(42 43 44) + print $array + array[-3,5]=(100 99) + print $array +0:Replacement of slice in middle, mixed indices +>1 2 42 43 44 5 +>1 2 42 100 99 5 + +# tests of var+=scalar + + s+=foo + echo $s +0:append scalar to unset scalar +>foo + + s=foo + s+=bar + echo $s +0:append to scalar +>foobar + + set -- a b c + 2+=end + echo $2 +0:append to positional parameter +>bend + + a=(first second) + a+=last + print -l $a +0:add scalar to array +>first +>second +>last + + setopt ksharrays + a=(first second) + a+=last + print -l $a + unsetopt ksharrays +0:add scalar to array with ksharrays set +>firstlast + + a=(1 2) + a[@]+=3 + print -l $a +0:add scalar to array with alternate syntax +>1 +>2 +>3 + + integer i=10 + i+=20 + (( i == 30 )) +0:add to integer + + float f=3.4 + f+=2.3 + printf "%g\n" f +0:add to float +>5.7 + + typeset -A hash + hash=(one 1) + hash+=string + [[ $hash[@] == string ]] +0:add scalar to association + +# tests of var+=(array) + + unset a + a+=(1 2 3) + print -l $a +0:add array to unset parameter +>1 +>2 +>3 + + a=(a) + a+=(b) + print -l $a +0:add array to existing array +>a +>b + + s=foo + s+=(bar) + print -l $s +0:add array to scalar +>foo +>bar + + integer i=1 + i+=(2 3) + print -l $i +0:add array to integer +>1 +>2 +>3 + + float f=2.5 + f+=(3.5 4.5) + printf '%g\n' $f +0:add array to float +>2.5 +>3.5 +>4.5 + + typeset -A h + h+=(a 1 b 2) + print -l $h +0:add to empty association +>1 +>2 + + typeset -A h + h=(a 1) + h+=(b 2 c 3) + print -l $h +0:add to association +>1 +>2 +>3 + + typeset -A h + h=(a 1 b 2) + h+=() + print -l $h +0:add empty array to association +>1 +>2 + +# tests of var[range]+=scalar + + s=sting + s[2]+=art + echo $s +0:insert scalar inside another +>starting + + s=inert + s[-4]+=s + echo $s +0:insert scalar inside another with negative index +>insert + + s=append + s[2,6]+=age + echo $s +0:append scalar to scalar using a range +>appendage + + s=123456789 + s[3,-5]+=X + echo $s +0:insert scalar inside another, specifying a slice +>12345X6789 + + a=(a b c) + a[2]+=oo + echo $a +0:append to array element +>a boo c + + a=(a b c d) + a[-2]+=ool + echo $a +0:append to array element with negative index +>a b cool d + + a=(a b c d) + a[2,-1]+=oom + echo $a +0:append to array element, specifying a slice +>a b c doom + + setopt ksharrays + a=(a b c d) + a[0]+=0 + echo $a + unsetopt ksharrays +0:append to array element with ksharrays set +>a0 + + typeset -A h + h=(one foo) + h[one]+=bar + echo $h +0:append to association element +>foobar + + typeset -A h + h[foo]+=bar + echo ${(kv)h} +0:append to non-existent association element +>foo bar + + typeset -A h + h=(one a two b three c four d) + h[(I)*o*]+=append +1:attempt to append to slice of association +?(eval):3: h: attempt to set slice of associative array + + integer i=123 + i[2]+=6 +1:attempt to add to indexed integer variable +?(eval):2: attempt to add to slice of a numeric variable + + float f=1234.5 + f[2,4]+=3 +1:attempt to add to slice of float variable +?(eval):2: attempt to add to slice of a numeric variable + + unset u + u[3]+=third + echo $u[1]:$u[3] +0:append to unset variable with index +>:third + +# tests of var[range]+=(array) + + a=(1 2 3) + a[2]+=(a b) + echo $a +0:insert array inside another +>1 2 a b 3 + + a=(a b c) + a[-1]+=(d) + echo $a +0:append to array using negative index +>a b c d + + a=(1 2 3 4) + a[-1,-3]+=(x) + echo $a +0:insert array using negative range +>1 2 x 3 4 + + s=string + s[2]+=(a b) +1:attempt to insert array into string +?(eval):2: s: attempt to assign array value to non-array + + integer i=365 + i[2]+=(1 2) +1:attempt to insert array into string +?(eval):2: i: attempt to assign array value to non-array + + typeset -A h + h=(a 1) + h[a]+=(b 2) +1:attempt to append array to hash element +?(eval):3: h: attempt to set slice of associative array + + unset u + u[-34,-2]+=(a z) + echo $u +0:add array to indexed unset variable +>a z + + repeat 10 PATH=. echo hello +0:saving and restoring of exported special parameters +>hello +>hello +>hello +>hello +>hello +>hello +>hello +>hello +>hello +>hello + + repeat 10 FOO=BAR BAR=FOO echo $FOO $BAR +0:save and restore multiple variables around builtin +> +> +> +> +> +> +> +> +> +> + + call() { print $HELLO; } + export HELLO=world + call + HELLO=universe call + call + HELLO=${HELLO}liness call + call + unset HELLO +0:save and restore when using original value in temporary +>world +>universe +>world +>worldliness +>world + + (integer i n x + float f + setopt globassign + i=tmpfile1 + n=tmpf* + x=*2 + f=2+2 + typeset -p i n x f) +0:GLOB_ASSIGN with numeric types +>typeset -i i=0 +>typeset -a n=( tmpfile1 tmpfile2 ) +>typeset x=tmpfile2 +>typeset -E f=4.000000000e+00 + + setopt globassign + foo=tmpf* + print $foo + unsetopt globassign + foo=tmpf* + print $foo +0:GLOB_ASSIGN option +>tmpfile1 tmpfile2 +>tmpf* + + (setopt globassign + typeset -A foo + touch gatest1 gatest2 + foo=(gatest*) + print ${(t)foo} + rm -rf gatest*) +0:GLOB_ASSIGN doesn't monkey with type if not scalar assignment. +>association-local + + A=(first second) + A="${A[*]}" /bin/sh -c 'echo $A' + print -l "${A[@]}" +0:command execution with assignments shadowing array parameter +>first second +>first +>second + + setopt ksharrays + A=(first second) + A="${A[*]}" /bin/sh -c 'echo $A' + print -l "${A[@]}" + unsetopt ksharrays +0:command execution with assignments shadowing array parameter with ksharrays +>first second +>first +>second + + typeset -aU unique_array=(first second) + unique_array[1]=second + print $unique_array +0:assignment to unique array +>second + + typeset -a array=(first) + array[1,3]=(FIRST) + print $array +0:slice beyond length of array +>FIRST + +# tests of string assignments + + a="abc" + a[1]=x + print $a +0:overwrite first character in string +>xbc + + a="abc" + a[2]="x" + print $a +0:overwrite middle character in string +>axc + + a="abc" + a[3]="x" + print $a +0:overwrite last character in string +>abx + + a="abc" + a[-1]="x" + print $a +0:overwrite -1 character in string +>abx + + a="abc" + a[-2]="x" + print $a +0:overwrite -2 character (middle) in string +>axc + + a="ab" + a[-2]="x" + print $a +0:overwrite -2 character (first) in string +>xb + + a="abc" + a[-3]="x" + print $a +0:overwrite -3 character (first) in string +>xbc + + a="abc" + a[-4]="x" + print $a +0:overwrite -4 character (before first) in string +>xabc + + a="abc" + a[-5]="x" + print $a +0:overwrite -5 character (before-before first) in string +>xabc + + a="abc" + a[-4,0]="x" + print $a +0:overwrite [-4,0] characters (before first) in string +>xabc + + a="abc" + a[-4,-4]="x" + print $a +0:overwrite [-4,-4] character (before first) in string +>xabc + + a="abc" + a[-40,-30]="x" + print $a +0:overwrite [-40,-30] characters (far before first) in string +>xabc + + a="abc" + a[-40,1]="x" + print $a +0:overwrite [-40,1] characters in short string +>xbc + + a="abc" + a[-40,40]="x" + print $a +0:overwrite [-40,40] characters in short string +>x + + a="abc" + a[2,40]="x" + print $a +0:overwrite [2,40] characters in short string +>ax + + a="abc" + a[2,-1]="x" + print $a +0:overwrite [2,-1] characters in short string +>ax + + a="abc" + a[-2,-1]="x" + print $a +0:overwrite [-2,-1] characters in short string +>ax + + a="a" + a[-1]="xx" + print $a +0:overwrite [-1] character with "xx" +>xx + + a="a" + a[-2]="xx" + print $a +0:overwrite [-2] character (before first) with "xx" +>xxa + + a="a" + a[2]="xx" + print $a +0:overwrite [2] character (after last) with "xx" +>axx + + a="" + a[1]="xx" + print $a +0:overwrite [1] character (string: "") with "xx" +>xx + + a="" + a[-1]="xx" + print $a +0:overwrite [-1] character (string: "") with "xx" +>xx + + a="" + a[2]="xx" + print $a +0:overwrite [2] character (string: "") with "xx" +>xx diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A07control.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A07control.ztst new file mode 100644 index 00000000..b1a24873 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/A07control.ztst @@ -0,0 +1,165 @@ +# Test control commands for loops and functions. + +%test + + fn3() { return $1; print Error } + fn2() { fn3 $1 } + fn() { + print start $1 + fn2 $1 + return + print Error + } + for val in -1 0 1 255; do + fn $val; print $? + done +0:Passing of return values back through functions +>start -1 +>-1 +>start 0 +>0 +>start 1 +>1 +>start 255 +>255 + + $ZTST_testdir/../Src/zsh -fc 'fn() { + continue + } + fn' +1:continue outside loop +?fn:continue:1: not in while, until, select, or repeat loop + + for outer in 0 1 2 3; do + print outer $outer + for inner in 0 1 2 3; do + print inner $inner + continue $(( (outer & 1) ? 2 : 1 )) + print error + done + print outer end + done +0:continue with valid argument +>outer 0 +>inner 0 +>inner 1 +>inner 2 +>inner 3 +>outer end +>outer 1 +>inner 0 +>outer 2 +>inner 0 +>inner 1 +>inner 2 +>inner 3 +>outer end +>outer 3 +>inner 0 + + for outer in 0 1; do + continue 0 + print -- $outer got here, status $? + done +1:continue error case 0 +?(eval):continue:2: argument is not positive: 0 + + for outer in 0 1; do + continue -1 + print -- $outer got here, status $? + done +1:continue error case -1 +?(eval):continue:2: argument is not positive: -1 + + fn() { + break + } + for outer in 0 1; do + print $outer + fn + done +0:break from within function (this is a feature, I disovered) +>0 + + for outer in 0 1 2 3; do + print outer $outer + for inner in 0 1 2 3; do + print inner $inner + break $(( (outer & 1) ? 2 : 1 )) + print error + done + print outer end + done +0:break with valid argument +>outer 0 +>inner 0 +>outer end +>outer 1 +>inner 0 + + for outer in 0 1; do + break 0 + print -- $outer got here, status $? + done +1:break error case 0 +?(eval):break:2: argument is not positive: 0 + + for outer in 0 1; do + break -1 + print -- $outer got here, status $? + done +1:break error case -1 +?(eval):break:2: argument is not positive: -1 + + false + for x in; do + print nothing executed + done +0:Status 0 from for with explicit empty list + + set -- + false + for x; do + print nothing executed + done +0:Status 0 from for with implicit empty list + + (exit 2) + for x in 1 2; do + print $? + done +0:Status from previous command propagated into for loop +>2 +>0 + + false + for x in $(echo 1 2; (exit 3)); do + print $? + done +0:Status from expansion propagated into for loop +>3 +>0 + + false + for x in $(exit 4); do + print not executed + done +0:Status from expansion not propagated after unexecuted for loop + + false + for x in NonExistentFilePrefix*(N); do + print not executed, either + done +0:Status from before for loop not propagated if empty after expansion + + for x in $(echo 1; false); do + done +0:Status reset by empty list in for loop + + false + for x in $(echo 1; false); do + echo $? + (exit 4) + done +4:Last status from loop body is kept even with other funny business going on +>1 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B01cd.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B01cd.ztst new file mode 100644 index 00000000..94447e71 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B01cd.ztst @@ -0,0 +1,144 @@ +# This file serves as a model for how to write tests, so is more heavily +# commented than the others. All tests are run in the Test subdirectory +# of the distribution, which must be writable. They should end with +# the suffix `.ztst': this is not required by the test harness itself, +# but it is needed by the Makefile to run all the tests. + +# Blank lines with no other special meaning (e.g. separating chunks of +# code) and all those with a `#' in the first column are ignored. + +# All section names start with a % in the first column. The names +# must be in the expected order, though not all sections are required. +# The sections are %prep (preparatory setup: code executed should return +# status 0, but no other tests are performed), %test (the main tests), and +# %clean (to cleanup: the code is simply unconditionally executed). +# +# Literal shell code to be evaluated must be indented with any number +# of spaces and/or tabs, to differentiate it from tags with a special +# meaning to the test harness. Note that this is true even in sections +# where there are no such tags. Also note that file descriptor 9 +# is reserved for input from the test script, and file descriptor 8 +# preserves the original stdout. Option settings are preserved between the +# execution of different code chunks; initially, all standard zsh options +# (the effect of `emulate -R zsh') are set. + +%prep +# This optional section prepares the test, creating directories and files +# and so on. Chunks of code are separated by blank lines (which is not +# necessary before the end of the section); each chunk of code is evaluated +# in one go and must return status 0, or the preparation is deemed to have +# failed and the test ends with an appropriate error message. Standard +# output from this section is redirected to /dev/null, but standard error +# is not redirected. +# +# Tests should use subdirectories ending in `.tmp'. These will be +# removed with all the contents even if the test is aborted. + mkdir cdtst.tmp cdtst.tmp/real cdtst.tmp/sub + + ln -s ../real cdtst.tmp/sub/fake + + setopt chaselinks + cd . + unsetopt chaselinks + mydir=$PWD + +%test +# This is where the tests are run. It consists of blocks separated +# by blank lines. Each block has the same format and there may be any +# number of them. It consists of indented code, plus optional sets of lines +# beginning '<', '>' and '?' which may appear in any order. These correspond +# to stdin (fed to the code), stdout (compared with code output) and +# stderr (compared with code error output) respectively. These subblocks +# may occur in any order, but the natural one is: code, stdin, stdout, +# stderr. +# +# The rules for '<', '>' and '?' lines are the same: only the first +# character is stripped (with the excpetion for '*' noted below), with +# subsequent whitespace being significant; lines are not subject to any +# substitution unless the `q' flag (see below) is set. +# +# Each line of a '>' and '?' chunk may be preceded by a '*', so the line +# starts '*>' or '*?'. This signifies that for any line with '*' in front +# the actual output should be pattern matched against the corresponding +# lines in the test output. Each line following '>' or '?' must be a +# valid pattern, so characters special to patterns such as parentheses +# must be quoted with a backslash. The EXTENDED_GLOB option is used for +# all such patterns. +# +# Each chunk of indented code is to be evaluated in one go and is to +# be followed by a line starting (in the first column) with +# the expected status returned by the code when run, or - if it is +# irrelevant. An optional set of single-letter flags follows the status +# or -. The following are understood: +# . d Don't diff stdout against the expected stdout. +# D Don't diff stderr against the expected stderr. +# q All redirection lines given in the test script (not the lines +# actually produced by the test) are subject to ordinary quoted shell +# expansion (i.e. not globbing). +# This can be followed by a `:' and a message describing the +# test, which will be printed if the test fails, along with a +# description of the failure that occurred. The `:' and message are +# optional, but highly recommended. +# Hence a complete status line looks something like: +# 0dDq:Checking whether the world will end with a bang or a whimper +# +# If either or both of the '>' and '?' sets of lines is absent, it is +# assumed the corresponding output should be empty and it is an error if it +# is not. If '<' is empty, stdin is an empty (but opened) file. +# +# It is also possible to add lines in the redirection section beginning +# with `F:'. The remaining text on all such lines will be concatenated +# (with newlines in between) and displayed in the event of an error. +# This text is useful for explaining certain frequent errors, for example +# ones which may arise from the environment rather than from the shell +# itself. (The example below isn't particularly useful as errors with +# `cd' are unusual.) +# +# A couple of features aren't used in this file, but are usefuil in cases +# where features may not be available so should not be tested. They boh +# take the form of variables. Note that to keep the test framework simple +# there is no magic in setting the variables: the chunk of code being +# executed needs to avoid executing any test code by appropriate structure +# (typically "if"). In both cases, the value of the variable is output +# as a warning that the test was skipped. +# ZTST_unimplemented: Set this in the %prep phase if the entire test file +# is to be skipped. +# ZTST_skip: Set this in any test case if that single test case is to be +# skipped. Testing resumes at the next test case in the same file. + cd cdtst.tmp/sub/fake && + pwd && + print $PWD +0q:Preserving symbolic links in the current directory string +>$mydir/cdtst.tmp/sub/fake +>$mydir/cdtst.tmp/sub/fake +F:This test shouldn't really fail. The fact that it has indicates +F:something is broken. But you already knew that. + + cd ../../.. && + pwd && + print $PWD +0q:Changing directory up through symbolic links without following them +>$mydir +>$mydir + + setopt chaselinks + cd cdtst.tmp/sub/fake && + pwd && + print $PWD +0q:Resolving symbolic links with chaselinks set +>$mydir/cdtst.tmp/real +>$mydir/cdtst.tmp/real + + ln -s nonexistent link_to_nonexistent + pwd1=$(pwd -P) + cd -s link_to_nonexistent + pwd2=$(pwd -P) + [[ $pwd1 = $pwd2 ]] || print "Ooops, changed to directory '$pwd2'" +0: +?(eval):cd:3: not a directory: link_to_nonexistent + +%clean +# This optional section cleans up after the test, if necessary, +# e.g. killing processes etc. This is in addition to the removal of *.tmp +# subdirectories. This is essentially like %prep, except that status +# return values are ignored. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B02typeset.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B02typeset.ztst new file mode 100644 index 00000000..b27bb4f6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B02typeset.ztst @@ -0,0 +1,723 @@ +# There are certain usages of typeset and its synonyms that it is not +# possible to test here, because they must appear at the top level and +# everything that follows is processed by an "eval" within a function. + +# Equivalences: +# declare typeset +# export typeset -xg +# float typeset -E +# functions typeset -f +# integer typeset -i +# local typeset +g -m approximately +# readonly typeset -r + +# Tested elsewhere: +# Equivalence of autoload and typeset -fu A05execution +# Associative array creation & assignment D04parameter, D06subscript +# Effects of GLOBAL_EXPORT E01options +# Function tracing (typeset -ft) E02xtrace + +# Not yet tested: +# Assorted illegal flag combinations + +%prep + ## Do not remove the next line, it's used by V10private.ztst + # test_zsh_param_private + + mkdir typeset.tmp && cd typeset.tmp + + setopt noglob + + scalar=scalar + array=(a r r a y) + + scope00() { + typeset scalar + scalar=local + typeset -a array + array=(l o c a l) + print $scalar $array + } + scope01() { + local scalar + scalar=local + local -a array + array=(l o c a l) + print $scalar $array + } + scope02() { + declare scalar + scalar=local + declare -a array + array=(l o c a l) + print $scalar $array + } + scope10() { + export outer=outer + /bin/sh -fc 'echo $outer' + } + scope11() { + typeset -x outer=outer + /bin/sh -fc 'echo $outer' + } + scope12() { + local -x outer=inner + /bin/sh -fc 'echo $outer' + } + scope13() { + local -xT OUTER outer + outer=(i n n e r) + /bin/sh -fc 'echo $OUTER' + } + + # Bug? `typeset -h' complains that ! # $ * - ? @ are not identifiers. + stress00() { + typeset -h +g -m [[:alpha:]_]* + unset -m [[:alpha:]_]* + typeset +m [[:alpha:]_]* + } + +%test + + typeset +m scalar array +0:Report types of parameters with typeset +m +>scalar +>array array + + scope00 + print $scalar $array +0:Simple local declarations +>local l o c a l +>scalar a r r a y + + scope01 + print $scalar $array +0:Equivalence of local and typeset in functions +>local l o c a l +>scalar a r r a y + + scope02 + print $scalar $array +0:Basic equivalence of declare and typeset +>local l o c a l +>scalar a r r a y + + declare +m scalar +0:declare previously lacked -m/+m options +>scalar + + scope10 + print $outer +0:Global export +>outer +>outer + + scope11 + print $outer +0:Equivalence of export and typeset -x +>outer +>outer + + scope12 + print $outer +0:Local export +>inner +>outer + + float f=3.14159 + typeset +m f + float -E3 f + print $f + float -F f + print $f +0:Floating point, adding a precision, and fixed point +>float local f +>3.14e+00 +>3.142 + + integer i=3.141 + typeset +m i + integer -i2 i + print $i +0:Integer and changing the base +>integer local i +>2#11 + + float -E3 f=3.141 + typeset +m f + integer -i2 f + typeset +m f + print $f +0:Conversion of floating point to integer +>float local f +>integer 2 local f +>2#11 + + typeset -f +0q:Equivalence of functions and typeset -f +>$(functions) + + readonly r=success + print $r + r=failure +1:Readonly declaration +>success +?(eval):3: read-only variable: r + + typeset r=success + readonly r + print $r + r=failure +1:Convert to readonly +>success +?(eval):4: read-only variable: r + + typeset -gU array + print $array +0:Uniquified arrays and non-local scope +>a r y + + typeset -T SCALAR=l:o:c:a:l array + print $array + typeset -U SCALAR + print $SCALAR $array +0:Tied parameters and uniquified colon-arrays +>l o c a l +>l:o:c:a l o c a + + (setopt NO_multibyte cbases + LC_ALL=C 2>/dev/null + typeset -T SCALAR=$'l\x83o\x83c\x83a\x83l' array $'\x83' + print $array + typeset -U SCALAR + for (( i = 1; i <= ${#SCALAR}; i++ )); do + char=$SCALAR[i] + print $(( [#16] #char )) + done + print $array) +0:Tied parameters and uniquified arrays with meta-character as separator +>l o c a l +>0x6C +>0x83 +>0x6F +>0x83 +>0x63 +>0x83 +>0x61 +>l o c a + + typeset -T SCALAR=$'l\000o\000c\000a\000l' array $'\000' + typeset -U SCALAR + print $array + [[ $SCALAR == $'l\000o\000c\000a' ]] +0:Tied parameters and uniquified arrays with NUL-character as separator +>l o c a + + typeset -T SCALAR array + typeset +T SCALAR +1:Untying is prohibited +?(eval):typeset:2: use unset to remove tied variables + + OUTER=outer + scope13 + print $OUTER +0:Export of tied parameters +>i:n:n:e:r +>outer + + typeset -TU MORESTUFF=here-we-go-go-again morestuff '-' + print -l $morestuff +0:Tied arrays with separator specified +>here +>we +>go +>again + + typeset -T THIS will not work +1:Tied array syntax +?(eval):typeset:1: too many arguments for -T + + local array[2]=x +1:Illegal local array element assignment +?(eval):local:1: array[2]: can't create local array elements + + local -a array + typeset array[1]=a array[2]=b array[3]=c + print $array +0:Legal local array element assignment +>a b c + + local -A assoc + local b=1 ;: to stomp assoc[1] if assoc[b] is broken + typeset assoc[1]=a assoc[b]=2 assoc[3]=c + print $assoc[1] $assoc[b] $assoc[3] +0:Legal local associative array element assignment +>a 2 c + + local scalar scalar[1]=a scalar[2]=b scalar[3]=c + print $scalar +0:Local scalar subscript assignment +>abc + + typeset -L 10 fools + for fools in " once" "twice" " thrice" " oops too long here"; do + print "'$fools'" + done +0:Left justification of scalars +>'once ' +>'twice ' +>'thrice ' +>'oops too l' + + typeset -L 10 -F 3 foolf + for foolf in 1.3 4.6 -2.987 -4.91031; do + print "'$foolf'" + done +0:Left justification of floating point +>'1.300 ' +>'4.600 ' +>'-2.987 ' +>'-4.910 ' + + typeset -L 10 -Z foolzs + for foolzs in 001.3 04.6 -2.987 -04.91231; do + print "'$foolzs'" + done +0:Left justification of scalars with zero suppression +>'1.3 ' +>'4.6 ' +>'-2.987 ' +>'-04.91231 ' + + typeset -R 10 foors + for foors in short longer even-longer; do + print "'$foors'" + done +0:Right justification of scalars +>' short' +>' longer' +>'ven-longer' + + typeset -Z 10 foozs + for foozs in 42 -42 " 43" " -43"; do + print "'$foozs'" + done +0:Right justification of scalars with zeroes +>'0000000042' +>' -42' +>' 000000043' +>' -43' + + integer -Z 10 foozi + for foozi in 42 -42 " 43" " -43"; do + print "'$foozi'" + done +0:Right justification of integers with zero, no initial base +>'0000000042' +>'-000000042' +>'0000000043' +>'-000000043' +# In case you hadn't twigged, the spaces are absorbed in the initial +# math evaluation, so don't get through. + + unsetopt cbases + integer -Z 10 -i 16 foozi16 + for foozi16 in 42 -42 " 43" " -43"; do + print "'$foozi16'" + done +0:Right justification of integers with zero, base 16, C_BASES off +>'16#000002A' +>'-16#00002A' +>'16#000002B' +>'-16#00002B' + + setopt cbases + integer -Z 10 -i 16 foozi16c + for foozi16c in 42 -42 " 43" " -43"; do + print "'$foozi16c'" + done +0:Right justification of integers with zero, base 16, C_BASES on +>'0x0000002A' +>'-0x000002A' +>'0x0000002B' +>'-0x000002B' + + setopt cbases + integer -Z 10 -i 16 foozi16c + for foozi16c in 0x1234 -0x1234; do + for (( i = 1; i <= 5; i++ )); do + print "'${foozi16c[i,11-i]}'" + done + print "'${foozi16c[-2]}'" + done +0:Extracting substrings from padded integers +>'0x00001234' +>'x0000123' +>'000012' +>'0001' +>'00' +>'3' +>'-0x0001234' +>'0x000123' +>'x00012' +>'0001' +>'00' +>'3' + + typeset -F 3 -Z 10 foozf + for foozf in 3.14159 -3.14159 4 -4; do + print "'$foozf'" + done +0:Right justification of fixed point numbers with zero +>'000003.142' +>'-00003.142' +>'000004.000' +>'-00004.000' + + stress00 + print $scalar $array +0q:Stress test: all parameters are local and unset, using -m +>scalar a r y + + local parentenv=preserved + fn() { + typeset -h +g -m \* + unset -m \* + integer i=9 + float -H f=9 + declare -t scalar + declare -H -a array + typeset + typeset + + } + fn + echo $parentenv +0:Parameter hiding and tagging, printing types and values +>array local array +>float local f +>integer local i=9 +>local tagged scalar='' +>array local array +>float local f +>integer local i +>local tagged scalar +>preserved + + export ENVFOO=bar + print ENVFOO in environment + env | grep '^ENVFOO' + print Changing ENVFOO + ENVFOO="not bar any more" + env | grep '^ENVFOO' + unset ENVFOO + print ENVFOO no longer in environment + env | grep '^ENVFOO' +1:Adding and removing values to and from the environment +>ENVFOO in environment +>ENVFOO=bar +>Changing ENVFOO +>ENVFOO=not bar any more +>ENVFOO no longer in environment + + (export FOOENV=BAR + env | grep '^FOOENV' + print Exec + exec $ZTST_testdir/../Src/zsh -fc ' + print Unset + unset FOOENV + env | grep "^FOOENV"') +1:Can unset environment variables after exec +>FOOENV=BAR +>Exec +>Unset + + local case1=upper + typeset -u case1 + print $case1 + upper="VALUE OF \$UPPER" + print ${(P)case1} +0:Upper case conversion, does not apply to values used internally +>UPPER +>VALUE OF $UPPER + + local case2=LOWER + typeset -l case2 + print $case2 + LOWER="value of \$lower" + print ${(P)case2} +0:Lower case conversion, does not apply to values used internally +>lower +>value of $lower + + typeset -a array + array=(foo bar) + fn() { typeset -p array nonexistent; } + fn +1:declare -p shouldn't create scoped values +>typeset -g -a array=( foo bar ) +?fn:typeset: no such variable: nonexistent + + unsetopt typesetsilent + silent1(){ typeset -g silence; } + silent2(){ local silence; silent1; } + silent2 +0:typeset -g should be silent even without TYPESET_SILENT + + typeset -T TIED_SCALAR tied_array + TIED_SCALAR=foo:bar + print $tied_array + typeset -T TIED_SCALAR=goo:car tied_array + print $tied_array + typeset -T TIED_SCALAR tied_array=(poo par) + print $TIED_SCALAR +0:retying arrays to same array works +>foo bar +>goo car +>poo:par + + ( + setopt POSIXBUILTINS + readonly pbro + print ${+pbro} >&2 + (typeset -g pbro=3) + (pbro=4) + readonly -p pbro >&2 # shows up as "readonly" although unset + typeset -gr pbro # idempotent (no error)... + print ${+pbro} >&2 # ...so still readonly... + typeset -g +r pbro # ...can't turn it off + ) +1:readonly with POSIX_BUILTINS +?0 +?(eval):5: read-only variable: pbro +?(eval):6: read-only variable: pbro +?typeset -g -r pbro +?0 +?(eval):10: read-only variable: pbro + + readonly foo=bar novalue + readonly -p +0:readonly -p output (no readonly specials) +>typeset -r foo=bar +>typeset -r novalue='' + + local -a a1 a2 + local -r r1=yes r2=no + a1=(one two) a2=(three four) + readonly a1 + typeset -pm 'a[12]' + typeset -pm 'r[12]' +0:readonly -p output +>typeset -ar a1=( one two ) +>typeset -a a2=( three four ) +>typeset -r r1=yes +>typeset -r r2=no + + one=hidden two=hidden three=hidden four=hidden five=hidden + fn() { + local bleugh="four=vier" + typeset -R10 one=eins two=(zwei dio) three $bleugh five=(cinq cinque) + three=drei + print -l $one $two $three $four $five + } + fn + print -l $one $two $three $four $five +0:typeset reserved word interface: basic +> eins +>zwei +>dio +> drei +> vier +>cinq +>cinque +>hidden +>hidden +>hidden +>hidden +>hidden + + ( + setopt glob + mkdir -p arrayglob + touch arrayglob/{one,two,three,four,five,six,seven} + fn() { + typeset array=(arrayglob/[tf]*) + print -l ${array:t} + # + typeset {first,second,third}=the_same_value array=( + extends + over + multiple + lines + ) + print -l $first $second $third "$array" + # + integer i=$(echo 1 + 2 + 3 + 4) + print $i + # + # only noted by accident this was broken.. + # we need to turn off special recognition + # of assignments within assignments... + typeset careful=( i=1 j=2 k=3 ) + print -l $careful + } + fn + ) +0:typeset reserved word, more complicated cases +>five +>four +>three +>two +>the_same_value +>the_same_value +>the_same_value +>extends over multiple lines +>10 +>i=1 +>j=2 +>k=3 + + ( + # reserved word is recognised at parsing. + # yes, this is documented. + # anyway, that means we need to + # re-eval the function... + fn=' + fn() { + typeset foo=`echo one word=two` + print $foo + print $word + } + ' + print reserved + eval $fn; fn + print builtin + disable -r typeset + eval $fn; fn + enable -r typeset + disable typeset + print reserved + eval $fn; fn + ) +0:reserved word and builtin interfaces +>reserved +>one word=two +> +>builtin +>one +>two +>reserved +>one word=two +> + + fn() { + emulate -L zsh + setopt typeset_silent + local k + typeset -A hash=(k1 v1 k2 v2) + typeset foo=word array=(more than one word) + for k in ${(ko)hash}; do + print $k $hash[$k] + done + print -l $foo $array + typeset -A hash + typeset foo array + for k in ${(ko)hash}; do + print $k $hash[$k] + done + print -l $foo $array + typeset hash=(k3 v3 k4 v4) array=(odd number here) + for k in ${(ko)hash}; do + print $k $hash[$k] + done + print -l $array + } + fn +0:typeset preserves existing variable types +>k1 v1 +>k2 v2 +>word +>more +>than +>one +>word +>k1 v1 +>k2 v2 +>word +>more +>than +>one +>word +>k3 v3 +>k4 v4 +>odd +>number +>here + + fn() { typeset foo bar thing=this stuff=(that other) more=woevva; } + which -x2 fn + fn2() { typeset assignfirst=(why not); } + which -x2 fn2 +0:text output from typeset +>fn () { +> typeset foo bar thing=this stuff=(that other) more=woevva +>} +>fn2 () { +> typeset assignfirst=(why not) +>} + + fn() { + typeset array=() + print ${(t)array} ${#array} + typeset gnothergarray=() gnothergarray[1]=yes gnothergarray[2]=no + print -l ${(t)gnothergarray} $gnothergarray + } + fn +0:can set empty array +>array-local 0 +>array-local +>yes +>no + + array=(nothing to see here) + fn() { + typeset array=(one two three four five) + typeset array[2,4]=(umm er) + print ${#array} $array + typeset array[2,3]=() + print ${#array} $array + } + fn + print ${#array} $array +0:can update array slices in typeset +>4 one umm er five +>2 one five +>4 nothing to see here + + array=(no really nothing here) + fn() { + typeset array=() array[2]=two array[4]=four + typeset -p array + typeset array=() array[3]=three array[1]=one + typeset -p array + } + fn + print $array +0:setting empty array in typeset +>typeset -a array=( '' two '' four ) +>typeset -a array=( one '' three ) +>no really nothing here + + readonly isreadonly=yes + typeset isreadonly=still +1:typeset returns status 1 if setting readonly variable +?(eval):2: read-only variable: isreadonly + + if (( UID )); then + UID=$((UID+1)) date; echo "Status is printed, $?" + else + ZTST_skip="cannot test setuid error when tests run as superuser" + fi +0:when cannot change UID, the command isn't run +# 'date' did not run. +>Status is printed, 1 +*?*: failed to change user ID: * diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B03print.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B03print.ztst new file mode 100644 index 00000000..c65568ad --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B03print.ztst @@ -0,0 +1,336 @@ +# Tests for the echo, print, printf and pushln builtins + +# Tested elsewhere: +# Use of print -p to output to coprocess A01grammar +# Prompt expansion with print -P D01prompt +# -l, -r, -R and -n indirectly tested in various places + +# Not yet tested: +# echo and pushln +# print's -b -c -s -z -N options + + +%test + + print -D "${HOME:-~}" +0:replace directory name +>~ + + print -u2 'error message' +0:output to file-descriptor +?error message + + print -o foo bar Baz +0:argument sorting +>Baz bar foo + + print -f +1:print -f needs a format specified +?(eval):print:1: argument expected: -f + + print -Of '%s\n' foo bar baz +0:reverse argument sorting +>foo +>baz +>bar + +# some locales force case-insensitive sorting + (LC_ALL=C; print -o a B c) +0:case-sensitive argument sorting +>B a c + + (LC_ALL=C; print -io a B c) +0:case-insensitive argument sorting +>a B c + + print -m '[0-9]' one 2 three 4 five 6 +0:removal of non-matching arguments +>2 4 6 + + printf '%s\n' string +0:test s format specifier +>string + + printf '%b' '\t\\\n' +0:test b format specifier +> \ + + printf '%q\n' '=a=b \ c!' +0: test q format specifier +>\=a=b\ \\\ c! + + printf '%c\n' char +0:test c format specifier +>c + + printf '%.10e%n\n' 1 count >/dev/null + printf '%d\n' $count +0:test n format specifier +>16 + + printf '%5b%n\n' abc count >/dev/null; echo $count +0:check count of width-specified %b +>5 + + printf '%s!%5b!\n' abc +0:ensure width is applied to empty param +>abc! ! + + printf '%d %d\n' 123.45 678 90.1 +0:test d format specifier +>123 678 +>90 0 + + printf '%g %g\n' 123.45 678 90.1 +0:test g format specifier +>123.45 678 +>90.1 0 + + print -f 'arg: %b\n' -C2 '\x41' '\x42' '\x43' +0:override -C when -f was given +>arg: A +>arg: B +>arg: C + +# Is anyone not using ASCII + printf '%d\n' \'A +0:initial quote to get numeric value of character with int +>65 + + printf '%.1E\n' \'B +0:initial quote to get numeric value of character with double +>6.6E+01 + + printf '%x\n' $(printf '"\xf0') +0:numeric value of high numbered character +>f0 + + printf '\x25s\n' arg +0:using \x25 to print a literal % in format +>%s + + printf '%3c\n' c +0:width specified in format specifier +> c + + printf '%.4s\n' chopped +0:precision specified in format specifier +>chop + + printf '%*.*f\n' 6 2 10.2 +0:width/precision specified in arguments +> 10.20 + + printf '%z' +1:use of invalid directive +?(eval):printf:1: %z: invalid directive + + printf '%d\n' 3a +1:bad arithmetic expression +?(eval):1: bad math expression: operator expected at `a' +>0 + + printf '%12$s' 1 2 3 +1:out of range argument specifier +?(eval):printf:1: 12: argument specifier out of range + + printf '%2$s\n' 1 2 3 +1:out of range argument specifier on format reuse +?(eval):printf:1: 2: argument specifier out of range +>2 + + printf '%*0$d' +1:out of range argument specifier on width +?(eval):printf:1: 0: argument specifier out of range + + print -m -f 'format - %s.\n' 'z' a b c +0:format not printed if no arguments left after -m removal + + print -f 'format - %s%b.\n' +0:format printed despite lack of arguments +>format - . + + printf 'x%4sx\n' +0:with no arguments empty string where string needed +>x x + + printf '%d\n' +0:with no arguments, zero used where number needed +>0 + + printf '%s\t%c:%#x%%\n' one a 1 two b 2 three c 3 +0:multiple arguments with format reused +>one a:0x1% +>two b:0x2% +>three c:0x3% + + printf '%d%n' 123 val val val > /dev/null + printf '%d\n' val +0:%n count zeroed on format reuse +>1 + +# this may fill spec string with '%0'+- #*.*lld\0' - 14 characters + printf '%1$0'"'+- #-08.5dx\n" 123 +0:maximal length format specification +>+00123 x + + printf "x:%-20s:y\n" fubar +0:left-justification of string +>x:fubar :y + + printf '%*smorning\n' -5 good +0:negative width specified +>good morning + + printf '%.*g\n' -1 .1 +0:negative precision specified +>0.1 + + printf '%2$s %1$d\n' 1 2 +0:specify argument to output explicitly +>2 1 + + printf '%3$.*1$d\n' 4 0 3 +0:specify output and precision arguments explicitly +>0003 + + printf '%2$d%1$d\n' 1 2 3 4 +0:reuse format where arguments are explicitly specified +>21 +>43 + + printf '%1$*2$d' 1 2 3 4 5 6 7 8 9 10; echo .EoL. +0:reuse of specified arguments +> 1 3 5 7 9.EoL. + + echo -n 'Now is the time'; echo .EoL. +0:testing -n with echo +>Now is the time.EoL. + + printf '%1$0+.3d\n' 3 +0:flags mixed with specified argument +>+003 + +# Test the parsing of the \c escape. + + echo '1 2!\c3 4' a b c d; echo .EoL. +0:Truncating first echo arg using backslash-c +>1 2!.EoL. + + echo a b '1 2?\c5 6' c d; echo .EoL. +0:Truncating third echo arg using backslash-c +>a b 1 2?.EoL. + + printf '1 2!\c3 4'; echo .EoL. +0:Truncating printf literal using backslash-c +>1 2!.EoL. + + printf '%s %b!\c%s %s' 1 2 3 4 5 6 7 8 9; echo .EoL. +0:Truncating printf format using backslash-c +>1 2!.EoL. + + printf '%s %b!\c%s %s' '1\c' '2\n\c' 3 4 5 6 7 8 9 +0:Truncating printf early %b arg using backslash-c +>1\c 2 + + printf '%b %b\n' 1 2 3 4 '5\c' 6 7 8 9; echo .EoL. +0:Truncating printf late %b arg using backslash-c +>1 2 +>3 4 +>5.EoL. + +# The following usage, as stated in the manual, is not recommended and the +# results are undefined. Tests are here anyway to ensure some form of +# half-sane behaviour. + + printf '%2$s %s %3$s\n' Morning Good World +0:mixed style of argument selection +>Good Morning World + + printf '%*1$.*d\n' 1 2 +0:argument specified for width only +>00 + + print -f '%*.*1$d\n' 1 2 3 +0:argument specified for precision only +>2 +>000 + + printf -- '%s\n' str +0:initial `--' ignored to satisfy POSIX +>str + + printf '%' +1:nothing after % in format specifier +?(eval):printf:1: %: invalid directive + + printf $'%\0' +1:explicit null after % in format specifier +?(eval):printf:1: %: invalid directive + + printf '%b\n' '\0123' +0:printf handles \0... octal escapes in replacement text +>S + + print -lO $'a' $'a\0' $'a\0b' $'a\0b\0' $'a\0b\0a' $'a\0b\0b' $'a\0c' | + while read -r line; do + for (( i = 1; i <= ${#line}; i++ )); do + foo=$line[i] + printf "%02x" $(( #foo )) + done + print + done +0:sorting with embedded nulls +>610063 +>6100620062 +>6100620061 +>61006200 +>610062 +>6100 +>61 + + foo=$'one\ttwo\tthree\tfour\n' + foo+=$'\tone\ttwo\tthree\tfour\n' + foo+=$'\t\tone\t\ttwo\t\tthree\t\tfour' + print -x4 $foo + print -X4 $foo +0:Tab expansion by print +>one two three four +> one two three four +> one two three four +>one two three four +> one two three four +> one two three four + + unset foo + print -v foo once more + typeset -p foo + printf -v foo "%s\0%s-" into the breach + typeset -p foo +0:print and printf into a variable +>typeset -g foo='once more' +>typeset -g foo=$'into\C-@the-breach\C-@-' + + typeset -a foo + print -f '%2$d %4s' -v foo one 1 two 2 three 3 + typeset -p foo +0:printf into an array variable +>typeset -a foo=( '1 one' '2 two' '3 three' ) + + typeset -a foo + print -f '%s' -v foo string + typeset -p foo +0:printf to an array variable without format string reuse +>typeset foo=string + + printf - + printf - - + printf -- + printf -- - + printf -- -- + printf -x -v foo + # Final print for newline on stdout + print +0:regression test of printf with assorted ambiguous options or formats +>------x +?(eval):printf:3: not enough arguments diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B04read.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B04read.ztst new file mode 100644 index 00000000..25c3d417 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B04read.ztst @@ -0,0 +1,112 @@ +# Tests for the read builtin + +# Tested elsewhere: +# reading from a coprocess A01grammar, A04redirect + +# Not tested: +# -c/-l/-n (options for compctl functions) +# -q/-s (needs a tty) + +%test + + read <<<'hello world' + print $REPLY +0:basic read command +>hello world + + read -A <<<'hello world' + print $reply[2] +0:array read +>world + + read -k3 -u0 <<foo + + for char in y Y n N X $'\n'; do + read -q -u0 <<<$char + print $? + done +0:read yes or no, default no +>0 +>0 +>1 +>1 +>1 +>1 + + read -d: <<foo + + print foo:bar|IFS=: read -A + print $reply +0:use different, IFS separator to array +>foo bar + + print -z hello world; read -z + print $REPLY +0:read from editor buffer stack +>hello world + + unset REPLY + read -E <<hello +>hello + + unset REPLY + read -e <<hello +> + + read -e -t <<hello + + SECONDS=0 + read -e -t 5 <<hello +>0 + + print -n 'Testing the\0null hypothesis\0' | + while read -d $'\0' line; do print $line; done +0:read with null delimiter +>Testing the +>null hypothesis + +# Note that trailing NULLs are not stripped even if they are in +# $IFS; only whitespace characters contained in $IFS are stripped. + print -n $'Aaargh, I hate nulls.\0\0\0' | read line + print ${#line} +0:read with trailing metafied characters +>24 + + (typeset -r foo + read foo) <<one +>two +>three +>one:two:three + + array=() + read -Ae array <<<'four five six' + print ${(j.:.)array} +0:Behaviour of -A and -e combination +>four +>five +>six +> diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B05eval.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B05eval.ztst new file mode 100644 index 00000000..6427d6f2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B05eval.ztst @@ -0,0 +1,34 @@ +# Tests for the eval builtin. +# This is quite short; eval is widely tested throughout the test suite +# and its basic behaviour is fairly straightforward. + +%prep + + cmd='print $?' + +%test + + false + eval $cmd +0:eval retains value of $? +>1 + + # no point getting worked up over what the error message is... + ./command_not_found 2>/dev/null + eval $cmd +0:eval after command not found +>127 + + # trick the test system + sp= + false + eval " + $sp + $sp + $sp + " +0:eval with empty command resets the status + + false + eval +0:eval with empty command resets the status diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B06fc.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B06fc.ztst new file mode 100644 index 00000000..922b0010 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B06fc.ztst @@ -0,0 +1,25 @@ +# Tests of fc command +%prep + + mkdir fc.tmp + cd fc.tmp + print 'fc -l foo' >fcl + +%test + $ZTST_testdir/../Src/zsh -f ./fcl +1:Checking that fc -l foo doesn't core dump when history is empty +?./fcl:fc:1: event not found: foo + + PS1='%% ' $ZTST_testdir/../Src/zsh +Z -fsi <<< $'fc -p /dev/null 0 0\n:' +0:Checking that fc -p doesn't core dump when history size is zero +*?*%* + + PS1='%% ' $ZTST_testdir/../Src/zsh +Z -fsi <<< 'fc -p /dev/null a 0' +1:Checking that fc -p rejects non-integer history size +*?*% fc: HISTSIZE must be an integer +*?*%* + + PS1='%% ' $ZTST_testdir/../Src/zsh +Z -fsi <<< 'fc -p /dev/null 0 a' +1:Checking that fc -p rejects non-integer history save size +*?*% fc: SAVEHIST must be an integer +*?*%* diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B07emulate.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B07emulate.ztst new file mode 100644 index 00000000..2de097e2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B07emulate.ztst @@ -0,0 +1,253 @@ +# Test the "emulate" builtin and related functions. + +%prep + + isset() { + print -n "${1}: " + if [[ -o $1 ]]; then print yes; else print no; fi + } + showopts() { + # Set for Bourne shell emulation + isset shwordsplit + # Set in native mode and unless "emulate -R" is in use + isset banghist + } + cshowopts() { + showopts + # Show a csh option, too + isset cshnullglob + } + +%test + + (print Before + showopts + fn() { + emulate sh + } + fn + print After + showopts) +0:Basic use of emulate +>Before +>shwordsplit: no +>banghist: yes +>After +>shwordsplit: yes +>banghist: yes + + fn() { + emulate -L sh + print During + showopts + } + print Before + showopts + fn + print After + showopts +0:Use of emulate -L +>Before +>shwordsplit: no +>banghist: yes +>During +>shwordsplit: yes +>banghist: yes +>After +>shwordsplit: no +>banghist: yes + + (print Before + showopts + emulate -R sh + print After + showopts) +0:Use of emulate -R +>Before +>shwordsplit: no +>banghist: yes +>After +>shwordsplit: yes +>banghist: no + + print Before + showopts + emulate sh -c 'print During; showopts' + print After + showopts +0:Use of emulate -c +>Before +>shwordsplit: no +>banghist: yes +>During +>shwordsplit: yes +>banghist: yes +>After +>shwordsplit: no +>banghist: yes + + print Before + showopts + emulate -R sh -c 'print During; showopts' + print After + showopts +0:Use of emulate -R -c +>Before +>shwordsplit: no +>banghist: yes +>During +>shwordsplit: yes +>banghist: no +>After +>shwordsplit: no +>banghist: yes + + print Before + showopts + emulate -R sh -c 'shshowopts() { showopts; }' + print After definition + showopts + print In sticky emulation + shshowopts + print After sticky emulation + showopts +0:Basic sticky function emulation +>Before +>shwordsplit: no +>banghist: yes +>After definition +>shwordsplit: no +>banghist: yes +>In sticky emulation +>shwordsplit: yes +>banghist: no +>After sticky emulation +>shwordsplit: no +>banghist: yes + + print Before + cshowopts + emulate -R sh -c 'shshowopts() { cshowopts; }' + emulate csh -c 'cshshowopts() { + cshowopts + print In nested sh emulation + shshowopts + }' + print After definition + cshowopts + print In sticky csh emulation + cshshowopts + print After sticky emulation + cshowopts +0:Basic sticky function emulation +>Before +>shwordsplit: no +>banghist: yes +>cshnullglob: no +>After definition +>shwordsplit: no +>banghist: yes +>cshnullglob: no +>In sticky csh emulation +>shwordsplit: no +>banghist: yes +>cshnullglob: yes +>In nested sh emulation +>shwordsplit: yes +>banghist: no +>cshnullglob: no +>After sticky emulation +>shwordsplit: no +>banghist: yes +>cshnullglob: no + + isalp() { if [[ -o alwayslastprompt ]]; then print on; else print off; fi; } + emulate sh -c 'shfunc_inner() { setopt alwayslastprompt; }' + emulate csh -c 'cshfunc_inner() { setopt alwayslastprompt; }' + emulate sh -c 'shfunc_outer() { + unsetopt alwayslastprompt; + shfunc_inner; + isalp + unsetopt alwayslastprompt + cshfunc_inner + isalp + }' + shfunc_outer +0:Sticky emulation not triggered if sticky emulation unchanged +>on +>off + + ( + setopt ignorebraces + emulate zsh -o extendedglob -c ' + [[ -o ignorebraces ]] || print "Yay, ignorebraces was reset" + [[ -o extendedglob ]] && print "Yay, extendedglob is set" + ' + ) +0:emulate -c with options +>Yay, ignorebraces was reset +>Yay, extendedglob is set + + ( + setopt ignorebraces + emulate zsh -o extendedglob + [[ -o ignorebraces ]] || print "Yay, ignorebraces is no longer set" + [[ -o extendedglob ]] && print "Yay, extendedglob is set" + ) +0:emulate with options but no -c +>Yay, ignorebraces is no longer set +>Yay, extendedglob is set + + emulate zsh -o fixallmybugs 'print This was executed, bad' +1:emulate -c with incorrect options +?(eval):emulate:1: no such option: fixallmybugs + + emulate zsh -c ' + func() { [[ -o extendedglob ]] || print extendedglob is off } + ' + func + emulate zsh -o extendedglob -c ' + func() { [[ -o extendedglob ]] && print extendedglob is on } + ' + func +0:options specified alongside emulation are also sticky +>extendedglob is off +>extendedglob is on + + emulate zsh -o extendedglob -c ' + func_inner() { setopt nobareglobqual } + ' + emulate zsh -o extendedglob -c ' + func_outer() { + func_inner + [[ -o bareglobqual ]] || print bareglobqual was turned off + [[ -o extendedglob ]] && print extendedglob is on, though + } + ' + [[ -o extendedglob ]] || print extendedglob is initially off + func_outer +0:options propagate between identical emulations +>extendedglob is initially off +>bareglobqual was turned off +>extendedglob is on, though + + emulate zsh -o extendedglob -c ' + func_inner() { setopt nobareglobqual } + ' + emulate zsh -o extendedglob -o cbases -c ' + func_outer() { + func_inner + [[ -o bareglobqual ]] && print bareglobqual is still on + [[ -o extendedglob ]] && print extendedglob is on, too + } + ' + [[ -o extendedglob ]] || print extendedglob is initially off + func_outer +0:options do not propagate between different emulations +>extendedglob is initially off +>bareglobqual is still on +>extendedglob is on, too + + emulate sh -c '[[ a == a ]]' +0:regression test for POSIX_ALIASES reserved words +F:Some reserved tokens are handled in alias expansion diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B08shift.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B08shift.ztst new file mode 100644 index 00000000..0aa92267 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B08shift.ztst @@ -0,0 +1,33 @@ +# Test the shift builtin. + +%test + + set -- one two three four five six seven eight nine ten + shift + print $* + shift 2 + print $* + shift -p 3 + print $* + shift -p + print $* +0:shifting positional parameters +>two three four five six seven eight nine ten +>four five six seven eight nine ten +>four five six seven +>four five six + + array=(yan tan tether mether pip azer sezar akker conter dick) + shift 2 array + print $array + shift array + print $array + shift -p 3 array + print $array + shift -p array + print $array +0:shifting array +>tether mether pip azer sezar akker conter dick +>mether pip azer sezar akker conter dick +>mether pip azer sezar +>mether pip azer diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B09hash.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B09hash.ztst new file mode 100644 index 00000000..7b5dfb43 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/B09hash.ztst @@ -0,0 +1,79 @@ +# The hash builtin is most used for the command hash table, which is +# populated automatically. This is therefore highly system specific, +# so mostly we'll test with the directory hash table: the logic is +# virtually identical but with the different table, and furthermore +# the shell doesn't care whether the directory exists unless you refer +# to it in a context that needs one. + +%prep + populate_hash() { + hash -d one=/first/directory + hash -d two=/directory/the/second + hash -d three=/noch/ein/verzeichnis + hash -d four=/bored/with/this/now + } + +%test + + hash -d +0:Directory hash initially empty + + populate_hash + hash -d +0:Populating directory hash and output with sort +>four=/bored/with/this/now +>one=/first/directory +>three=/noch/ein/verzeichnis +>two=/directory/the/second + + hash -rd + hash -d +0:Empty hash + + populate_hash + hash -d +0:Refill hash +>four=/bored/with/this/now +>one=/first/directory +>three=/noch/ein/verzeichnis +>two=/directory/the/second + + hash -dL +0:hash -L option +>hash -d four=/bored/with/this/now +>hash -d one=/first/directory +>hash -d three=/noch/ein/verzeichnis +>hash -d two=/directory/the/second + + hash -dm 't*' +0:hash -m option +>three=/noch/ein/verzeichnis +>two=/directory/the/second + + hash -d five=/yet/more six=/here/we/go seven=/not/yet/eight + hash -d +0:Multiple assignments +>five=/yet/more +>four=/bored/with/this/now +>one=/first/directory +>seven=/not/yet/eight +>six=/here/we/go +>three=/noch/ein/verzeichnis +>two=/directory/the/second + + hash -d one two three +0:Multiple arguments with no assignment not in verbose mode + + hash -vd one two three +0:Multiple arguments with no assignment in verbose mode +>one=/first/directory +>two=/directory/the/second +>three=/noch/ein/verzeichnis + + hash -d t-t=/foo + i="~t-t" + print ~t-t/bar + print ${~i}/rab +0:Dashes are untokenized in directory hash names +>/foo/bar +>/foo/rab diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C01arith.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C01arith.ztst new file mode 100644 index 00000000..61da763a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C01arith.ztst @@ -0,0 +1,422 @@ +# Tests corresponding to the texinfo node `Arithmetic Evaluation' + +%test + + integer light there + (( light = 42 )) && + let 'there = light' && + print $(( there )) +0:basic integer arithmetic +>42 + + float light there + integer rnd + (( light = 3.1415 )) && + let 'there = light' && + print -- $(( rnd = there * 10000 )) +# save rounding problems by converting to integer +0:basic floating point arithmetic +>31415 + + integer rnd + (( rnd = ((29.1 % 13.0 * 10) + 0.5) )) + print $rnd +0:Test floating point modulo function +>31 + + print $(( 0x10 + 0X01 + 2#1010 )) +0:base input +>27 + + float light + (( light = 4 )) + print $light + typeset -F light + print $light +0:conversion to float +>4.000000000e+00 +>4.0000000000 + + integer i + (( i = 32.5 )) + print $i +0:conversion to int +>32 + + integer i + (( i = 4 - - 3 * 7 << 1 & 7 ^ 1 | 16 ** 2 )) + print $i +0:precedence (arithmetic) +>1591 + + fn() { + setopt localoptions c_precedences + integer i + (( i = 4 - - 3 * 7 << 1 & 7 ^ 1 | 16 ** 2 )) + print $i + } + fn +0:precedence (arithmetic, with C_PRECEDENCES) +>259 + + print $(( 1 < 2 || 2 < 2 && 3 > 4 )) +0:precedence (logical) +>1 + + print $(( 1 + 4 ? 3 + 2 ? 4 + 3 ? 5 + 6 ? 4 * 8 : 0 : 0 : 0 : 0 )) +0:precedence (ternary) +>32 + + print $(( 3 ? 2 )) +1:parsing ternary (1) +?(eval):1: bad math expression: ':' expected + + print $(( 3 ? 2 : 1 : 4 )) +1:parsing ternary (2) +?(eval):1: bad math expression: ':' without '?' + + print $(( 0, 4 ? 3 : 1, 5 )) +0:comma operator +>5 + + foo=000 + print $(( ##A + ##\C-a + #foo + $#foo )) +0:#, ## and $# +>117 + + print $((##)) +1:## without following character +?(eval):1: bad math expression: character missing after ## + + print $((## )) +0:## followed by a space +>32 + + integer i + (( i = 3 + 5 * 1.75 )) + print $i +0:promotion to float +>11 + + typeset x && + (( x = 3.5 )) && + print $x && + (( x = 4 )) && + print $x +0:use of scalars to store integers and floats +>3.5 +>4 + + (( newarray[unsetvar] = 1 )) +2:error using unset variable as index +?(eval):1: newarray: assignment to invalid subscript range + + integer setvar=1 + (( newarray[setvar]++ )) + (( newarray[setvar]++ )) + print ${(t)newarray} ${#newarray} ${newarray[1]} +0:setting array elements in math context +>array 1 2 + + xarr=() + (( xarr = 3 )) + print ${(t)xarr} $xarr +0:converting type from array +>integer 3 + + print $(( 13 = 42 )) +1:bad lvalue +?(eval):1: bad math expression: lvalue required + + x=/bar + (( x = 32 )) + print $x +0:assigning to scalar which contains non-math string +>32 + + print $(( )) +0:empty math parse e.g. $(( )) acts like a zero +>0 + + print $(( a = )) +1:empty assignment +?(eval):1: bad math expression: operand expected at end of string + + print $(( 3, )) +1:empty right hand of comma +?(eval):1: bad math expression: operand expected at end of string + + print $(( 3,,4 )) +1:empty middle of comma +?(eval):1: bad math expression: operand expected at `,4 ' + + print $(( (3 + 7, 4), 5 )) +0:commas and parentheses, part 1 +>5 + + print $(( 5, (3 + 7, 4) )) +0:commas and parentheses, part 1 +>4 + + print $(( 07.5 )) + (setopt octalzeroes; print $(( 09.5 ))) +0:leading zero doesn't affect floating point +>7.5 +>9.5 + + (setopt octalzeroes; print $(( 09 ))) +1:octalzeroes rejects invalid constants +?(eval):1: bad math expression: operator expected at `9 ' + + (setopt octalzeroes; print $(( 08#77 ))) +0:octalzeroes doesn't affect bases +>63 + + print $(( 36#z )) +0:bases up to 36 work +>35 + + print $(( 37#z )) +1:bases beyond 36 don't work +?(eval):1: invalid base (must be 2 to 36 inclusive): 37 + + print $(( 3 + "fail" )) +1:parse failure in arithmetic +?(eval):1: bad math expression: operand expected at `"fail" ' + + alias 3=echo + print $(( 3 + "OK"); echo "Worked") +0:not a parse failure because not arithmetic +>+ OK Worked + + fn() { + emulate -L zsh + print $(( [#16] 255 )) + print $(( [##16] 255 )) + setopt cbases + print $(( [#16] 255 )) + print $(( [##16] 255 )) + } + fn +0:doubled # in base removes radix +>16#FF +>FF +>0xFF +>FF + + array=(1) + x=0 + (( array[++x]++ )) + print $x + print $#array + print $array +0:no double increment for subscript +>1 +>1 +>2 + + # This is a bit naughty... the value of array + # isn't well defined since there's no sequence point + # between the increments of x, however we just want + # to be sure that in this case, unlike the above, + # x does get incremented twice. + x=0 + array=(1 2) + (( array[++x] = array[++x] + 1 )) + print $x +0:double increment for repeated expression +>2 + + # Floating point. Default precision should take care of rounding errors. + print $(( 1_0.000_000e0_1 )) + # Integer. + print $(( 0x_ff_ff_ )) + # _ are parts of variable names that don't start with a digit + __myvar__=42 + print $(( __myvar__ + $__myvar__ )) + # _ is not part of variable name that does start with a digit + # (which are substituted before math eval) + set -- 6 + print $(( $1_000_000 )) + # Underscores in expressions with no whitespace + print $(( 3_000_+4_000_/2 )) + # Underscores may appear in the base descriptor, for what it's worth... + print $(( 1_6_#f_f_ )) +0:underscores in math constants +>100. +>65535 +>84 +>6000000 +>5000 +>255 + + # Force floating point. + for expr in "3/4" "0x100/0x200" "0x30/0x10"; do + print $(( $expr )) + setopt force_float + print $(( $expr )) + unsetopt force_float + done +0:Forcing floating point constant evaluation, or not. +>0 +>0.75 +>0 +>0.5 +>3 +>3. + + print $(( 0x30 + 0.5 )) + print $(( 077 + 0.5 )) + (setopt octalzeroes; print $(( 077 + 0.5 )) ) +0:Mixed float and non-decimal integer constants +>48.5 +>77.5 +>63.5 + + underscore_integer() { + setopt cbases localoptions + print $(( [#_] 1000000 )) + print $(( [#16_] 65536 )) + print $(( [#16_4] 65536 * 32768 )) + } + underscore_integer +0:Grouping output with underscores: integers +>1_000_000 +>0x10_000 +>0x8000_0000 + + print $(( [#_] (5. ** 10) / 16. )) +0:Grouping output with underscores: floating point +>610_351.562_5 + + env SHLVL=1+RANDOM $ZTST_testdir/../Src/zsh -f -c 'print $SHLVL' +0:Imported integer functions are not evaluated +>2 + + print $(( 0b0 + 0b1 + 0b11 + 0b110 )) +0:Binary input +>10 + + print $(( 0b2 )) +1:Binary numbers don't tend to have 2's in +?(eval):1: bad math expression: operator expected at `2 ' +# ` for emacs shell mode + + integer varassi + print $(( varassi = 5.5 / 2.0 )) + print $varassi +0:Integer variable assignment converts result to integer +>2 +>2 +# It's hard to test for integer to float. + + integer ff1=3 ff2=4 + print $(( ff1/ff2 )) + setopt force_float + print $(( ff1/ff2 )) + unsetopt force_float +0:Variables are forced to floating point where necessary +# 0.75 is exactly representable, don't expect rounding error. +>0 +>0.75 + + # The following tests for a bug that only happens when + # backing up over input read a line at a time, so we'll + # read the input from stdin. + $ZTST_testdir/../Src/zsh -f <<<' + print $((echo first command + ); echo second command) + print third command + ' +0:Backing up a line of input when finding out it's not arithmetic +>first command second command +>third command + + $ZTST_testdir/../Src/zsh -f <<<' + print $((3 + + 4)) + print next line + ' +0:Not needing to back up a line when reading multiline arithmetic +>7 +>next line + + $ZTST_testdir/../Src/zsh -f <<<' + print $((case foo in + bar) + echo not this no, no + ;; + foo) + echo yes, this one + ;; + esac) + print after case in subshell) + ' +0:Non-arithmetic subst with command subsitution parse from hell +>yes, this one after case in subshell + + print "a$((echo one subst) + (echo two subst))b" +0:Another tricky case that is actually a command substitution +>aone subst +>two substb + + print "x$((echo one frob); (echo two frob))y" +0:Same on a single line +>xone frob +>two froby + + # This case actually only works by accident: if it wasn't for the + # unbalanced parenthesis this would be a valid math substitution. + # Hence it's definitely not recommended code. However, it does give + # the algorithm an extra check. + print $((case foo in + foo) + print Worked OK + ;; + esac)) +0:Would-be math expansion with extra parenthesis making it a cmd subst +>Worked OK + + (setopt extendedglob + set -- 32.463 + print ${$(( $1 * 100 ))%%.[0-9]#}) +0:Arithmetic substitution nested in parameter substitution +>3246 + + print $((`:`)) +0:Null string in arithmetic evaluation after command substitution +>0 + + print $(( 1 + $(( 2 + 3 )) )) + print $(($((3+4)))) + print $((1*$((2*$((3))*4))*5)) +0:Nested math substitutions. Yes, I know, very useful. +>6 +>7 +>120 + + foo="(1)" + print $((foo)) + print $(($foo)) + print $(((2))) + foo="3)" + (print $((foo))) 2>&1 + (print $(($foo))) 2>&1 +1: Good and bad trailing parentheses +>1 +>1 +>2 +>(eval):6: bad math expression: unexpected ')' +>(eval):7: bad math expression: unexpected ')' + + unset number + (( number = 3 )) + print ${(t)number} + unset number + (setopt posix_identifiers + (( number = 3 )) + print ${(t)number}) +0:type of variable when created in arithmetic context +>integer +>scalar diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C02cond.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C02cond.ztst new file mode 100644 index 00000000..38525016 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C02cond.ztst @@ -0,0 +1,448 @@ +# Tests corresponding to the texinfo node `Conditional Expressions' + +%prep + + umask 077 + + mkdir cond.tmp + + cd cond.tmp + + typeset -gi isnfs + [[ "$(find . -prune -fstype nfs 2>/dev/null)" == "." ]] && isnfs=1 + if (( isnfs )) && + (cd -q ${ZTST_tmp} >/dev/null 2>&1 && + [[ "$(find . -prune -fstype nfs 2>/dev/null)" != "." ]]); then + filetmpprefix=${ZTST_tmp}/condtest-$$- + isnfs=0 + else + filetmpprefix= + fi + newnewnew=${filetmpprefix}newnewnew + unmodified=${filetmpprefix}unmodified + zlnfs=${filetmpprefix}zlnfs + + touch $unmodified + + touch zerolength + chgrp $EGID zerolength + + touch $zlnfs + chgrp $EGID $zlnfs + + print 'Garbuglio' >nonzerolength + + mkdir modish + chgrp $EGID modish + + chmod 7710 modish # g+xs,u+s,+t + chmod g+s modish # two lines combined work around chmod bugs + + touch unmodish + chmod 000 unmodish + + print 'MZ' > cmd.exe + chmod +x cmd.exe +%test + + [[ -a zerolength && ! -a nonexistent ]] +0:-a cond + + # Find a block special file system. This is a little tricky. + block=$(find /dev(|ices)/ -type b -print) + if [[ -n $block ]]; then + [[ -b $block[(f)1] && ! -b zerolength ]] + else + print -u$ZTST_fd 'Warning: Not testing [[ -b blockdevice ]] (no devices found)' + [[ ! -b zerolength ]] + fi +0D:-b cond + + # Use hardcoded /dev/tty because globbing inside /dev fails on Cygwin + char=/dev/tty + [[ -c $char && ! -c $zerolength ]] +0:-c cond + + [[ -d . && ! -d zerolength ]] +0:-d cond + + [[ -e zerolength && ! -e nonexistent ]] +0:-e cond + + if [[ -n $block ]]; then + [[ -f zerolength && ! -f cond && ! -f $char && ! -f $block[(f)1] && ! -f . ]] + else + print -u$ZTST_fd 'Warning: Not testing [[ -f blockdevice ]] (no devices found)' + [[ -f zerolength && ! -f cond && ! -f $char && ! -f . ]] + fi +0:-f cond + + [[ -g modish && ! -g zerolength ]] +0:-g cond + + ln -s zerolength link + [[ -h link && ! -h zerolength ]] +0:-h cond + + [[ -k modish && ! -k zerolength ]] +0:-k cond + + foo=foo + bar= + [[ -n $foo && ! -n $bar && ! -n '' ]] +0:-n cond + + [[ -o rcs && ! -o norcs && -o noerrexit && ! -o errexit ]] +0:-o cond + + if ! grep '#define HAVE_FIFOS' $ZTST_testdir/../config.h; then + print -u$ZTST_fd 'Warning: Not testing [[ -p pipe ]] (FIFOs not supported)' + [[ ! -p zerolength ]] + else + if whence mkfifo && mkfifo pipe || mknod pipe p; then + [[ -p pipe && ! -p zerolength ]] + else + print -u$ZTST_fd 'Warning: Not testing [[ -p pipe ]] (cannot create FIFO)' + [[ ! -p zerolength ]] + fi + fi +0dD:-p cond + + if (( EUID == 0 )); then + print -u$ZTST_fd 'Warning: Not testing [[ ! -r file ]] (root reads anything)' + [[ -r zerolength && -r unmodish ]] + elif [[ $OSTYPE = cygwin ]]; then + print -u$ZTST_fd 'Warning: Not testing [[ ! -r file ]] + (all files created by user may be readable)' + [[ -r zerolength ]] + else + [[ -r zerolength && ! -r unmodish ]] + fi +0:-r cond + + [[ -s nonzerolength && ! -s zerolength ]] +0:-s cond + +# no simple way of guaranteeing test for -t + + [[ -u modish && ! -u zerolength ]] +0:-u cond + + [[ -x cmd.exe && ! -x zerolength ]] +0:-x cond + + [[ -z $bar && -z '' && ! -z $foo ]] +0:-z cond + + [[ -L link && ! -L zerolength ]] +0:-L cond + +# hard to guarantee a file not owned by current uid + [[ -O zerolength ]] +0:-O cond + + [[ -G zerolength ]] +0:-G cond + +# can't be bothered with -S + + if [[ ${mtab::="$({mount || /sbin/mount || /usr/sbin/mount} 2>/dev/null)"} = *[(]?*[)] ]]; then + print -u $ZTST_fd 'This test takes two seconds...' + else + unmodified_ls="$(ls -lu $unmodified)" + print -u $ZTST_fd 'This test takes up to 60 seconds...' + fi + sleep 2 + touch $newnewnew + if [[ $OSTYPE == "cygwin" ]]; then + ZTST_skip="[[ -N file ]] not supported on Cygwin" + elif (( isnfs )); then + ZTST_skip="[[ -N file ]] not supported with NFS" + elif { (( ! $+unmodified_ls )) && + cat $unmodified && + { df -k -- ${$(print -r -- "$mtab" | + awk '/noatime/ {print $1,$3}'):-""} | tr -s ' ' | + fgrep -- "$(df -k . | tail -1 | tr -s ' ')" } >&/dev/null } || + { (( $+unmodified_ls )) && SECONDS=0 && + ! until (( SECONDS >= 58 )); do + ZTST_hashmark; sleep 2; cat $unmodified + [[ $unmodified_ls != "$(ls -lu $unmodified)" ]] && break + done }; then + ZTST_skip="[[ -N file ]] not supported with noatime file system" + else + [[ -N $newnewnew && ! -N $unmodified ]] + fi +0:-N cond +F:This test can fail on NFS-mounted filesystems as the access and +F:modification times are not updated separately. The test will fail +F:on HFS+ (Apple Mac OS X default) filesystems because access times +F:are not recorded. Also, Linux ext3 filesystems may be mounted +F:with the noatime option which does not update access times. +F:Failures in these cases do not indicate a problem in the shell. + + [[ $newnewnew -nt $zlnfs && ! ($unmodified -nt $zlnfs) ]] +0:-nt cond + + [[ $zlnfs -ot $newnewnew && ! ($zlnfs -ot $unmodified) ]] +0:-ot cond + + [[ link -ef zerolength && ! (link -ef nonzerolength) ]] +0:-ef cond + + [[ foo = foo && foo != bar && foo == foo && foo != '' ]] +0:=, == and != conds + + [[ bar < foo && foo > bar ]] +0:< and > conds + + [[ $(( 3 + 4 )) -eq 0x07 && $(( 5 * 2 )) -ne 0x10 ]] +0:-eq and -ne conds + + [[ 3 -lt 04 && 05 -gt 2 ]] +0:-lt and -gt conds + + [[ 3 -le 3 && ! (4 -le 3) ]] +0:-le cond + + [[ 3 -ge 3 && ! (3 -ge 4) ]] +0:-ge cond + + [[ 1 -lt 2 || 2 -lt 2 && 3 -gt 4 ]] +0:|| and && in conds + + if ! grep '#define PATH_DEV_FD' $ZTST_testdir/../config.h; then + print -u$ZTST_fd "Warning: not testing [[ -e /dev/fd/0 ]] (/dev/fd not supported)" + true + else + [[ -e /dev/fd/0 ]] + fi +0dD:/dev/fd support in conds handled by access + + if ! grep '#define PATH_DEV_FD' $ZTST_testdir/../config.h; then + print -u$ZTST_fd "Warning: not testing [[ -O /dev/fd/0 ]] (/dev/fd not supported)" + true + else + [[ -O /dev/fd/0 ]] + fi +0dD:/dev/fd support in conds handled by stat + + [[ ( -z foo && -z foo ) || -z foo ]] +1:complex conds with skipping + + [ '' != bar -a '' = '' ] +0:strings with `[' builtin + + [ `echo 0` -lt `echo 1` ] +0:substitution in `[' builtin + + [ -n foo scrimble ] +2:argument checking for [ builtin +?(eval):[:1: too many arguments + + test -n foo scramble +2:argument checking for test builtin +?(eval):test:1: too many arguments + + [ -n foo scrimble scromble ] +2:argument checking for [ builtin +?(eval):[:1: too many arguments + + test -n foo scramble scrumble +2:argument checking for test builtin +?(eval):test:1: too many arguments + + [ -n foo -a -n bar scrimble ] +2:argument checking for [ builtin +?(eval):[:1: too many arguments + + test -n foo -a -z "" scramble +2:argument checking for test builtin +?(eval):test:1: too many arguments + + fn() { + # careful: first file must exist to trigger bug + [[ -e $unmodified ]] || print Where\'s my file\? + [[ $unmodified -nt NonExistentFile ]] + print status = $? + } + fn +0:-nt shouldn't abort on non-existent files +>status = 1 + + str='string' empty='' + [[ -v IFS && -v str && -v empty && ! -v str[3] && ! -v not_a_variable ]] +0:-v cond + + arr=( 1 2 3 4 ) empty=() + [[ -v arr && -v arr[1,4] && -v arr[1] && -v arr[4] && -v arr[-4] && + -v arr[(i)3] && ! -v arr[(i)x] && + ! -v arr[0] && ! -v arr[5] && ! -v arr[-5] && ! -v arr[2][1] && + ! -v arr[3]extra && -v empty && ! -v empty[1] ]] +0:-v cond with array + + typeset -A assoc=( key val num 4 ) + [[ -v assoc && -v assoc[key] && -v assoc[(i)*] && -v assoc[(I)*] && + ! -v assoc[x] && ! -v assoc[key][1] ]] +0:-v cond with association + + () { [[ -v 0 && -v 1 && -v 2 && ! -v 3 ]] } arg '' +0:-v cond with positional parameters + +# core dumps on failure + if zmodload zsh/regex 2>/dev/null; then + echo >regex_test.sh 'if [[ $# = 1 ]]; then + if [[ $1 =~ /?[^/]+:[0-9]+:$ ]]; then + : + fi + fi + exit 0' + $ZTST_testdir/../Src/zsh -f ./regex_test.sh + fi +0:regex tests shouldn't crash + + if zmodload zsh/regex 2>/dev/null; then + ( # subshell in case coredump test failed + string="this has stuff in it" + bad_regex=0 + if [[ $string =~ "h([a-z]*) s([a-z]*) " ]]; then + if [[ "$MATCH $MBEGIN $MEND" != "has stuff 6 15" ]]; then + print -r "regex variables MATCH MBEGIN MEND: + '$MATCH $MBEGIN $MEND' + should be: + 'has stuff 6 15'" + bad_regex=1 + else + results=("as 7 8" "tuff 11 14") + for i in 1 2; do + if [[ "$match[$i] $mbegin[$i] $mend[$i]" != $results[i] ]]; then + print -r "regex variables match[$i] mbegin[$i] mend[$i]: + '$match[$i] $mbegin[$i] $mend[$i]' + should be + '$results[$i]'" + bad_regex=1 + break + fi + done + fi + (( bad_regex )) || print OK + else + print -r "regex failed to match '$string'" + fi + ) + else + # if it didn't load, tough, but not a test error + ZTST_skip="regexp library not found." + fi +0:MATCH, MBEGIN, MEND, match, mbegin, mend +>OK + + if zmodload zsh/regex 2>/dev/null; then + ( # subshell because regex module may dump core, see above + if [[ a =~ a && b == b ]]; then + print OK + else + print "regex =~ inverted following test" + fi + ) + else + # not a test error + ZTST_skip="regexp library not found." + fi +0:regex infix operator should not invert following conditions +>OK + + [[ -fail badly ]] +2:Error message for unknown prefix condition +?(eval):1: unknown condition: -fail + + [[ really -fail badly ]] +2:Error message for unknown infix condition +?(eval):1: unknown condition: -fail + + crashme() { + if [[ $1 =~ ^http:* ]] + then + url=${1#*=} + fi + } + which crashme +0:Regression test for examining code with regular expression match +>crashme () { +> if [[ $1 =~ ^http:* ]] +> then +> url=${1#*=} +> fi +>} + + weirdies=( + '! -a !' + '! -o !' + '! -a' + '! -o' + '! -a ! -a !' + '! = !' + '! !' + '= -a o' + '! = -a o') + for w in $weirdies; do + eval test $w + print $? + done +0:test compatability weirdness: treat ! as a string sometimes +>0 +>0 +>1 +>0 +>0 +>0 +>1 +>0 +>1 + + foo='' + [[ $foo ]] || print foo is empty + foo=full + [[ $foo ]] && print foo is full +0:bash compatibility with single [[ ... ]] argument +>foo is empty +>foo is full + + test -z \( || print Not zero 1 + test -z \< || print Not zero 2 + test -n \( && print Not zero 3 + test -n \) && print Not zero 4 + [ -n \> ] && print Not zero 5 + [ -n \! ] && print Not zero 6 +0:test with two arguments and a token +>Not zero 1 +>Not zero 2 +>Not zero 3 +>Not zero 4 +>Not zero 5 +>Not zero 6 + + [ '(' = ')' ] || print OK 1 + [ '((' = '))' ] || print OK 2 + [ '(' = '(' ] && print OK 3 + [ '(' non-empty-string ')' ] && echo OK 4 + [ '(' '' ')' ] || echo OK 5 +0:yet more old-fashioned test fix ups: prefer comparison to parentheses +>OK 1 +>OK 2 +>OK 3 +>OK 4 +>OK 5 + + fn() { [[ 'a' == 'b' || 'b' = 'c' || 'c' != 'd' ]] } + which -x2 fn +0: = and == appear as input +>fn () { +> [[ 'a' == 'b' || 'b' = 'c' || 'c' != 'd' ]] +>} + +%clean + # This works around a bug in rm -f in some versions of Cygwin + chmod 644 unmodish + for tmpfile in $newnewnew $unmodified $zlnfs; do + [[ -f $tmpfile ]] && rm -f $tmpfile + done diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C03traps.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C03traps.ztst new file mode 100644 index 00000000..7bc0b486 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C03traps.ztst @@ -0,0 +1,761 @@ +# Tests for both trap builtin and TRAP* functions. + +%prep + + setopt localtraps + mkdir traps.tmp && cd traps.tmp + +%test + + fn1() { + trap 'print EXIT1' EXIT + fn2() { trap 'print EXIT2' EXIT; } + fn2 + } + fn1 +0:Nested `trap ... EXIT' +>EXIT2 +>EXIT1 + + fn1() { + TRAPEXIT() { print EXIT1; } + fn2() { TRAPEXIT() { print EXIT2; }; } + fn2 + } + fn1 +0: Nested TRAPEXIT +>EXIT2 +>EXIT1 + + fn1() { + trap 'print EXIT1' EXIT + fn2() { trap - EXIT; } + fn2 + } + fn1 +0:Nested `trap - EXIT' on `trap ... EXIT' +>EXIT1 + + fn1() { + TRAPEXIT() { print EXIT1; } + fn2() { trap - EXIT; } + fn2 + } + fn1 +0:Nested `trap - EXIT' on `TRAPEXIT' +>EXIT1 + +# We can't test an EXIT trap for the shell as a whole, because +# we're inside a function scope which we don't leave when the +# subshell exits. Not sure if that's the correct behaviour, but +# it's sort of consistent. + ( fn1() { trap 'print Function 1 going' EXIT; exit; print Not reached; } + fn2() { trap 'print Function 2 going' EXIT; fn1; print Not reached; } + fn2 + ) +0:EXIT traps on functions when exiting from function +>Function 1 going +>Function 2 going + +# $ZTST_exe is relative to the parent directory. +# We ought to fix this in ztst.zsh... + (cd .. + $ZTST_exe -fc 'TRAPEXIT() { print Exited.; }') +0:EXIT traps on a script +>Exited. + + trap - + trap + trap int INT + trap sigterm SIGTERM + trap quit 3 + trap +0: Outputting traps correctly +>trap -- int INT +>trap -- quit QUIT +>trap -- sigterm TERM + + fn1() { + trap - + trap + trap 'print INT1' INT + fn2() { trap 'print INT2' INT; trap; } + trap + fn2 + trap + } + fn1 +0: Nested `trap ... INT', not triggered +>trap -- 'print INT1' INT +>trap -- 'print INT2' INT +>trap -- 'print INT1' INT + + fn1() { + trap - + trap + TRAPINT() { print INT1; } + fn2() { TRAPINT() { print INT2; }; trap; } + trap + fn2 + trap + } + fn1 +0: Nested TRAPINT, not triggered +>TRAPINT () { +> print INT1 +>} +>TRAPINT () { +> print INT2 +>} +>TRAPINT () { +> print INT1 +>} + + fn1() { + trap - + trap 'print INT1' INT + fn2() { trap - INT; trap; } + trap + fn2 + trap + } + fn1 +0: Nested `trap - INT' on untriggered `trap ... INT' +>trap -- 'print INT1' INT +>trap -- 'print INT1' INT + +# Testing the triggering of traps here is very unpleasant. +# The delays are attempts to avoid race conditions, though there is +# no guarantee that they will work. Note the subtlety that the +# `sleep' in the function which receives the trap does *not* get the +# signal, only the parent shell, which is waiting for a SIGCHILD. +# (At least, that's what I think is happening.) Thus we have to wait at +# least the full two seconds to make sure we have got the output from the +# execution of the trap. + + print -u $ZTST_fd 'This test takes at least three seconds...' + fn1() { + trap 'print TERM1' TERM + fn2() { trap 'print TERM2; return 1' TERM; sleep 2; } + fn2 & + sleep 1 + kill -TERM $! + sleep 2 + } + fn1 +0: Nested `trap ... TERM', triggered on inner loop +>TERM2 + + print -u $ZTST_fd 'This test, too, takes at least three seconds...' + fn1() { + trap 'print TERM1; return 1' TERM + fn2() { trap 'print TERM2; return 1' TERM; } + fn2 + sleep 2 + } + fn1 & + sleep 1 + kill -TERM $! + sleep 2 +0: Nested `trap ... TERM', triggered on outer loop +>TERM1 + + TRAPZERR() { print error activated; } + fn() { print start of fn; false; print end of fn; } + fn + fn() { + setopt localoptions localtraps + unfunction TRAPZERR + print start of fn + false + print end of fn + } + fn + unfunction TRAPZERR + print finish +0: basic localtraps handling +>start of fn +>error activated +>end of fn +>start of fn +>end of fn +>finish + + TRAPZERR() { print 'ERR-or!'; } + f() { print f; false; } + t() { print t; } + f + f && t + t && f && true + t && f + testunset() { + setopt localtraps + unset -f TRAPZERR + print testunset + false + true + } + testunset + f + print status $? + unfunction TRAPZERR +0: more sophisticated error trapping +>f +>ERR-or! +>f +>t +>f +>t +>f +>ERR-or! +>testunset +>f +>ERR-or! +>status 1 + + f() { + setopt localtraps + TRAPWINCH() { print "Window changed. That wrecked the test."; } + } + f + f + functions TRAPWINCH +1:Unsetting ordinary traps with localtraps. + +# +# Returns from within traps are a perennial problem. +# The following two apply to returns in and around standard +# ksh-style traps. The intention is that a return value from +# within the function is preserved (i.e. statuses set by the trap +# are ignored) unless the trap explicitly executes `return', which makes +# it return from the enclosing function. +# + fn() { trap 'true' EXIT; return 1; } + fn +1: ksh-style EXIT traps preserve return value + + inner() { trap 'return 3' EXIT; return 2; } + outer() { inner; return 1; } + outer +3: ksh-style EXIT traps can force return status of enclosing function + +# Autoloaded traps are horrid, but unfortunately people expect +# them to work if we support them. + echo "print Running exit trap" >TRAPEXIT + ${${ZTST_exe##[^/]*}:-$ZTST_testdir/$ZTST_exe} -fc ' + fpath=(. $fpath) + autoload TRAPEXIT + print "Exiting, attempt 1" + exit + print "What?" + ' + ${${ZTST_exe##[^/]*}:-$ZTST_testdir/$ZTST_exe} -fc ' + fpath=(. $fpath) + autoload TRAPEXIT; + fn() { print Some function } + fn + print "Exiting, attempt 2" + exit + ' +0: autoloaded TRAPEXIT (exit status > 128 indicates an old bug is back) +>Exiting, attempt 1 +>Running exit trap +>Some function +>Exiting, attempt 2 +>Running exit trap + + print -u $ZTST_fd Another test that takes three seconds + gotsig=0 + signal_handler() { + echo "parent received signal" + gotsig=1 + } + child() { + sleep 1 + echo "child sending signal" + kill -15 $parentpid + sleep 2 + echo "child exiting" + exit 33 + } + parentpid=$$ + child & + childpid=$! + trap signal_handler 15 + echo "parent waiting" + wait $childpid + cstatus=$? + echo "wait #1 finished, gotsig=$gotsig, status=$cstatus" + gotsig=0 + wait $childpid + cstatus=$? + echo "wait #2 finished, gotsig=$gotsig, status=$cstatus" +0:waiting for trapped signal +>parent waiting +>child sending signal +>parent received signal +>wait #1 finished, gotsig=1, status=143 +>child exiting +>wait #2 finished, gotsig=0, status=33 + + fn1() { + setopt errexit + trap 'echo error1' ZERR + false + print Shouldn\'t get here 1a + } + fn2() { + setopt errexit + trap 'echo error2' ZERR + return 1 + print Shouldn\'t get here 2a + } + fn3() { + setopt errexit + TRAPZERR() { echo error3; } + false + print Shouldn\'t get here 3a + } + fn4() { + setopt errexit + TRAPZERR() { echo error4; } + return 1 + print Shouldn\'t get here 4a + } + (fn1; print Shouldn\'t get here 1b) + (fn2; print Shouldn\'t get here 2b) + (fn3; print Shouldn\'t get here 3b) + (fn4; print Shouldn\'t get here 4b) +1: Combination of ERR_EXIT and ZERR trap +>error1 +>error2 +>error3 +>error4 + + fn1() { TRAPZERR() { print trap; return 42; }; false; print Broken; } + (fn1) + print Working $? +0: Force return of containing function from TRAPZERR. +>trap +>Working 42 + + fn2() { trap 'print trap; return 42' ZERR; false; print Broken } + (fn2) + print Working $? +0: Return with non-zero status triggered from within trap '...' ZERR. +>trap +>Working 42 + + fn3() { TRAPZERR() { print trap; return 0; }; false; print OK this time; } + (fn3) + print Working $? +0: Normal return from TRAPZERR. +>trap +>OK this time +>Working 0 + + fn4() { trap 'print trap; return 0' ZERR; false; print Broken; } + (fn4) + print Working $? +0: Return with zero status triggered from within trap '...' ZERR. +>trap +>Working 0 + + { trap 'echo This subshell is exiting' EXIT; } | cat +0: EXIT trap set in current shell at left of pipeline +>This subshell is exiting + + ( trap 'echo This subshell is also exiting' EXIT; ) | cat +0: EXIT trap set in subshell at left of pipeline +>This subshell is also exiting + + ( trap 'echo Should only appear once at the end' EXIT + ( : trap reset here ) | cat + : trap not reset but not part of shell command list | cat + echo nothing after this should appear $( : trap reset here too) + ) +0: EXIT trap set in subshell reset in subsubshell +>nothing after this should appear +>Should only appear once at the end + + echo $( trap 'echo command substitution exited' EXIT ) +0: EXIT trap set in command substitution +>command substitution exited + + (cd ..; $ZTST_exe -fc 'setopt posixtraps; + TRAPEXIT() { print Exited; } + fn1() { trap; } + setopt localtraps # should be ignored by EXIT + fn2() { TRAPEXIT() { print No, really exited; } } + fn1 + fn2 + fn1') +0:POSIX_TRAPS option +>TRAPEXIT () { +> print Exited +>} +>TRAPEXIT () { +> print No, really exited +>} +>No, really exited + + (cd ..; $ZTST_exe -fc 'unsetopt posixtraps; + echo start program + emulate sh -c '\''testfn() { + echo start function + set -o | grep posixtraps + trap "echo EXIT TRAP TRIGGERED" EXIT + echo end function + }'\'' + testfn + echo program continuing + echo end of program') +0:POSIX_TRAPS effect on EXIT trap is sticky +>start program +>start function +>noposixtraps off +>end function +>program continuing +>end of program +>EXIT TRAP TRIGGERED + + (cd ..; $ZTST_exe -fc ' + echo entering program + emulate sh -c '\''trap "echo POSIX exit trap triggered" EXIT'\'' + fn() { + trap "echo native zsh function-local exit trap triggered" EXIT + echo entering native zsh function + } + fn + echo exiting program + ') +0:POSIX EXIT trap can have nested native mode EXIT trap +>entering program +>entering native zsh function +>native zsh function-local exit trap triggered +>exiting program +>POSIX exit trap triggered + + (cd ..; $ZTST_exe -fc ' + echo entering program + emulate sh -c '\''spt() { trap "echo POSIX exit trap triggered" EXIT; }'\'' + fn() { + trap "echo native zsh function-local exit trap triggered" EXIT + echo entering native zsh function + } + spt + fn + echo exiting program + ') +0:POSIX EXIT trap not replaced if defined within function +>entering program +>entering native zsh function +>native zsh function-local exit trap triggered +>exiting program +>POSIX exit trap triggered + + (set -e + printf "a\nb\n" | while read line + do + [[ $line = a* ]] || continue + ((ctr++)) + [[ $line = foo ]] + done + echo "ctr = $ctr" + ) +1:ERREXIT in loop with simple commands + + fn() { + emulate -L zsh + setopt errreturn + if false; then + false + print No. + else + print Oh, yes + fi + } + fn +0:ERR_RETURN not triggered in if condition +>Oh, yes + + fn() { + emulate -L zsh + setopt errreturn + if true; then + false + print No. + else + print No, no. + fi + } + fn +1:ERR_RETURN in "if" + + fn() { + emulate -L zsh + setopt errreturn + if false; then + print No. + else + false + print No, no. + fi + } + fn +1:ERR_RETURN in "else" branch (regression test) + + $ZTST_testdir/../Src/zsh -f =(<<<" + if false; then + : + else + if [[ -n '' ]]; then + a=2 + fi + print Yes + fi + ") +0:ERR_RETURN when false "if" is the first statement in an "else" (regression) +>Yes +F:Must be tested with a top-level script rather than source or function + + fn() { + emulate -L zsh + setopt errreturn + print before + false + print after + } + fn +1:ERR_RETURN, basic case +>before + + fn() { + emulate -L zsh + setopt errreturn + print before + ! true + ! false + print after + } + fn +0:ERR_RETURN with "!" +>before +>after + + fn() { + emulate -L zsh + setopt errreturn + print before + ! true + ! false + false + print after + } + fn +1:ERR_RETURN with "!" and a following false +>before + + fn() { + emulate -L zsh + setopt errreturn + print before + ! if true; then + false + fi + print after + } + fn +0:ERR_RETURN with "!" suppressed inside complex structure +>before +>after + + fn() { + emulate -L zsh + setopt errreturn + print before + if true; then + false + fi + print after + } + fn +1:ERR_RETURN with no "!" suppression (control case) +>before + + (setopt err_return + fn() { + print before-in + false && false + } + print before-out + fn + print after-out + ) +1:ERR_RETURN with "&&" in function (regression test) +>before-out +>before-in + + (setopt err_return + fn() { + print before-in + false && false + print after-in + } + print before-out + fn + print after-out + ) +0:ERR_RETURN not triggered on LHS of "&&" in function +>before-out +>before-in +>after-in +>after-out + + (setopt err_return + fn() { + print before-in + true && false + print after-in + } + print before-out + fn + print after-out + ) +1:ERR_RETURN triggered on RHS of "&&" in function +>before-out +>before-in + + (setopt err_exit + for x in y; do + false && true + done + print OK + ) +0:ERR_EXIT not triggered by status 1 at end of for +>OK + + (setopt err_exit + integer x=0 + while (( ! x++ )); do + false && true + done + print OK + ) +0:ERR_EXIT not triggered by status 1 at end of while +>OK + + (setopt err_exit + repeat 1; do + false && true + done + print OK + ) +0:ERR_EXIT not triggered by status 1 at end of repeat +>OK + + (setopt err_exit + if true; then + false && true + fi + print OK + ) +0:ERR_EXIT not triggered by status 1 at end of if +>OK + + (setopt err_exit + { + false && true + } + print OK + ) +0:ERR_EXIT not triggered by status 1 at end of { } +>OK + + (setopt err_exit + for x in y; do + false + done + print OK + ) +1:ERR_EXIT triggered by status 1 within for + + (setopt err_exit + integer x=0 + while (( ! x++ )); do + false + done + print OK + ) +1:ERR_EXIT triggered by status 1 within while + + (setopt err_exit + repeat 1; do + false + done + print OK + ) +1:ERR_EXIT triggered by status 1 within repeat + + (setopt err_exit + if true; then + false + fi + print OK + ) +1:ERR_EXIT triggered by status 1 within if + + (setopt err_exit + { + false + } + print OK + ) +1:ERR_EXIT triggered by status 1 within { } + + (setopt err_exit + () { + false && true + print Still functioning + false && true + } + print OK + ) +1:ERR_EXIT triggered by status 1 at end of anon func +>Still functioning + + if zmodload zsh/system 2>/dev/null; then + ( + trap 'echo TERM; exit 2' TERM + trap 'echo EXIT' EXIT + kill -s TERM "$sysparams[pid]" + echo 'FATAL: we should never get here!' 1>&2 + exit 1 + ) + else + ZTST_skip="zsh/system library not found." + fi +2:EXIT trap from TERM trap +>TERM +>EXIT + + # Should not get "hello" in the single quotes. + ( + trap "echo hello" EXIT; + { :; } | { read line; print "'$line'"; } + ) +0:EXIT trap not called in LHS of pipeline: Shell construct on LHS +>'' +>hello + + ( + trap "echo hello" EXIT; + cat '' +>hello + +%clean + + rm -f TRAPEXIT diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C04funcdef.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C04funcdef.ztst new file mode 100644 index 00000000..0cf2b58b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C04funcdef.ztst @@ -0,0 +1,502 @@ +%prep + + mkdir funcdef.tmp + cd funcdef.tmp + setopt chaselinks + cd . + unsetopt chaselinks + mydir=$PWD + +%test + + fn1() { return 1; } + fn2() { + fn1 + print $? + return 2 + } + fn2 +2:Basic status returns from functions +>1 + + fnz() { } + false + fnz +0:Empty function body resets status + + fn3() { return 3; } + fnstat() { print $?; } + fn3 + fnstat +0:Status is not reset on non-empty function body +>3 + + function f$$ () { + print regress expansion of function names + } + f$$ +0:Regression test: 'function f$$ () { ... }' +>regress expansion of function names + + function foo () print bar + foo +0:Function definition without braces +>bar + + functions -M m1 + m1() { (( $# )) } + print $(( m1() )) + print $(( m1(1) )) + print $(( m1(1,2) )) +0:User-defined math functions, argument handling +>0 +>1 +>2 + + functions -M m2 + m2() { + integer sum + local val + for val in $*; do + (( sum += $val )) + done + } + print $(( m2(1) )) + print $(( m2(1,3+3,4**2) )) +0:User-defined math functions, complex argument handling +>1 +>23 + + functions -M m3 1 2 + m3() { (( 1 )) } + print zero + (print $(( m3() ))) + print one + print $(( m3(1) )) + print two + print $(( m3(1,2) )) + print three + (print $(( m3(1,2,3) ))) +1:User-defined math functions, argument checking +>zero +>one +>1 +>two +>1 +>three +?(eval):4: wrong number of arguments: m3() +?(eval):10: wrong number of arguments: m3(1,2,3) + + functions -M m4 0 0 testmathfunc + functions -M m5 0 0 testmathfunc + testmathfunc() { + if [[ $0 = m4 ]]; then + (( 4 )) + else + (( 5 )) + fi + } + print $(( m4() )) + print $(( m5() )) +0:User-defined math functions, multiple interfaces +>4 +>5 + + command_not_found_handler() { + print "Great News! I've handled the command:" + print "$1" + print "with arguments:" + print -l ${argv[2,-1]} + } + ACommandWhichHadBetterNotExistOnTheSystem and some "really useful" args +0:Command not found handler, success +>Great News! I've handled the command: +>ACommandWhichHadBetterNotExistOnTheSystem +>with arguments: +>and +>some +>really useful +>args + +# ' deconfuse emacs + + command_not_found_handler() { + print "Your command:" >&2 + print "$1" >&2 + print "has gone down the tubes. Sorry." >&2 + return 42 + } + ThisCommandDoesNotExistEither +42:Command not found handler, failure +?Your command: +?ThisCommandDoesNotExistEither +?has gone down the tubes. Sorry. + + local variable=outside + print "I am $variable" + function { + local variable=inside + print "I am $variable" + } + print "I am $variable" + () { + local variable="inside again" + print "I am $variable" + } + print "I am $variable" +0:Anonymous function scope +>I am outside +>I am inside +>I am outside +>I am inside again +>I am outside + + integer i + for (( i = 0; i < 10; i++ )); do function { + case $i in + ([13579]) + print $i is odd + ;| + ([2468]) + print $i is even + ;| + ([2357]) + print $i is prime + ;; + esac + }; done +0:Anonymous function with patterns in loop +>1 is odd +>2 is even +>2 is prime +>3 is odd +>3 is prime +>4 is even +>5 is odd +>5 is prime +>6 is even +>7 is odd +>7 is prime +>8 is even +>9 is odd + + echo stuff in file >file.in + function { + sed 's/stuff/rubbish/' + } file.out + cat file.out +0:Anonymous function redirection +>rubbish in file + + variable="Do be do" + print $variable + function { + print $variable + local variable="Da de da" + print $variable + function { + print $variable + local variable="Dum da dum" + print $variable + } + print $variable + } + print $variable +0:Nested anonymous functions +>Do be do +>Do be do +>Da de da +>Da de da +>Dum da dum +>Da de da +>Do be do + + () (cat $1 $2) <(print process expanded) =(print expanded to file) +0:Process substitution with anonymous functions +>process expanded +>expanded to file + + () { print This has arguments $*; } of all sorts; print After the function + function { print More stuff $*; } and why not; print Yet more +0:Anonymous function with arguments +>This has arguments of all sorts +>After the function +>More stuff and why not +>Yet more + + fn() { + (){ print Anonymous function 1 $*; } with args + function { print Anonymous function 2 $*; } with more args + print Following bit + } + functions fn +0:Text representation of anonymous function with arguments +>fn () { +> () { +> print Anonymous function 1 $* +> } with args +> () { +> print Anonymous function 2 $* +> } with more args +> print Following bit +>} + + touch yes no + () { echo $1 } (y|z)* + (echo here) + () { echo $* } some (y|z)* + () { echo empty };(echo here) +0:Anonymous function arguments and command arguments +>yes +>here +>some yes +>empty +>here + + if true; then f() { echo foo1; } else f() { echo bar1; } fi; f + if false; then f() { echo foo2; } else f() { echo bar2; } fi; f +0:Compatibility with other shells when not anonymous functions +>foo1 +>bar2 + + ( + setopt ignorebraces + fpath=(.) + print "{ echo OK }\n[[ -o ignorebraces ]] || print 'ignorebraces is off'" \ + >emufunctest + (autoload -z emufunctest; emufunctest) 2>&1 + emulate zsh -c 'autoload -Uz emufunctest' + emufunctest + [[ -o ignorebraces ]] && print 'ignorebraces is still on here' + ) +0:sticky emulation applies to autoloads and autoloaded function execution +>emufunctest:3: parse error near `\n' +>OK +>ignorebraces is off +>ignorebraces is still on here +#` (matching error message for editors parsing the file) + +# lsfoo should not be expanded as an anonymous function argument + alias lsfoo='This is not ls.' + () (echo anon func; echo "$@") lsfoo +0:Anonmous function with arguments in a form nobody sane would ever use but unfortunately we have to support anyway +>anon func +>lsfoo + + print foo | () cat +0:Simple anonymous function should not simplify enclosing pipeline +>foo + + alias fooalias=barexpansion + funcwithalias() { echo $(fooalias); } + functions funcwithalias + barexpansion() { print This is the correct output.; } + funcwithalias +0:Alias expanded in command substitution does not appear expanded in text +>funcwithalias () { +> echo $(fooalias) +>} +>This is the correct output. + + unfunction command_not_found_handler # amusing but unhelpful + alias first='firstfn1 firstfn2' second='secondfn1 secondfn2' + function first second { print This is function $0; } + first + second + firstfn1 + secondfn1 +127:No alias expansion after "function" keyword +>This is function first +>This is function second +?(eval):6: command not found: firstfn1 +?(eval):7: command not found: secondfn1 + + ( + fpath=(.) + print "print oops was successfully autoloaded" >oops + oops() { eval autoload -X } + oops + which -x2 oops + ) +0:autoload containing eval +>oops was successfully autoloaded +>oops () { +> print oops was successfully autoloaded +>} + + ( + fpath=(.) + printf '%s\n' 'oops(){}' 'ninjas-earring(){}' 'oops "$@"' >oops + autoload oops + oops + whence -v oops + ) +0q:whence -v of zsh-style autoload +>oops is a shell function from $mydir/oops + + ( + fpath=(.) + mkdir extra + print 'print "I have been loaded by explicit path."' >extra/spec + autoload -Uz $PWD/extra/spec + spec + ) +0:autoload with explicit path +>I have been loaded by explicit path. + + ( + fpath=(.) + print 'print "I have been loaded by default path."' >def + autoload -Uz $PWD/extra/def + def + ) +1:autoload with explicit path with function in normal path, no -d +?(eval):5: def: function definition file not found + + ( + fpath=(.) + autoload -dUz $PWD/extra/def + def + ) +0:autoload with explicit path with function in normal path, with -d +>I have been loaded by default path. + + ( + cd extra + fpath=(.) + autoload -r spec + cd .. + spec + ) +0:autoload -r +>I have been loaded by explicit path. + + ( + cd extra + fpath=(.) + autoload -r def + cd .. + def + ) +0:autoload -r is permissive +>I have been loaded by default path. + + ( + cd extra + fpath=(.) + autoload -R def + ) +1:autoload -R is not permissive +?(eval):4: def: function definition file not found + + ( + spec() { autoload -XUz $PWD/extra; } + spec + ) +0:autoload -X with path +>I have been loaded by explicit path. + +# The line number 1 here and in the next test seems suspect, +# but this example proves it's not down to the new features +# being tested here. + ( + fpath=(.) + cod() { autoload -XUz; } + cod + ) +1:autoload -X with no path, failure +?(eval):1: cod: function definition file not found + + ( + fpath=(.) + def() { autoload -XUz $PWD/extra; } + def + ) +1:autoload -X with wrong path and no -d +?(eval):1: def: function definition file not found + + ( + fpath=(.) + def() { autoload -dXUz $PWD/extra; } + def + ) +0:autoload -dX with path +>I have been loaded by default path. + + ( + fpath=(.) + print 'loadthisfunc() { autoload -X }' >loadthisfunc_sourceme + print 'print Function was loaded correctly.' >loadthisfunc + source $PWD/loadthisfunc_sourceme + loadthisfunc + ) +0: autoload -X interaction with absolute filename used for source location +>Function was loaded correctly. + + ( + fpath=() + mkdir extra2 + for f in fun2a fun2b; do + print "print $f" >extra2/$f + done + repeat 3; do + autoload $PWD/extra2/fun2{a,b} $PWD/extra/spec + fun2a + fun2b + spec + unfunction fun2a fun2b spec + autoload $PWD/extra2/fun2{a,b} $PWD/extra/spec + spec + fun2b + fun2a + unfunction fun2a fun2b spec + done + ) +0: Exercise the directory name cache for autoloads +>fun2a +>fun2b +>I have been loaded by explicit path. +>I have been loaded by explicit path. +>fun2b +>fun2a +>fun2a +>fun2b +>I have been loaded by explicit path. +>I have been loaded by explicit path. +>fun2b +>fun2a +>fun2a +>fun2b +>I have been loaded by explicit path. +>I have been loaded by explicit path. +>fun2b +>fun2a + + not_trashed() { print This function was not trashed; } + autoload -Uz /foo/bar/not_trashed + not_trashed +0:autoload with absolute path doesn't trash loaded function +>This function was not trashed + + # keep spec from getting loaded in parent shell for simplicity + ( + if whence spec; then print spec already loaded >&2; exit 1; fi + autoload -Uz $PWD/spec + autoload -Uz $PWD/extra/spec + spec + ) +0:autoload with absolute path can be overridden if not yet loaded +>I have been loaded by explicit path. + + ( + if whence spec; then print spec already loaded >&2; exit 1; fi + autoload -Uz $PWD/extra/spec + autoload spec + spec + ) +0:autoload with absolute path not cancelled by bare autoload +>I have been loaded by explicit path. + +%clean + + rm -f file.in file.out diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C05debug.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C05debug.ztst new file mode 100644 index 00000000..9a8df1da --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/C05debug.ztst @@ -0,0 +1,159 @@ +%prep + + setopt localtraps + +%test + + unsetopt DEBUG_BEFORE_CMD + debug-trap-bug1() { + setopt localtraps + print "print bug file here" >bug-file + print "print this is line one + print this is line two + print this is line three + print and this is line fifty-nine." >bug-file2 + function debug_trap_handler { + print $functrace[1] + do_bug + } + function do_bug { + . ./bug-file + } + trap 'echo EXIT hit' EXIT + trap 'debug_trap_handler' DEBUG + . ./bug-file2 + } + debug-trap-bug1 +0: Relationship between traps and sources +>debug-trap-bug1:15 +>bug file here +>this is line one +>./bug-file2:1 +>bug file here +>this is line two +>./bug-file2:2 +>bug file here +>this is line three +>./bug-file2:3 +>bug file here +>and this is line fifty-nine. +>./bug-file2:4 +>bug file here +>debug-trap-bug1:16 +>bug file here +>EXIT hit + + cat >zsh-trapreturn-bug2 <<-'HERE' + cmd='./fdasfsdafd' + [[ -x $cmd ]] && rm $cmd + set -o DEBUG_BEFORE_CMD + trap '[[ $? -ne 0 ]] && exit 0' DEBUG + $cmd # invalid command + # Failure + exit 10 + HERE + $ZTST_testdir/../Src/zsh -f ./zsh-trapreturn-bug2 2>erroutput.dif + mystat=$? + ( + setopt extendedglob + print ${"$(< erroutput.dif)"%%:[^:]#: ./fdasfsdafd} + ) + (( mystat == 0 )) +0: trapreturn handling bug is properly fixed +>./zsh-trapreturn-bug2:5 + + fn() { + setopt localtraps localoptions debugbeforecmd + trap '(( LINENO == 4 )) && setopt errexit' DEBUG + print $LINENO three + print $LINENO four + print $LINENO five + [[ -o errexit ]] && print "Hey, ERREXIT is set!" + } + fn +1:Skip line from DEBUG trap +>3 three +>5 five + + # Assignments are a special case, since they use a simpler + # wordcode type, so we need to test skipping them separately. + fn() { + setopt localtraps localoptions debugbeforecmd + trap '(( LINENO == 4 )) && setopt errexit' DEBUG + x=three + x=four + print $LINENO $x + [[ -o errexit ]] && print "Hey, ERREXIT is set!" + } + fn +1:Skip assignment from DEBUG trap +>5 three + + fn() { + setopt localtraps localoptions debugbeforecmd + trap 'print $LINENO' DEBUG + [[ a = a ]] && print a is ok + } + fn +0:line numbers of complex sublists +>3 +>a is ok + + fn() { + setopt localtraps localoptions debugbeforecmd + trap 'print $LINENO' DEBUG + print before + x=' first + second + third' + print $x + } + fn +0:line numbers of multiline assignments +>3 +>before +>4 +>7 +> first +> second +> third + + fn() { + emulate -L zsh; setopt debugbeforecmd + trap 'print "$LINENO: '\''$ZSH_DEBUG_CMD'\''"' DEBUG + print foo && + print bar || + print rod + x=y + print $x + fn2() { echo wow } + fn2 + } + fn +0:ZSH_DEBUG_CMD in debug traps +>3: 'print foo && print bar || print rod' +>foo +>bar +>6: 'x=y ' +>7: 'print $x' +>y +>8: 'fn2 () { +> echo wow +>}' +>9: 'fn2' +>0: 'echo wow' +>wow + + foo() { + emulate -L zsh; setopt debugbeforecmd + trap '[[ $ZSH_DEBUG_CMD == *bar* ]] && return 2' DEBUG + echo foo + echo bar + } + foo +2:Status of forced return from eval-style DEBUG trap +>foo + +%clean + + rm -f bug-file bug-file2 erroutput.dif zsh-trapreturn-bug2 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D01prompt.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D01prompt.ztst new file mode 100644 index 00000000..607ffb69 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D01prompt.ztst @@ -0,0 +1,203 @@ +%prep + + mkdir prompt.tmp + cd prompt.tmp + mydir=$PWD + SHLVL=2 + setopt extendedglob + +%test + + hash -d mydir=$mydir + print -P ' %%%): %) + %%~: %~ + %%d: %d + %%1/: %1/ + %%h: %h + %%L: %L + %%M: %M + %%m: %m + %%n: %n + %%N: %N + %%i: %i + a%%{...%%}b: a%{%}b + ' +0q:Basic prompt escapes as shown. +> %): ) +> %~: ~mydir +> %d: $mydir +> %1/: ${mydir:t} +> %h: 0 +> %L: 2 +> %M: $HOST +> %m: ${HOST%%.*} +> %n: $USERNAME +> %N: (eval) +> %i: 2 +> a%{...%}b: ab +> + + true + print -P '%?' + false + print -P '%?' +0:`%?' prompt escape +>0 +>1 + + PS4="%_> " + setopt xtrace + if true; then true; else false; fi + unsetopt xtrace +0:`%_' prompt escape +?if> true +?then> true +?> unsetopt xtrace + + diff =(print -P '%#') =(print -P '%(!.#.%%)') +0:`%#' prompt escape and its equivalent + + psvar=(caesar adsum jam forte) + print -P '%v' '%4v' +0:`%v' prompt escape +>caesar forte + + true + print -P '%(?.true.false)' + false + print -P '%(?.true.false)' +0:ternary prompt escapes +>true +>false + + print -P 'start %10<......>truncated at 10%>> Not truncated%3> ...>Not shown' +0:prompt truncation +>start ...d at 10 Not truncated ... +>start truncat... Not truncated ... + +# It's hard to check the time and date as they are moving targets. +# We therefore just check that various forms of the date are consistent. +# In fact, if you perform this at midnight it can still fail. +# We could test for that, but we can't be bothered. +# I hope LC_ALL is enough to make the format what's expected. + + LC_ALL=C + date1=$(print -P %w) + date2=$(print -P %W) + date3=$(print -P %D) + if [[ $date1 != [A-Z][a-z][a-z][[:blank:]]##[0-9]## ]]; then + print "Date \`$date1' is not in the form \`Day DD' (e.g. \`Mon 1'" + fi + if [[ $date2 != [0-9][0-9]/[0-9][0-9]/[0-9][0-9] ]]; then + print "Date \`$date2' is not in the form \`DD/MM/YYYY'" + fi + if [[ $date3 != [0-9][0-9]-[0-9][0-9]-[0-9][0-9] ]]; then + print "Date \`$date3' is not in the form \`YY-MM-DD'" + fi + if (( $date1[5,-1] != $date2[4,5] )) || (( $date2[4,5] != $date3[7,8] )) + then + print "Days of month do not agree in $date1, $date2, $date3" + fi + if (( $date2[1,2] != $date3[4,5] )); then + print "Months do not agree in $date2, $date3" + fi + if (( $date2[7,8] != $date3[1,2] )); then + print "Years do not agree in $date2, $date3" + fi +0:Dates produced by prompt escapes + + mkdir foo + mkdir foo/bar + mkdir foo/bar/rod + (zsh_directory_name() { + emulate -L zsh + setopt extendedglob + local -a match mbegin mend + if [[ $1 = d ]]; then + if [[ $2 = (#b)(*bar)/rod ]]; then + reply=(barmy ${#match[1]}) + else + return 1 + fi + else + if [[ $2 = barmy ]]; then + reply=($mydir/foo/bar) + else + return 1 + fi + fi + } + # success + print ~[barmy]/anything + cd foo/bar/rod + print -P %~ + # failure + setopt nonomatch + print ~[scuzzy]/rubbish + cd ../.. + print -P %~ + # catastrophic failure + unsetopt nonomatch + print ~[scuzzy]/rubbish + ) +1q:Dynamic named directories +>$mydir/foo/bar/anything +>~[barmy]/rod +>~[scuzzy]/rubbish +>~mydir/foo +?(eval):33: no directory expansion: ~[scuzzy] + + ( + zsh_directory_name() { + emulate -L zsh + setopt extendedglob + local -a match mbegin mend + if [[ $1 = n ]]; then + if [[ $2 = *:l ]]; then + reply=(${2%%:l}/very_long_directory_name) + return 0 + else + return 1 + fi + else + if [[ $2 = (#b)(*)/very_long_directory_name ]]; then + reply=(${match[1]}:l ${#2}) + return 0 + else + return 1 + fi + fi + } + parent=$PWD + dir=$parent/very_long_directory_name + mkdir $dir + cd $dir + fn() { + PS4='+%N:%i> ' + setopt localoptions xtrace + # The following is the key to the test. + # It invokes zsh_directory_name which does PS4 output stuff + # while we're doing prompt handling for the parameter + # substitution. This checks recursion works OK. + local d=${(%):-%~} + print ${d//$parent/\} + } + fn 2>stderr + # post process error to remove variable contents + while read line; do + # tricky: reply is set to include directory length which is variable + [[ $line = *reply* ]] && continue + print ${line//$parent/\} + done &2 + ) +0:Recursive use of prompts +>~[:l] +?+zsh_directory_name:1> emulate -L zsh +?+zsh_directory_name:2> setopt extendedglob +?+zsh_directory_name:3> local -a match mbegin mend +?+zsh_directory_name:4> [[ d = n ]] +?+zsh_directory_name:12> [[ /very_long_directory_name = (#b)(*)/very_long_directory_name ]] +?+zsh_directory_name:14> return 0 +?+fn:7> local d='~[:l]' +?+fn:8> print '~[:l]' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D02glob.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D02glob.ztst new file mode 100644 index 00000000..1385d57d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D02glob.ztst @@ -0,0 +1,688 @@ +# Tests for globbing + +%prep + mkdir glob.tmp + mkdir glob.tmp/dir{1,2,3,4} + mkdir glob.tmp/dir3/subdir + : >glob.tmp/{,{dir1,dir2}/}{a,b,c} + + globtest () { + $ZTST_testdir/../Src/zsh -f $ZTST_srcdir/../Misc/$1 + } + + regress_absolute_path_and_core_dump() { + local absolute_dir=$(cd glob.tmp && pwd -P) + [[ -n $absolute_dir ]] || return 1 + setopt localoptions extendedglob nullglob + print $absolute_dir/**/*~/* + setopt nonullglob nomatch + print glob.tmp/**/*~(.)# + } + +%test + + globtest globtests +0:zsh globbing +>0: [[ foo~ = foo~ ]] +>0: [[ foo~ = (foo~) ]] +>0: [[ foo~ = (foo~|) ]] +>0: [[ foo.c = *.c~boo* ]] +>1: [[ foo.c = *.c~boo*~foo* ]] +>0: [[ fofo = (fo#)# ]] +>0: [[ ffo = (fo#)# ]] +>0: [[ foooofo = (fo#)# ]] +>0: [[ foooofof = (fo#)# ]] +>0: [[ fooofoofofooo = (fo#)# ]] +>1: [[ foooofof = (fo##)# ]] +>1: [[ xfoooofof = (fo#)# ]] +>1: [[ foooofofx = (fo#)# ]] +>0: [[ ofxoofxo = ((ofo#x)#o)# ]] +>1: [[ ofooofoofofooo = (fo#)# ]] +>0: [[ foooxfooxfoxfooox = (fo#x)# ]] +>1: [[ foooxfooxofoxfooox = (fo#x)# ]] +>0: [[ foooxfooxfxfooox = (fo#x)# ]] +>0: [[ ofxoofxo = ((ofo#x)#o)# ]] +>0: [[ ofoooxoofxo = ((ofo#x)#o)# ]] +>0: [[ ofoooxoofxoofoooxoofxo = ((ofo#x)#o)# ]] +>0: [[ ofoooxoofxoofoooxoofxoo = ((ofo#x)#o)# ]] +>1: [[ ofoooxoofxoofoooxoofxofo = ((ofo#x)#o)# ]] +>0: [[ ofoooxoofxoofoooxoofxooofxofxo = ((ofo#x)#o)# ]] +>0: [[ aac = ((a))#a(c) ]] +>0: [[ ac = ((a))#a(c) ]] +>1: [[ c = ((a))#a(c) ]] +>0: [[ aaac = ((a))#a(c) ]] +>1: [[ baaac = ((a))#a(c) ]] +>0: [[ abcd = ?(a|b)c#d ]] +>0: [[ abcd = (ab|ab#)c#d ]] +>0: [[ acd = (ab|ab#)c#d ]] +>0: [[ abbcd = (ab|ab#)c#d ]] +>0: [[ effgz = (bc##d|ef#g?|(h|)i(j|k)) ]] +>0: [[ efgz = (bc##d|ef#g?|(h|)i(j|k)) ]] +>0: [[ egz = (bc##d|ef#g?|(h|)i(j|k)) ]] +>0: [[ egzefffgzbcdij = (bc##d|ef#g?|(h|)i(j|k))# ]] +>1: [[ egz = (bc##d|ef##g?|(h|)i(j|k)) ]] +>0: [[ ofoofo = (ofo##)# ]] +>0: [[ oxfoxoxfox = (oxf(ox)##)# ]] +>1: [[ oxfoxfox = (oxf(ox)##)# ]] +>0: [[ ofoofo = (ofo##|f)# ]] +>0: [[ foofoofo = (foo|f|fo)(f|ofo##)# ]] +>0: [[ oofooofo = (of|oofo##)# ]] +>0: [[ fffooofoooooffoofffooofff = (f#o#)# ]] +>1: [[ fffooofoooooffoofffooofffx = (f#o#)# ]] +>0: [[ fofoofoofofoo = (fo|foo)# ]] +>0: [[ foo = ((^x)) ]] +>0: [[ foo = ((^x)*) ]] +>1: [[ foo = ((^foo)) ]] +>0: [[ foo = ((^foo)*) ]] +>0: [[ foobar = ((^foo)) ]] +>0: [[ foobar = ((^foo)*) ]] +>1: [[ foot = z*~*x ]] +>0: [[ zoot = z*~*x ]] +>1: [[ foox = z*~*x ]] +>1: [[ zoox = z*~*x ]] +>0: [[ moo.cow = (*~*.*).(*~*.*) ]] +>1: [[ mad.moo.cow = (*~*.*).(*~*.*) ]] +>0: [[ moo.cow = (^*.*).(^*.*) ]] +>1: [[ sane.moo.cow = (^*.*).(^*.*) ]] +>1: [[ mucca.pazza = mu(^c#)?.pa(^z#)? ]] +>1: [[ _foo~ = _(|*[^~]) ]] +>0: [[ fff = ((^f)) ]] +>0: [[ fff = ((^f)#) ]] +>0: [[ fff = ((^f)##) ]] +>0: [[ ooo = ((^f)) ]] +>0: [[ ooo = ((^f)#) ]] +>0: [[ ooo = ((^f)##) ]] +>0: [[ foo = ((^f)) ]] +>0: [[ foo = ((^f)#) ]] +>0: [[ foo = ((^f)##) ]] +>1: [[ f = ((^f)) ]] +>1: [[ f = ((^f)#) ]] +>1: [[ f = ((^f)##) ]] +>0: [[ foot = (^z*|*x) ]] +>1: [[ zoot = (^z*|*x) ]] +>0: [[ foox = (^z*|*x) ]] +>0: [[ zoox = (^z*|*x) ]] +>0: [[ foo = (^foo)# ]] +>1: [[ foob = (^foo)b* ]] +>0: [[ foobb = (^foo)b* ]] +>1: [[ foob = (*~foo)b* ]] +>0: [[ foobb = (*~foo)b* ]] +>1: [[ zsh = ^z* ]] +>0: [[ a%1X = [[:alpha:][:punct:]]#[[:digit:]][^[:lower:]] ]] +>1: [[ a%1 = [[:alpha:][:punct:]]#[[:digit:]][^[:lower:]] ]] +>0: [[ [: = [[:]# ]] +>0: [[ :] = []:]# ]] +>0: [[ :] = [:]]# ]] +>0: [[ [ = [[] ]] +>0: [[ ] = []] ]] +>0: [[ [] = [^]]] ]] +>0: [[ fooxx = (#i)FOOXX ]] +>1: [[ fooxx = (#l)FOOXX ]] +>0: [[ FOOXX = (#l)fooxx ]] +>1: [[ fooxx = (#i)FOO(#I)X(#i)X ]] +>0: [[ fooXx = (#i)FOO(#I)X(#i)X ]] +>0: [[ fooxx = ((#i)FOOX)x ]] +>1: [[ fooxx = ((#i)FOOX)X ]] +>1: [[ BAR = (bar|(#i)foo) ]] +>0: [[ FOO = (bar|(#i)foo) ]] +>0: [[ Modules = (#i)*m* ]] +>0: [[ fooGRUD = (#i)(bar|(#I)foo|(#i)rod)grud ]] +>1: [[ FOOGRUD = (#i)(bar|(#I)foo|(#i)rod)grud ]] +>0: [[ readme = (#i)readme~README|readme ]] +>0: [[ readme = (#i)readme~README|readme~README ]] +>0: [[ 633 = <1-1000>33 ]] +>0: [[ 633 = <-1000>33 ]] +>0: [[ 633 = <1->33 ]] +>0: [[ 633 = <->33 ]] +>0: [[ 12345678901234567890123456789012345678901234567890123456789012345678901234567890foo = <42->foo ]] +>0: [[ READ.ME = (#ia1)readme ]] +>1: [[ READ..ME = (#ia1)readme ]] +>0: [[ README = (#ia1)readm ]] +>0: [[ READM = (#ia1)readme ]] +>0: [[ README = (#ia1)eadme ]] +>0: [[ EADME = (#ia1)readme ]] +>0: [[ READEM = (#ia1)readme ]] +>1: [[ ADME = (#ia1)readme ]] +>1: [[ README = (#ia1)read ]] +>0: [[ bob = (#a1)[b][b] ]] +>1: [[ bob = (#a1)[b][b]a ]] +>0: [[ bob = (#a1)[b]o[b]a ]] +>1: [[ bob = (#a1)[c]o[b] ]] +>0: [[ abcd = (#a2)XbcX ]] +>0: [[ abcd = (#a2)ad ]] +>0: [[ ad = (#a2)abcd ]] +>0: [[ abcd = (#a2)bd ]] +>0: [[ bd = (#a2)abcd ]] +>0: [[ badc = (#a2)abcd ]] +>0: [[ adbc = (#a2)abcd ]] +>1: [[ dcba = (#a2)abcd ]] +>0: [[ dcba = (#a3)abcd ]] +>0: [[ aabaXaaabY = (#a1)(a#b)#Y ]] +>0: [[ aabaXaaabY = (#a1)(a#b)(a#b)Y ]] +>0: [[ aaXaaaaabY = (#a1)(a#b)(a#b)Y ]] +>0: [[ aaaXaaabY = (#a1)(a##b)##Y ]] +>0: [[ aaaXbaabY = (#a1)(a##b)##Y ]] +>1: [[ read.me = (#ia1)README~READ.ME ]] +>0: [[ read.me = (#ia1)README~READ_ME ]] +>1: [[ read.me = (#ia1)README~(#a1)READ_ME ]] +>0: [[ test = *((#s)|/)test((#e)|/)* ]] +>0: [[ test/path = *((#s)|/)test((#e)|/)* ]] +>0: [[ path/test = *((#s)|/)test((#e)|/)* ]] +>0: [[ path/test/ohyes = *((#s)|/)test((#e)|/)* ]] +>1: [[ atest = *((#s)|/)test((#e)|/)* ]] +>1: [[ testy = *((#s)|/)test((#e)|/)* ]] +>1: [[ testy/path = *((#s)|/)test((#e)|/)* ]] +>1: [[ path/atest = *((#s)|/)test((#e)|/)* ]] +>1: [[ atest/path = *((#s)|/)test((#e)|/)* ]] +>1: [[ path/testy = *((#s)|/)test((#e)|/)* ]] +>1: [[ path/testy/ohyes = *((#s)|/)test((#e)|/)* ]] +>1: [[ path/atest/ohyes = *((#s)|/)test((#e)|/)* ]] +>0: [[ XabcdabcY = X(ab|c|d)(#c5)Y ]] +>0: [[ XabcdabcY = X(ab|c|d)(#c1,5)Y ]] +>0: [[ XabcdabcY = X(ab|c|d)(#c5,8)Y ]] +>0: [[ XabcdabcY = X(ab|c|d)(#c4,)Y ]] +>1: [[ XabcdabcY = X(ab|c|d)(#c6,)Y ]] +>1: [[ XabcdabcY = X(ab|c|d)(#c1,4)Y ]] +>0: [[ ZX = Z(|)(#c1)X ]] +>0: [[ froofroo = (fro(#c2))(#c2) ]] +>1: [[ froofroofroo = (fro(#c2))(#c2) ]] +>1: [[ froofro = (fro(#c2))(#c2) ]] +>0: [[ ax = ?(#c1,2)x ]] +>0: [[ ax = ?(#c1,)x ]] +>0: [[ ax = ?(#c0,1)x ]] +>1: [[ ax = ?(#c0,0)x ]] +>1: [[ ax = ?(#c2,)x ]] +>0: [[ aa = a(#c1,2)a ]] +>0: [[ aa = a(#c1,)a ]] +>0: [[ aa = a(#c0,1)a ]] +>1: [[ aa = a(#c0,0)a ]] +>1: [[ aa = a(#c2,)a ]] +>0: [[ test.zsh = *.?(#c1)sh ]] +>0: [[ test.bash = *.?(#c2)sh ]] +>0: [[ test.bash = *.?(#c1,2)sh ]] +>0: [[ test.bash = *.?(#c1,)sh ]] +>0: [[ test.zsh = *.?(#c1,)sh ]] +>0 tests failed. + + globtest globtests.ksh +0:ksh compatibility +>0: [[ fofo = *(f*(o)) ]] +>0: [[ ffo = *(f*(o)) ]] +>0: [[ foooofo = *(f*(o)) ]] +>0: [[ foooofof = *(f*(o)) ]] +>0: [[ fooofoofofooo = *(f*(o)) ]] +>1: [[ foooofof = *(f+(o)) ]] +>1: [[ xfoooofof = *(f*(o)) ]] +>1: [[ foooofofx = *(f*(o)) ]] +>0: [[ ofxoofxo = *(*(of*(o)x)o) ]] +>1: [[ ofooofoofofooo = *(f*(o)) ]] +>0: [[ foooxfooxfoxfooox = *(f*(o)x) ]] +>1: [[ foooxfooxofoxfooox = *(f*(o)x) ]] +>0: [[ foooxfooxfxfooox = *(f*(o)x) ]] +>0: [[ ofxoofxo = *(*(of*(o)x)o) ]] +>0: [[ ofoooxoofxo = *(*(of*(o)x)o) ]] +>0: [[ ofoooxoofxoofoooxoofxo = *(*(of*(o)x)o) ]] +>0: [[ ofoooxoofxoofoooxoofxoo = *(*(of*(o)x)o) ]] +>1: [[ ofoooxoofxoofoooxoofxofo = *(*(of*(o)x)o) ]] +>0: [[ ofoooxoofxoofoooxoofxooofxofxo = *(*(of*(o)x)o) ]] +>0: [[ aac = *(@(a))a@(c) ]] +>0: [[ ac = *(@(a))a@(c) ]] +>1: [[ c = *(@(a))a@(c) ]] +>0: [[ aaac = *(@(a))a@(c) ]] +>1: [[ baaac = *(@(a))a@(c) ]] +>0: [[ abcd = ?@(a|b)*@(c)d ]] +>0: [[ abcd = @(ab|a*@(b))*(c)d ]] +>0: [[ acd = @(ab|a*(b))*(c)d ]] +>0: [[ abbcd = @(ab|a*(b))*(c)d ]] +>0: [[ effgz = @(b+(c)d|e*(f)g?|?(h)i@(j|k)) ]] +>0: [[ efgz = @(b+(c)d|e*(f)g?|?(h)i@(j|k)) ]] +>0: [[ egz = @(b+(c)d|e*(f)g?|?(h)i@(j|k)) ]] +>0: [[ egzefffgzbcdij = *(b+(c)d|e*(f)g?|?(h)i@(j|k)) ]] +>1: [[ egz = @(b+(c)d|e+(f)g?|?(h)i@(j|k)) ]] +>0: [[ ofoofo = *(of+(o)) ]] +>0: [[ oxfoxoxfox = *(oxf+(ox)) ]] +>1: [[ oxfoxfox = *(oxf+(ox)) ]] +>0: [[ ofoofo = *(of+(o)|f) ]] +>0: [[ foofoofo = @(foo|f|fo)*(f|of+(o)) ]] +>0: [[ oofooofo = *(of|oof+(o)) ]] +>0: [[ fffooofoooooffoofffooofff = *(*(f)*(o)) ]] +>1: [[ fffooofoooooffoofffooofffx = *(*(f)*(o)) ]] +>0: [[ fofoofoofofoo = *(fo|foo) ]] +>0: [[ foo = !(x) ]] +>0: [[ foo = !(x)* ]] +>1: [[ foo = !(foo) ]] +>0: [[ foo = !(foo)* ]] +>0: [[ foobar = !(foo) ]] +>0: [[ foobar = !(foo)* ]] +>0: [[ moo.cow = !(*.*).!(*.*) ]] +>1: [[ mad.moo.cow = !(*.*).!(*.*) ]] +>1: [[ mucca.pazza = mu!(*(c))?.pa!(*(z))? ]] +>1: [[ _foo~ = _?(*[^~]) ]] +>0: [[ fff = !(f) ]] +>0: [[ fff = *(!(f)) ]] +>0: [[ fff = +(!(f)) ]] +>0: [[ ooo = !(f) ]] +>0: [[ ooo = *(!(f)) ]] +>0: [[ ooo = +(!(f)) ]] +>0: [[ foo = !(f) ]] +>0: [[ foo = *(!(f)) ]] +>0: [[ foo = +(!(f)) ]] +>1: [[ f = !(f) ]] +>1: [[ f = *(!(f)) ]] +>1: [[ f = +(!(f)) ]] +>0: [[ foot = @(!(z*)|*x) ]] +>1: [[ zoot = @(!(z*)|*x) ]] +>0: [[ foox = @(!(z*)|*x) ]] +>0: [[ zoox = @(!(z*)|*x) ]] +>0: [[ foo = *(!(foo)) ]] +>1: [[ foob = !(foo)b* ]] +>0: [[ foobb = !(foo)b* ]] +>0: [[ fooxx = (#i)FOOXX ]] +>1: [[ fooxx = (#l)FOOXX ]] +>0: [[ FOOXX = (#l)fooxx ]] +>1: [[ fooxx = (#i)FOO@(#I)X@(#i)X ]] +>0: [[ fooXx = (#i)FOO@(#I)X@(#i)X ]] +>0: [[ fooxx = @((#i)FOOX)x ]] +>1: [[ fooxx = @((#i)FOOX)X ]] +>1: [[ BAR = @(bar|(#i)foo) ]] +>0: [[ FOO = @(bar|(#i)foo) ]] +>0: [[ Modules = (#i)*m* ]] +>0 tests failed. + + (unsetopt multibyte + [[ bjrn = *[]* ]]) +0:single byte match with top bit set + + ( regress_absolute_path_and_core_dump ) +0:exclusions regression test +> +>glob.tmp/a glob.tmp/b glob.tmp/c glob.tmp/dir1 glob.tmp/dir1/a glob.tmp/dir1/b glob.tmp/dir1/c glob.tmp/dir2 glob.tmp/dir2/a glob.tmp/dir2/b glob.tmp/dir2/c glob.tmp/dir3 glob.tmp/dir3/subdir glob.tmp/dir4 + + print glob.tmp/*(/) +0:Just directories +>glob.tmp/dir1 glob.tmp/dir2 glob.tmp/dir3 glob.tmp/dir4 + + print glob.tmp/*(.) +0:Just files +>glob.tmp/a glob.tmp/b glob.tmp/c + + print glob.tmp/*(.e^'reply=( glob.tmp/*/${REPLY:t} )'^:t) +0:Globbing used recursively (inside e glob qualifier) +>a a b b c c + + print glob.tmp/*/*(e:'reply=( glob.tmp/**/*([1]) )'::t) +0:Recursive globbing used recursively (inside e glob qualifier) +>a a a a a a a + + print glob.tmp/**/(:h) +0:Head modifier +>. glob.tmp glob.tmp glob.tmp glob.tmp glob.tmp/dir3 + + print glob.tmp(:r) +0:Remove extension modifier +>glob + + print glob.tmp/*(:s/./_/) +0:Substitute modifier +>glob_tmp/a glob_tmp/b glob_tmp/c glob_tmp/dir1 glob_tmp/dir2 glob_tmp/dir3 glob_tmp/dir4 + + print glob.tmp/*(F) +0:Just full dirs +>glob.tmp/dir1 glob.tmp/dir2 glob.tmp/dir3 + + print glob.tmp/*(^F) +0:Omit full dirs +>glob.tmp/a glob.tmp/b glob.tmp/c glob.tmp/dir4 + + print glob.tmp/*(/^F) +0:Just empty dirs +>glob.tmp/dir4 + + setopt extendedglob + print glob.tmp/**/*~*/dir3(/*|(#e))(/) +0:Exclusions with complicated path specifications +>glob.tmp/dir1 glob.tmp/dir2 glob.tmp/dir4 + + print -l -- glob.tmp/*(P:-f:) +0:Prepending words to each argument +>-f +>glob.tmp/a +>-f +>glob.tmp/b +>-f +>glob.tmp/c +>-f +>glob.tmp/dir1 +>-f +>glob.tmp/dir2 +>-f +>glob.tmp/dir3 +>-f +>glob.tmp/dir4 + + print -l -- glob.tmp/*(P:one word:P:another word:) +0:Prepending two words to each argument +>one word +>another word +>glob.tmp/a +>one word +>another word +>glob.tmp/b +>one word +>another word +>glob.tmp/c +>one word +>another word +>glob.tmp/dir1 +>one word +>another word +>glob.tmp/dir2 +>one word +>another word +>glob.tmp/dir3 +>one word +>another word +>glob.tmp/dir4 + + [[ "" = "" ]] && echo OK +0:Empty strings +>OK + + foo="this string has a : colon in it" + print ${foo%% #:*} +0:Must-match arguments in complex patterns +>this string has a + + mkdir glob.tmp/ra=1.0_et=3.5 + touch glob.tmp/ra=1.0_et=3.5/foo + print glob.tmp/ra=1.0_et=3.5/??? +0:Bug with intermediate paths with plain strings but tokenized characters +>glob.tmp/ra=1.0_et=3.5/foo + + doesmatch() { + setopt localoptions extendedglob + print -n $1 $2\ + if [[ $1 = $~2 ]]; then print yes; else print no; fi; + } + doesmatch MY_IDENTIFIER '[[:IDENT:]]##' + doesmatch YOUR:IDENTIFIER '[[:IDENT:]]##' + IFS=$'\n' doesmatch $'\n' '[[:IFS:]]' + IFS=' ' doesmatch $'\n' '[[:IFS:]]' + IFS=':' doesmatch : '[[:IFSSPACE:]]' + IFS=' ' doesmatch ' ' '[[:IFSSPACE:]]' + WORDCHARS="" doesmatch / '[[:WORD:]]' + WORDCHARS="/" doesmatch / '[[:WORD:]]' +0:Named character sets handled internally +>MY_IDENTIFIER [[:IDENT:]]## yes +>YOUR:IDENTIFIER [[:IDENT:]]## no +> +> [[:IFS:]] yes +> +> [[:IFS:]] no +>: [[:IFSSPACE:]] no +> [[:IFSSPACE:]] yes +>/ [[:WORD:]] no +>/ [[:WORD:]] yes + + [[ foo = (#c0)foo ]] +2:Misplaced (#c...) flag +?(eval):1: bad pattern: (#c0)foo + + mkdir glob.tmp/dir5 + touch glob.tmp/dir5/N123 + print glob.tmp/dir5/N<->(N) + rm -rf glob.tmp/dir5 +0:Numeric glob is not usurped by process substitution. +>glob.tmp/dir5/N123 + + tpd() { + [[ $1 = $~2 ]] + print -r "$1, $2: $?" + } + test_pattern_disables() { + emulate -L zsh + tpd 'forthcoming' 'f*g' + disable -p '*' + tpd 'forthcoming' 'f*g' + tpd 'f*g' 'f*g' + tpd '[frog]' '[frog]' + tpd '[frog]' '\[[f]rog\]' + disable -p '[' + tpd '[frog]' '[frog]' + tpd '[frog]' '\[[f]rog\]' + setopt extendedglob + tpd 'foo' '^bar' + disable -p '^' + tpd 'foo' '^bar' + tpd '^bar' '^bar' + tpd 'rumble' '(rumble|bluster)' + tpd '(thunder)' '(thunder)' + disable -p '(' + tpd 'rumble' '(rumble|bluster)' + tpd '(thunder)' '(thunder)' + setopt kshglob + tpd 'scramble' '@(panic|frenzy|scramble)' + tpd '@(scrimf)' '@(scrimf)' + disable -p '@(' + tpd 'scramble' '@(panic|frenzy|scramble)' + tpd '@(scrimf)' '@(scrimf)' + disable -p + } + test_pattern_disables + print Nothing should be disabled. + disable -p +0:disable -p +>forthcoming, f*g: 0 +>forthcoming, f*g: 1 +>f*g, f*g: 0 +>[frog], [frog]: 1 +>[frog], \[[f]rog\]: 0 +>[frog], [frog]: 0 +>[frog], \[[f]rog\]: 1 +>foo, ^bar: 0 +>foo, ^bar: 1 +>^bar, ^bar: 0 +>rumble, (rumble|bluster): 0 +>(thunder), (thunder): 1 +>rumble, (rumble|bluster): 1 +>(thunder), (thunder): 0 +>scramble, @(panic|frenzy|scramble): 0 +>@(scrimf), @(scrimf): 1 +>scramble, @(panic|frenzy|scramble): 1 +>@(scrimf), @(scrimf): 0 +>'(' '*' '[' '^' '@(' +>Nothing should be disabled. + + ( + setopt nomatch + x=( '' ) + print $^x(N) + ) +0:No error with empty null glob with (N). +> + + (setopt kshglob + test_array=( + '+fours' '+*' + '@titude' '@*' + '!bang' '!*' + # and check they work in the real kshglob cases too... + '+bus+bus' '+(+bus|-car)' + '@sinhats' '@(@sinhats|wrensinfens)' + '!kerror' '!(!somethingelse)' + # and these don't match, to be sure + '+more' '+(+less)' + '@all@all' '@(@all)' + '!goesitall' '!(!goesitall)' + ) + for str pat in $test_array; do + eval "[[ $str = $pat ]]" && print "$str matches $pat" + done + true + ) +0:kshglob option does not break +, @, ! without following open parenthesis +>+fours matches +* +>@titude matches @* +>!bang matches !* +>+bus+bus matches +(+bus|-car) +>@sinhats matches @(@sinhats|wrensinfens) +>!kerror matches !(!somethingelse) + + ( + setopt extendedglob + cd glob.tmp + [[ -n a*(#qN) ]] && print File beginning with a + [[ -z z*(#qN) ]] && print No file beginning with z + setopt nonomatch + [[ -n z*(#q) ]] && print Normal string if nullglob not set + ) +0:Force glob expansion in conditions using (#q) +>File beginning with a +>No file beginning with z +>Normal string if nullglob not set + + (){ print $#@ } glob.tmp/dir*(Y1) + (){ print $#@ } glob.tmp/file*(NY1) + (){ [[ "$*" == */dir?\ */dir? ]] && print Returns matching filenames } glob.tmp/dir*(Y2) + (){ print "Limit is upper bound:" ${(o)@:t} } glob.tmp/dir*(Y5) + (){ print "Negated:" $@:t } glob.tmp/dir*(Y1^Y) + (){ print "Sorting:" $@:t } glob.tmp/dir*(Y4On) + (){ [[ $#@ -eq 1 ]] && print Globs before last path component } glob.tmp/dir?/subdir(NY1) + (){ [[ $1 == glob.tmp/a ]] } glob.tmp/**/a(Y1) && print Breadth first + (){ [[ $#@ -eq 0 ]] && print Respects qualifiers } glob.tmp/dir*(NY1.) + (print -- *(Y)) 2>/dev/null || print "Argument required" +0:short-circuit modifier +>1 +>0 +>Returns matching filenames +>Limit is upper bound: dir1 dir2 dir3 dir4 +>Negated: dir1 dir2 dir3 dir4 +>Sorting: dir4 dir3 dir2 dir1 +>Globs before last path component +>Breadth first +>Respects qualifiers +>Argument required + + [[ "ce fichier n'existe pas" = (#b)ce\ (f[^ ]#)\ *s(#q./) ]] + print $match[1] +0:(#q) is ignored completely in conditional pattern matching +>fichier + +# The following should not cause excessive slowdown. + print glob.tmp/*.* + print glob.tmp/**************************.************************* +0:Optimisation to squeeze multiple *'s used as ordinary glob wildcards. +>glob.tmp/ra=1.0_et=3.5 +>glob.tmp/ra=1.0_et=3.5 + + [[ 1_2_ = (*_)(#c1) ]] && print 1 OK # because * matches 1_2 + [[ 1_2_ = (*_)(#c2) ]] && print 2 OK + [[ 1_2_ = (*_)(#c3) ]] || print 3 OK +0:Some more complicated backtracking with match counts. +>1 OK +>2 OK +>3 OK + + [[ foo = 'f'\o"o" ]] +0:Stripping of quotes from patterns (1) + + [[ foo = 'f'('o'|'a')('o'|'b') ]] +0:Stripping of quotes from patterns (2) + + [[ fob = 'f'('o'|'a')('o'|'b') ]] +0:Stripping of quotes from patterns (3) + + [[ fab = 'f'('o'|'a')('o'|'b') ]] +0:Stripping of quotes from patterns (4) + + [[ fib != 'f'('o'|'a')('o'|'b') ]] +0:Stripping of quotes from patterns (4) + + [[ - != [a-z] ]] +0:- is a special character in ranges + + [[ - = ['a-z'] ]] +0:- is not a special character in ranges if quoted + + [[ b-1 = [a-z]-[0-9] ]] +0:- untokenized following a bracketed subexpression + + [[ b-1 = []a-z]-[]0-9] ]] +0:- "]" after "[" is normal range character and - still works + + headremove="bcdef" + print ${headremove#[a-z]} +0:active - works in pattern in parameter +>cdef + + headremove="bcdef" + print ${headremove#['a-z']} + headremove="-cdef" + print ${headremove#['a-z']} +0:quoted - works in pattern in parameter +>bcdef +>cdef + + [[ a != [^a] ]] +0:^ active in character class if not quoted + + [[ a = ['^a'] ]] +0:^ not active in character class if quoted + + [[ a != [!a] ]] +0:! active in character class if not quoted + + [[ a = ['!a'] ]] +0:! not active in character class if quoted + + # Actually, we don't need the quoting here, + # c.f. the next test. This just makes it look + # more standard. + cset="^a-z" + [[ "^" = ["$cset"] ]] || print Fail 1 + [[ "a" = ["$cset"] ]] || print Fail 2 + [[ "-" = ["$cset"] ]] || print Fail 3 + [[ "z" = ["$cset"] ]] || print Fail 4 + [[ "1" != ["$cset"] ]] || print Fail 5 + [[ "b" != ["$cset"] ]] || print Fail 6 +0:character set specified as quoted variable + + cset="^a-z" + [[ "^" = [$~cset] ]] || print Fail 1 + [[ "a" != [$~cset] ]] || print Fail 2 + [[ "-" = [$~cset] ]] || print Fail 3 + [[ "z" != [$~cset] ]] || print Fail 4 + [[ "1" = [$~cset] ]] || print Fail 5 + [[ "b" != [$~cset] ]] || print Fail 6 +0:character set specified as active variable + + () { print -l -- $@:a } / /..{,/} /1 /nonexistent/..{,/} /deeper/nonexistent/..{,/} +0:modifier ':a' doesn't require existence +>/ +>/ +>/ +>/1 +>/ +>/ +>/deeper +>/deeper + + () { set -- ${PWD}/$^@; print -l -- $@:A } glob.tmp/nonexistent/foo/bar/baz +0:modifier ':A' doesn't require existence +*>*/glob.tmp/nonexistent/foo/bar/baz + + ln -s dir3/subdir glob.tmp/link + () { + print ${1:A} | grep glob.tmp + } glob.tmp/link/../../hello + rm glob.tmp/link +0:modifier ':A' resolves '..' components before symlinks +# There should be no output + + ln -s dir3/subdir glob.tmp/link + () { + print ${1:P} + } glob.tmp/link/../../hello/world + rm glob.tmp/link +0:modifier ':P' resolves symlinks before '..' components +*>*glob.tmp/hello/world diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D03procsubst.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D03procsubst.ztst new file mode 100644 index 00000000..ca8d56ff --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D03procsubst.ztst @@ -0,0 +1,151 @@ +# Tests for process substitution: <(...), >(...) and =(...). + +%prep + if grep '#define PATH_DEV_FD' $ZTST_testdir/../config.h > /dev/null 2>&1 || + grep '#define HAVE_FIFOS' $ZTST_testdir/../config.h > /dev/null 2>&1; then + mkdir procsubst.tmp + cd procsubst.tmp + print 'First\tSecond\tThird\tFourth' >FILE1 + print 'Erste\tZweite\tDritte\tVierte' >FILE2 + else + ZTST_unimplemented="process substitution is not supported" + true + fi + + function copycat { cat "$@" } + +%test + paste <(cut -f1 FILE1) <(cut -f3 FILE2) +0:<(...) substitution +>First Dritte + +# slightly desperate hack to force >(...) to be synchronous + { paste <(cut -f2 FILE1) <(cut -f4 FILE2) } > >(sed 's/e/E/g' >OUTFILE) + cat OUTFILE +0:>(...) substitution +>SEcond ViErtE + + diff =(cat FILE1) =(cat FILE2) +1:=(...) substituion +>1c1 +>< First Second Third Fourth +>--- +>> Erste Zweite Dritte Vierte + + copycat <(print First) <(print Zweite) +0:FDs remain open for external commands called from functions +>First +>Zweite + + catfield2() { + local -a args + args=(${(s.,.)1}) + print $args[1] + cat $args[2] + print $args[3] + } + catfield2 up,<(print $'\x64'own),sideways +0:<(...) when embedded within an argument +>up +>down +>sideways + + outputfield2() { + local -a args + args=(${(s.,.)1}) + print $args[1] + echo 'How sweet the moonlight sits upon the bank' >$args[2] + print $args[3] + } + outputfield2 muddy,>(sed -e s/s/th/g >outputfield2.txt),vesture + # yuk + while [[ ! -e outputfield2.txt || ! -s outputfield2.txt ]]; do :; done + cat outputfield2.txt +0:>(...) when embedded within an argument +>muddy +>vesture +>How thweet the moonlight thitth upon the bank + + catfield1() { + local -a args + args=(${(s.,.)1}) + cat $args[1] + print $args[2] + } + catfield1 =(echo s$'\x69't),jessica +0:=(...) followed by something else without a break +>sit +>jessica + + ( + setopt nonomatch + # er... why is this treated as a glob? + print everything,=(here is left),alone + ) +0:=(...) preceded by other stuff has no special effect +>everything,=(here is left),alone + + print something=${:-=(echo 'C,D),(F,G)'} +1: Graceful handling of bad substitution in enclosed context +?(eval):1: unterminated `=(...)' +# '` + + () { + print -n "first: " + cat $1 + print -n "second: " + cat $2 + } =(echo This becomes argument one) =(echo and this argument two) + function { + print -n "third: " + cat $1 + print -n "fourth: " + cat $2 + } =(echo This becomes argument three) =(echo and this argument four) +0:Process environment of anonymous functions +>first: This becomes argument one +>second: and this argument two +>third: This becomes argument three +>fourth: and this argument four + + () { + # Make sure we don't close the file descriptor too early + eval 'print "Execute a complicated command first" | sed s/command/order/' + cat $1 + } <(echo This line was brought to you by the letters F and D) +0:Process substitution as anonymous function argument +>Execute a complicated order first +>This line was brought to you by the letters F and D + + alias foo='cat <(' + eval 'foo echo this is bound to work)' +0:backtacking within command string parsing with alias still pending +>this is bound to work + + alias foo='cat <( print' + eval 'foo here is some output)' +0:full alias expanded when substitution starts in alias +>here is some output + + if ! (mkfifo test_pipe >/dev/null 2>&1); then + ZTST_skip="mkfifo not available" + else + echo 1 | tee >(cat > test_pipe) | (){ + local pipein + read pipein 1 +>1 + + if [[ ! -e test_pipe ]]; then + ZTST_skip="mkfifo not available" + else + echo 1 | tee >(cat > test_pipe) | paste - test_pipe + fi +0:proc subst fd in forked subshell closed in parent (external command) +>1 1 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D04parameter.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D04parameter.ztst new file mode 100644 index 00000000..9128c3c3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D04parameter.ztst @@ -0,0 +1,2058 @@ +# Test parameter expansion. Phew. +# (By the way, did I say "phew"?) + +%prep + + mkdir parameter.tmp + + cd parameter.tmp + + touch boringfile evenmoreboringfile + +%test + + foo='the first parameter' + bar='the second parameter' + print -l $foo ${bar} +0:Basic scalar parameter substitution +>the first parameter +>the second parameter + + array1=(the first array) + array2=(the second array) + print -l $array1 ${array2} +0:Basic array parameter substitution +>the +>first +>array +>the +>second +>array + + setopt ksharrays + print -l $array1 ${array2} + unsetopt ksharrays +0:Basic ksharray substitution +>the +>the + + setopt shwordsplit + print -l $foo ${bar} + print -l ${==bar} + unsetopt shwordsplit +0:Basic shwordsplit option handling +>the +>first +>parameter +>the +>second +>parameter +>the second parameter + + print $+foo ${+foo} $+notappearinginthistest ${+notappearinginthistest} +0:$+... +>1 1 0 0 + + x=() + print ${+x} ${+x[1]} ${+x[(r)foo]} ${+x[(r)bar]} + x=(foo) + print ${+x} ${+x[1]} ${+x[(r)foo]} ${+x[(r)bar]} +0:$+... with arrays +>1 0 0 0 +>1 1 1 0 + + set1=set1v + null1= + print ${set1:-set1d} ${set1-set2d} ${null1:-null1d} ${null1-null2d} x + print ${unset1:-unset1d} ${unset1-unset2d} x +0:${...:-...} and ${...-...} +>set1v set1v null1d x +>unset1d unset2d x + + set2=irrelevant + print ${set1:=set1d} ${set2::=set2d} + print $set2 + wasnull1= + wasnull2= + print ${wasnull1=wasnull1d} ${wasnull2:=wasnull2d} + print $wasnull1 $wasnull2 +0:${...:=...}, ${...::=...}, ${...=...} +>set1v set2d +>set2d +>wasnull2d +>wasnull2d + + unset array + print ${#${(A)=array=word}} +0:${#${(A)=array=word}} counts array elements +>1 + + (print ${set1:?okhere}; print ${unset1:?exiting1}; print not reached;) + (print ${null1?okhere}; print ${null1:?exiting2}; print not reached;) +1:${...:?...}, ${...?...} +>set1v +> +?(eval):1: unset1: exiting1 +?(eval):2: null1: exiting2 + + PROMPT="" $ZTST_testdir/../Src/zsh -fis <<<' + unsetopt PROMPT_SP + PS1="" PS2="" PS3="" PS4="" RPS1="" RPS2="" + exec 2>&1 + foo() { + print ${1:?no arguments given} + print not reached + } + foo + print reached + ' 2>/dev/null +0:interactive shell returns to top level on ${...?...} error +*>*foo:1: 1: no arguments given +>reached + + print ${set1:+word1} ${set1+word2} ${null1:+word3} ${null1+word4} + print ${unset1:+word5} ${unset1+word6} +0:${...:+...}, ${...+...} +>word1 word2 word4 +> + + str1='This is very boring indeed.' + print ${str1#*s} + print ${str1##*s} + print $str1##s +0:${...#...}, ${...##...} +> is very boring indeed. +> very boring indeed. +>This is very boring indeed.##s + + str2='If you'\''re reading this you should go and fix some bugs instead.' + print ${str2%d*} + print ${str2%%d*} +0:${...%...}, ${...%%...} +>If you're reading this you should go and fix some bugs instea +>If you're rea + + str1='does match' + str2='does not match' + print ${str1:#does * match} + print ${str2:#does * match} +0:${...:#...} +>does match +> + + array1=(arthur boldly claws dogs every fight) + print ${array1:#[aeiou]*} + print ${(M)array1:#[aeiou]*} +0:${...:#...}, ${(M)...:#...} with array +>boldly claws dogs fight +>arthur every + + str1="$array1" + print ${str1/[aeiou]*g/a braw bricht moonlicht nicht the nic} + print ${(S)str1/[aeiou]*g/relishe} +0:scalar ${.../.../...}, ${(S).../.../...} +>a braw bricht moonlicht nicht the nicht +>relishes every fight + + print ${array1/[aeiou]*/Y} + print ${(S)array1/[aeiou]*/Y} +0:array ${.../.../...}, ${(S).../.../...} +>Y bY clY dY Y fY +>Yrthur bYldly clYws dYgs Yvery fYght + + str1='o this is so, so so very dull' + print ${str1//o*/Please no} + print ${(S)str1//o*/Please no} +0:scalar ${...//.../...}, ${(S)...//.../...} +>Please no +>Please no this is sPlease no, sPlease no sPlease no very dull + + print ${array1//[aeiou]*/Y} + print ${(S)array1//[aeiou]*/Y} +0:array ${...//.../...}, ${(S)...//.../...} +>Y bY clY dY Y fY +>YrthYr bYldly clYws dYgs YvYry fYght + + print ${array1:/[aeiou]*/expletive deleted} +0:array ${...:/...} +>expletive deleted boldly claws dogs expletive deleted fight + + str1='a\string\with\backslashes' + str2='a/string/with/slashes' + print "${str1//\\/-}" + print ${str1//\\/-} + print "${str2//\//-}" + print ${str2//\//-} +0:use of backslashes in //-substitutions +>a-string-with-backslashes +>a-string-with-backslashes +>a-string-with-slashes +>a-string-with-slashes + + args=('one' '#foo' '(bar' "'three'" two) + mod=('#foo' '(bar' "'three'" sir_not_appearing_in_this_film) + print ${args:|mod} + print ${args:*mod} + print "${(@)args:|mod}" + print "${(@)args:*mod}" + args=(two words) + mod=('one word' 'two words') + print "${args:|mod}" + print "${args:*mod}" + scalar='two words' + print ${scalar:|mod} + print ${scalar:*mod} + print ${args:*nonexistent} + empty= + print ${args:*empty} +0:"|" array exclusion and "*" array intersection +>one two +>#foo (bar 'three' +>one two +>#foo (bar 'three' +> +>two words +> +>two words +> +> + + str1='twocubed' + array=(the number of protons in an oxygen nucleus) + print $#str1 ${#str1} "$#str1 ${#str1}" $#array ${#array} "$#array ${#array}" +0:${#...}, $#... +>8 8 8 8 8 8 8 8 + + set 1 2 3 4 5 6 7 8 9 + print ${##} + set 1 2 3 4 5 6 7 8 9 10 + print ${##} + print ${##""} + print ${##1} + print ${##2} + print ${###<->} # oh, for pete's sake... +0:${##} is length of $#, and other tales of hash horror +>1 +>2 +>10 +>0 +>10 +> + + array=(once bitten twice shy) + print IF${array}THEN + print IF${^array}THEN +0:basic ${^...} +>IFonce bitten twice shyTHEN +>IFonceTHEN IFbittenTHEN IFtwiceTHEN IFshyTHEN + + # Quote ${array} here because {...,...} doesn't like unquoted spaces. + print IF{"${array}",THEN}ELSE + print IF{${^array},THEN}ELSE +0:combined ${^...} and {...,...} +>IFonce bitten twice shyELSE IFTHENELSE +>IFonceELSE IFTHENELSE IFbittenELSE IFTHENELSE IFtwiceELSE IFTHENELSE IFshyELSE IFTHENELSE + + str1='one word' + print -l $str1 ${=str1} "split ${=str1}wise" +0:${=...} +>one word +>one +>word +>split one +>wordwise + + str1='*' + print $str1 ${~str1} $~str1 + setopt globsubst + print $str1 + unsetopt globsubst +0:${~...} and globsubst +>* boringfile evenmoreboringfile boringfile evenmoreboringfile +>boringfile evenmoreboringfile + +# The following tests a bug where globsubst didn't preserve +# backslashes when printing out the original string. + str1='\\*\\' + ( + setopt globsubst nonomatch + [[ \\\\ = $str1 ]] && print -r '\\ matched by' $str1 + [[ \\foo\\ = $str1 ]] && print -r '\\foo matched by' $str1 + [[ a\\b\\ = $str1 ]] || print -r 'a\\b not matched by' $str1 + ) +0:globsubst with backslashes +>\\ matched by \\*\\ +>\\foo matched by \\*\\ +>a\\b not matched by \\*\\ + + ( + setopt globsubst + foo="boring*" + print ${foo+$foo} + print ${foo+"$foo"} + print ${~foo+"$foo"} + ) +0:globsubst together with nested quoted expansion +>boringfile +>boring* +>boringfile + + print -l "${$(print one word)}" "${=$(print two words)}" +0:splitting of $(...) inside ${...} +>one word +>two +>words + + (setopt shwordsplit # ensure this doesn't get set in main shell... + test_splitting () + { + array="one two three" + for e in $array; do + echo "'$e'" + done + } + test_split_var= + echo _${test_split_var:=$(test_splitting)}_ + echo "_${test_split_var}_") +0:SH_WORD_SPLIT inside $(...) inside ${...} +>_'one' 'two' 'three'_ +>_'one' +>'two' +>'three'_ + + print -l "${(f)$(print first line\\nsecond line\\nthird line)}" +0:${(f)$(...)} +>first line +>second line +>third line + + array1=( uno ) + print -l ${(A)newarray=splitting by numbers} + print -l ${(t)newarray} + print -l ${(A)=newarray::=splitting by spaces, actually} + print -l ${(t)newarray} + print -l ${(A)newarray::=$array1} + print -l ${(t)newarray} + print -l ${newarray::=$array1} + print -l ${(t)newarray} + print -l ${newarray::=$array2} + print -l ${(t)newarray} +0:${(A)...=...}, ${(A)...::=...}, ${scalar=$array} +>splitting by numbers +>array +>splitting +>by +>spaces, +>actually +>array +>uno +>array +>uno +>scalar +>the second array +>scalar + + newarray=("split me" "split me" "I\'m yours") + print -l "${(@)newarray}" +0:"${(@)...}" +>split me +>split me +>I'm yours + + foo='$(print Howzat usay)' + print -l ${(e)foo} +0:${(e)...} +>Howzat +>usay + + foo='`print Howzat usay`' + print -l ${(e)foo} +0:Regress ${(e)...} with backticks (see zsh-workers/15871) +>Howzat +>usay + + foo='\u65\123' + print -r ${(g:o:)foo} + foo='\u65\0123^X\C-x' + print -r ${(g::)foo} + foo='^X' + bar='\C-\130' + [[ ${(g:c:)foo} == ${(g:oe:)bar} ]] + echo $? +0:${(g)...} +>eS +>eS^X\C-x +>0 + + foo='I'\''m nearly out of my mind with tedium' + bar=foo + print ${(P)bar} +0:${(P)...} +>I'm nearly out of my mind with tedium +#' deconfuse emacs + + foo=(I could be watching that programme I recorded) + print ${(o)foo} + print ${(oi)foo} + print ${(O)foo} + print ${(Oi)foo} +0:${(o)...}, ${(O)...} +>I I be could programme recorded that watching +>be could I I programme recorded that watching +>watching that recorded programme could be I I +>watching that recorded programme I I could be + + foo=(yOU KNOW, THE ONE WITH wILLIAM dALRYMPLE) + bar=(doing that tour of India.) + print ${(L)foo} + print ${(U)bar} +0:${(L)...}, ${(U)...} +>you know, the one with william dalrymple +>DOING THAT TOUR OF INDIA. + + foo='instead here I am stuck by the computer' + print ${(C)foo} +0:${(C)...} +>Instead Here I Am Stuck By The Computer + + foo=$'\x7f\x00' + print -r -- ${(V)foo} +0:${(V)...} +>^?^@ + + foo='playing '\''stupid'\'' "games" \w\i\t\h $quoting.' + print -r ${(q)foo} + print -r ${(qq)foo} + print -r ${(qqq)foo} + print -r ${(qqqq)foo} + print -r ${(q-)foo} +0:${(q...)...} +>playing\ \'stupid\'\ \"games\"\ \\w\\i\\t\\h\ \$quoting. +>'playing '\''stupid'\'' "games" \w\i\t\h $quoting.' +>"playing 'stupid' \"games\" \\w\\i\\t\\h \$quoting." +>$'playing \'stupid\' "games" \\w\\i\\t\\h $quoting.' +>'playing '\'stupid\'' "games" \w\i\t\h $quoting.' + + print -r ${(qqqq):-""} +0:workers/36551: literal empty string in ${(qqqq)...} +>$'' + + x=( a '' '\b' 'c d' '$e' ) + print -r ${(q)x} + print -r ${(q-)x} +0:Another ${(q...)...} test +>a '' \\b c\ d \$e +>a '' '\b' 'c d' '$e' + + print -r -- ${(q-):-foo} + print -r -- ${(q-):-foo bar} + print -r -- ${(q-):-"*(.)"} + print -r -- ${(q-):-"wow 'this is cool' or is it?"} + print -r -- ${(q-):-"no-it's-not"} +0:${(q-)...} minimal single quoting +>foo +>'foo bar' +>'*(.)' +>'wow '\''this is cool'\'' or is it?' +>no-it\'s-not + + foo="'and now' \"even the pubs\" \\a\\r\\e shut." + print -r ${(Q)foo} +0:${(Q)...} +>and now even the pubs are shut. + + foo="X$'\x41'$'\x42'Y" + print -r ${(Q)foo} +0:${(Q)...} with handling of $'...' +>XABY + + # The following may look a bit random. + # For the split we are checking that anything that + # would normally be followed by a different word has + # an argument break after it and anything that wouldn't doesn't. + # For the (Q) we are simply checking that nothing disappears + # in the parsing. + foo=' {six} (seven) >eight< }nine{ |forty-two| $many$ )ten( more' + array=(${(z)foo}) + print -l ${(Q)array} +0:${(z)...} and ${(Q)...} for some hard to parse cases +>< +>five +>> +>{six} +>( +>seven +>) +>> +>eight +>< +>}nine{ +>| +>forty-two +>| +>$many$ +>) +>ten( more + + strings=( + 'foo=(1 2 3)' + '(( 3 + 1 == 8 / 2 ))' + 'for (( i = 1 ; i < 10 ; i++ ))' + '((0.25542 * 60) - 15)*60' + 'repeat 3 (x)' + 'repeat 3 (echo foo; echo bar)' + 'repeat $(( 2 + 4 )) (x)' + 'repeat $( : foo bar; echo 4) (x)' + 'repeat "1"'\''2'\''$(( 3 + 0 ))$((echo 4);)\ 5 (x)' + ) + for string in $strings; do + array=(${(z)string}) + for (( i = 1; i <= ${#array}; i++ )); do + print -r -- "${i}:${array[i]}:" + done + done +0:Some syntactical expressions that are hard to split into words with (z). +>1:foo=(: +>2:1: +>3:2: +>4:3: +>5:): +>1:(( 3 + 1 == 8 / 2 )): +>1:for: +>2:((: +# Leading whitespace is removed, because the word proper hasn't started; +# trailing whitespace is left because the word is terminated by the +# semicolon or double parentheses. Bit confusing but sort of consistent. +>3:i = 1 ;: +>4:i < 10 ;: +>5:i++ : +>6:)): +# This one needs resolving between a math expression and +# a command, which causes interesting effects internally. +>1:(: +>2:(: +>3:0.25542: +>4:*: +>5:60: +>6:): +>7:-: +>8:15: +>9:): +>10:*60: +>1:repeat: +>2:3: +>3:(: +>4:x: +>5:): +>1:repeat: +>2:3: +>3:(: +>4:echo: +>5:foo: +>6:;: +>7:echo: +>8:bar: +>9:): +>1:repeat: +>2:$(( 2 + 4 )): +>3:(: +>4:x: +>5:): +>1:repeat: +>2:$( : foo bar; echo 4): +>3:(: +>4:x: +>5:): +>1:repeat: +>2:"1"'2'$(( 3 + 0 ))$((echo 4);)\ 5: +>3:(: +>4:x: +>5:): + + + line=$'A line with # someone\'s comment\nanother line # (1 more\nanother one' + print "*** Normal ***" + print -l ${(z)line} + print "*** Kept ***" + print -l ${(Z+c+)line} + print "*** Removed ***" + print -l ${(Z+C+)line} +0:Comments with (z) +>*** Normal *** +>A +>line +>with +># +>someone's comment +>another line # (1 more +>another one +>*** Kept *** +>A +>line +>with +># someone's comment +>; +>another +>line +># (1 more +>; +>another +>one +>*** Removed *** +>A +>line +>with +>; +>another +>line +>; +>another +>one + + line='with comment # at the end' + print -l ${(Z+C+)line} +0:Test we don't get an additional newline token +>with +>comment + + line=$'echo one\necho two # with a comment\necho three' + print -l ${(Z+nc+)line} +0:Treating zplit newlines as ordinary whitespace +>echo +>one +>echo +>two +># with a comment +>echo +>three + + print -rl - ${(z):-":;(( echo 42 "} +0:${(z)} with incomplete math expressions +>: +>; +>(( echo 42 + + # From parse error on it's not possible to split. + # Just check we get the complete string. + foo='echo $(|||) bar' + print -rl ${(z)foo} +0:$($(z)} with parse error in command substitution. +>echo +>$(|||) bar + + psvar=(dog) + setopt promptsubst + foo='It shouldn'\''t $(happen) to a %1v.' + bar='But `echo what can you do\?`' + print -r ${(%)foo} + print -r ${(%%)bar} +0:${(%)...} +>It shouldn't $(happen) to a dog. +>But what can you do? + + foo='unmatched "' + print ${(QX)foo} +1:${(QX)...} +?(eval):2: unmatched " +# " deconfuse emacs + + array=(characters in an array) + print ${(c)#array} +0:${(c)#...} +>22 + + print ${(w)#array} + str='colon::bolon::solon' + print ${(ws.:.)#str} + print ${(Ws.:.)#str} +0:${(w)...}, ${(W)...} +>4 +>3 +>5 + + typeset -A assoc + assoc=(key1 val1 key2 val2) + print ${(o)assoc} + print ${(ok)assoc} + print ${(ov)assoc} + print ${(okv)assoc} +0:${(k)...}, ${(v)...} +>val1 val2 +>key1 key2 +>val1 val2 +>key1 key2 val1 val2 + + word="obfuscatory" + print !${(l.16.)word}! +${(r.16.)word}+ +0:simple padding +>! obfuscatory! +obfuscatory + + + foo=(resulting words uproariously padded) + print ${(pl.10..\x22..X.)foo} +0:${(pl...)...} +>Xresulting """"Xwords roariously """Xpadded +#" deconfuse emacs + + print ${(l.5..X.r.5..Y.)foo} + print ${(l.6..X.r.4..Y.)foo} + print ${(l.7..X.r.3..Y.)foo} + print ${(l.6..X..A.r.6..Y..B.)foo} + print ${(l.6..X..AROOGA.r.6..Y..BARSOOM.)foo} +0:simultaneous left and right padding +>Xresulting XXXwordsYY proariousl XXpaddedYY +>XXresultin XXXXwordsY uproarious XXXpaddedY +>XXXresulti XXXXXwords Xuproariou XXXXpadded +>XAresultingB XXXAwordsBYY uproariously XXApaddedBYY +>GAresultingB OOGAwordsBAR uproariously OGApaddedBAR + + foo=(why in goodness name am I doing this) + print ${(r.5..!..?.)foo} +0:${(r...)...} +>why?! in?!! goodn name? am?!! I?!!! doing this? + + array=(I\'m simply putting a brave face on) + print ${(j:--:)array} +0:${(j)...} +>I'm--simply--putting--a--brave--face--on + + print ${(F)array} +0:${(F)...} +>I'm +>simply +>putting +>a +>brave +>face +>on + + string='zometimez zis getz zplit on a z' + print -l ${(s?z?)string} +0:${(s...)...} +>ometime +> +>is get +> +>plit on a + + str=s + arr=(a) + typeset -A ass + ass=(a a) + integer i + float f + print ${(t)str} ${(t)arr} ${(t)ass} ${(t)i} ${(t)f} +0:${(t)...} +>scalar array association-local integer-local float-local + + # it's not quite clear that these are actually right unless you know + # the algorithm: search along the string for the point at which the + # first (last) match occurs, for ## (%%), then take the shortest possible + # version of that for # (%). it's as good a definition as anything. + string='where is the white windmill, whispered walter wisely' + print ${(S)string#h*e} + print ${(S)string##h*e} + print ${(S)string%h*e} + print ${(S)string%%h*e} +0:${(S)...#...} etc. +>wre is the white windmill, whispered walter wisely +>wly +>where is the white windmill, wred walter wisely +>where is the white windmill, wly + + setopt extendedglob + print ${(SI:1:)string##w[^[:space:]]# } + print ${(SI:1+1:)string##w[^[:space:]]# } + print ${(SI:1+1+1:)string##w[^[:space:]]# } + print ${(SI:1+1+1+1:)string##w[^[:space:]]# } +0:${(I:...:)...} +>is the white windmill, whispered walter wisely +>where is the windmill, whispered walter wisely +>where is the white whispered walter wisely +>where is the white windmill, walter wisely + + print ${(MSI:1:)string##w[^[:space:]]# } +0:${(M...)...} +>where + + print ${(R)string//w[a-z]# #} +0:${(R)...} +>is the , + + # This (1) doesn't work with // or / + # (2) perhaps ought to be 18, to be consistent with normal zsh + # substring indexing and with backreferences. + print ${(BES)string##white} +0:${(BE...)...} +>14 19 + + print ${(NS)string##white} +0:${(N)...} +>5 + + string='abcdefghijklmnopqrstuvwxyz' + print ${${string%[aeiou]*}/(#m)?(#e)/${(U)MATCH}} +0:Rule 1: Nested substitutions +>abcdefghijklmnopqrsT + + array=(et Swann avec cette muflerie intermittente) + string="qui reparaissait chez lui" + print ${array[4,5]} + print ${array[4,5][1]} + print ${array[4,5][1][2,3]} + print ${string[4,5]} + print ${string[4,5][1]} +0:Rule 2: Parameter subscripting +>cette muflerie +>cette +>et +> r +> + + foo=stringalongamax + print ${${(P)foo[1,6]}[1,3]} +0:Rule 3: Parameter Name Replacement +>qui + + print "${array[5,6]}" + print "${(j.:.)array[1,2]}" +0:Rule 4: Double-Quoted Joining +>muflerie intermittente +>et:Swann + + print "${${array}[5,7]}" + print "${${(@)array}[1,2]}" +0:Rule 5: Nested Subscripting +>wan +>et Swann + + print "${${(@)array}[1,2]#?}" + print "${(@)${(@)array}[1,2]#?}" +0:Rule 6: Modifiers +>t Swann +>t wann + + array=(she sells z shells by the z shore) + (IFS='+'; print ${(s.s.)array}) +0:Rule 7: Forced Joining, and 8: Forced splitting +>he+ ell +z+ hell +by+the+z+ hore + + setopt shwordsplit + string='another poxy boring string' + print -l ${${string}/o/ } + unsetopt shwordsplit +0:Rule 9: Shell Word Splitting +>an +>ther +>p +>xy +>b +>ring +>string + + setopt nonomatch + foo='b* e*' + print ${(e)~foo} + print ${(e)~=foo} + setopt nomatch +0:Rule 10: Re-Evaluation +>b* e* +>boringfile evenmoreboringfile + + # ${bar} -> $bar here would yield "bad substitution". + bar=confinement + print ${(el.20..X.)${bar}} +0:Rule 11: Padding +>XXXXXXXXXconfinement + + foo=(bar baz) + bar=(ax1 bx1) + print "${(@)${foo}[1]}" + print "${${(@)foo}[1]}" + print -l ${(s/x/)bar} + print -l ${(j/x/s/x/)bar} + print -l ${(s/x/)bar%%1*} +0:Examples in manual on parameter expansion +>b +>bar +>a +>1 b +>1 +>a +>1 +>b +>1 +>a +> b + + set If "this test fails" "we have broken" the shell again + print -l ${1+"$@"} +0:Regression test of ${1+"$@"} bug +>If +>this test fails +>we have broken +>the +>shell +>again + + set If "this test fails" "we have broken" the shell again + print -l "${(A)foo::=$@}" + print -l ${(t)foo} + print -l $foo +0:Regression test of "${(A)foo=$@}" bug +>If this test fails we have broken the shell again +>array +>If +>this test fails +>we have broken +>the +>shell +>again + + local sure_that='sure that' varieties_of='varieties of' one=1 two=2 + extra=(5 4 3) + unset foo + set Make $sure_that "this test keeps" on 'preserving all' "$varieties_of" quoted whitespace + print -l ${=1+"$@"} + print -l ${(A)=foo=Make $sure_that "this test keeps" on 'preserving all' "$varieties_of" quoted whitespace} + print ${(t)foo} + print -l ${=1+$one $two} + print -l ${1+$extra$two$one} +0:Regression test of ${=1+"$@"} bug and some related expansions +>Make +>sure that +>this test keeps +>on +>preserving all +>varieties of +>quoted +>whitespace +>Make +>sure +>that +>this test keeps +>on +>preserving all +>varieties of +>quoted +>whitespace +>array +>1 +>2 +>5 +>4 +>321 + + splitfn() { + emulate -L sh + local HOME="/differs from/bash" foo='1 2' bar='3 4' + print -l ${1:-~} + touch has\ space + print -l ${1:-*[ ]*} + print -l ${1:-*[\ ]*} + print -l ${1:-*} + print -l ${1:-"$foo" $bar} + print -l ${==1:-$foo $bar} + rm has\ space + } + splitfn +0:More bourne-shell-compatible nested word-splitting with wildcards and ~ +>/differs from/bash +>*[ +>]* +>has space +>boringfile +>evenmoreboringfile +>has space +>1 2 +>3 +>4 +>1 2 3 4 + + splitfn() { + local IFS=.- + local foo=1-2.3-4 + # + print "Called with argument '$1'" + print "No quotes" + print -l ${=1:-1-2.3-4} ${=1:-$foo} + print "With quotes on default argument only" + print -l ${=1:-"1-2.3-4"} ${=1:-"$foo"} + } + print 'Using "="' + splitfn + splitfn 5.6-7.8 + # + splitfn() { + emulate -L zsh + setopt shwordsplit + local IFS=.- + local foo=1-2.3-4 + # + print "Called with argument '$1'" + print "No quotes" + print -l ${1:-1-2.3-4} ${1:-$foo} + print "With quotes on default argument only" + print -l ${1:-"1-2.3-4"} ${1:-"$foo"} + } + print Using shwordsplit + splitfn + splitfn 5.6-7.8 +0:Test of nested word splitting with and without quotes +>Using "=" +>Called with argument '' +>No quotes +>1 +>2 +>3 +>4 +>1 +>2 +>3 +>4 +>With quotes on default argument only +>1-2.3-4 +>1-2.3-4 +>Called with argument '5.6-7.8' +>No quotes +>5 +>6 +>7 +>8 +>5 +>6 +>7 +>8 +>With quotes on default argument only +>5 +>6 +>7 +>8 +>5 +>6 +>7 +>8 +>Using shwordsplit +>Called with argument '' +>No quotes +>1 +>2 +>3 +>4 +>1 +>2 +>3 +>4 +>With quotes on default argument only +>1-2.3-4 +>1-2.3-4 +>Called with argument '5.6-7.8' +>No quotes +>5 +>6 +>7 +>8 +>5 +>6 +>7 +>8 +>With quotes on default argument only +>5 +>6 +>7 +>8 +>5 +>6 +>7 +>8 + +# Tests a long-standing bug with joining on metafied characters in IFS + (array=(one two three) + IFS=$'\0' + foo="$array" + for (( i = 1; i <= ${#foo}; i++ )); do + char=${foo[i]} + print $(( #char )) + done) +0:Joining with NULL character from IFS +>111 +>110 +>101 +>0 +>116 +>119 +>111 +>0 +>116 +>104 +>114 +>101 +>101 + + unset SHLVL + (( SHLVL++ )) + print $SHLVL +0:Unsetting and recreation of numerical special parameters +>1 + + unset manpath + print $+MANPATH + manpath=(/here /there) + print $MANPATH + unset MANPATH + print $+manpath + MANPATH=/elsewhere:/somewhere + print $manpath +0:Unsetting and recreation of tied special parameters +>0 +>/here:/there +>0 +>/elsewhere /somewhere + + local STRING=a:b + typeset -T STRING string + print $STRING $string + unset STRING + set -A string x y z + print $STRING $string + STRING=a:b + typeset -T STRING string + print $STRING $string + unset STRING + set -A string x y z + print $STRING $string + STRING=a:b + typeset -T STRING string + print $STRING $string + unset string + STRING=x:y:z + print $STRING $string + STRING=a:b + typeset -T STRING string + print $STRING $string + unset string + STRING=x:y:z + print $STRING $string +0:Unsetting and recreation of tied normal parameters +>a:b a b +>x y z +>a:b a b +>x y z +>a:b a b +>x:y:z +>a:b a b +>x:y:z + + typeset -T tied1 tied2 + + typeset -T tied2 tied1 + +1:Attempts to swap tied variables are safe but futile +?(eval):typeset:2: already tied as non-scalar: tied2 + + string='look for a match in here' + if [[ ${string%%(#b)(match)*} = "look for a " ]]; then + print $match[1] $mbegin[1] $mend[1] $string[$mbegin[1],$mend[1]] + print $#match $#mbegin $#mend + else + print That didn\'t work. + fi +0:Parameters associated with backreferences +>match 12 16 match +>1 1 1 +#' deconfuse emacs + + string='and look for a MATCH in here' + if [[ ${(S)string%%(#m)M*H} = "and look for a in here" ]]; then + print $MATCH $MBEGIN $MEND $string[$MBEGIN,$MEND] + print $#MATCH + else + print Oh, dear. Back to the drawing board. + fi +0:Parameters associated with (#m) flag +>MATCH 16 20 MATCH +>5 + + string='this is a string' + print ${string//(#m)s/$MATCH $MBEGIN $MEND} +0:(#m) flag with pure string +>this 4 4 is 7 7 a s 11 11tring + + print ${${~:-*}//(#m)*/$MATCH=$MATCH} +0:(#m) flag with tokenized input +>*=* + + print -l JAMES${(u)${=:-$(echo yes yes)}}JOYCE + print -l JAMES${(u)${=:-$(echo yes yes she said yes i will yes)}}JOYCE +0:Bug with (u) flag reducing arrays to one element +>JAMESyesJOYCE +>JAMESyes +>she +>said +>i +>willJOYCE + + print -l JAMES${(u)${=:-$(echo yes yes she said yes i will yes she said she will and yes she did yes)}}JOYCE +0:New hash seive unique algorithm for arrays of more than 10 elements +>JAMESyes +>she +>said +>i +>will +>and +>didJOYCE + + foo= + print "${${foo}/?*/replacement}" +0:Quoted zero-length strings are handled properly +> + + file=aleftkept + print ${file//(#b)(*)left/${match/a/andsome}} + print ${file//(#b)(*)left/${match//a/andsome}} +0:Substitutions where $match is itself substituted in the replacement +>andsomekept +>andsomekept + + file=/one/two/three/four + print ${file:fh} + print ${file:F.1.h} + print ${file:F+2+h} + print ${file:F(3)h} + print ${file:F<4>h} + print ${file:F{5}h} +0:Modifiers with repetition +>/ +>/one/two/three +>/one/two +>/one +>/ +>/ + + baz=foo/bar + zab=oof+rab + print ${baz:s/\//+/} + print "${baz:s/\//+/}" + print ${zab:s/+/\//} + print "${zab:s/+/\//}" +0:Quoting of separator in substitution modifier +>foo+bar +>foo+bar +>oof/rab +>oof/rab + + bsbs='X\\\\Y' + print -r -- ${bsbs:s/\\/\\/} + print -r -- "${bsbs:s/\\/\\/}" + print -r -- ${bsbs:s/\\\\/\\\\/} + print -r -- "${bsbs:s/\\\\/\\\\/}" + print -r -- ${bsbs:gs/\\/\\/} + print -r -- "${bsbs:gs/\\/\\/}" + print -r -- ${bsbs:gs/\\\\/\\\\/} + print -r -- "${bsbs:gs/\\\\/\\\\/}" +0:Handling of backslashed backslashes in substitution modifier +>X\\\\Y +>X\\\\Y +>X\\\\Y +>X\\\\Y +>X\\\\Y +>X\\\\Y +>X\\\\Y +>X\\\\Y + + print -r ${${:-one/two}:s,/,X&Y,} + print -r ${${:-one/two}:s,/,X\&Y,} + print -r ${${:-one/two}:s,/,X\\&Y,} + print -r "${${:-one/two}:s,/,X&Y,}" + print -r "${${:-one/two}:s,/,X\&Y,}" + print -r "${${:-one/two}:s,/,X\\&Y,}" +0:Quoting of ampersand in substitution modifier RHS +>oneX/Ytwo +>oneX&Ytwo +>oneX\/Ytwo +>oneX/Ytwo +>oneX&Ytwo +>oneX\/Ytwo + + nully=($'a\0c' $'a\0b\0b' $'a\0b\0a' $'a\0b\0' $'a\0b' $'a\0' $'a') + for string in ${(o)nully}; do + for (( i = 1; i <= ${#string}; i++ )); do + foo=$string[i] + printf "%02x" $(( #foo )) + done + print + done +0:Sorting arrays with embedded nulls +>61 +>6100 +>610062 +>61006200 +>6100620061 +>6100620062 +>610063 + + array=(X) + patterns=("*X*" "spong" "a[b") + for pat in $patterns; do + print A${array[(r)$pat]}B C${array[(I)$pat]}D + done +0:Bad patterns should never match array elements +>AXB C1D +>AB C0D +>AB C0D + + foo=(a6 a117 a17 b6 b117 b17) + print ${(n)foo} + print ${(On)foo} +0:Numeric sorting +>a6 a17 a117 b6 b17 b117 +>b117 b17 b6 a117 a17 a6 + + x=sprodj + x[-10]=scrumf + print $x +0:Out of range negative scalar subscripts +>scrumfsprodj + + a=(some sunny day) + a[-10]=(we\'ll meet again) + print -l $a +0:Out of range negative array subscripts +>we'll +>meet +>again +>some +>sunny +>day + +# ' emacs likes this close quote + + a=(sping spang spong bumble) + print ${a[(i)spong]} + print ${a[(i)spung]} + print ${a[(ib.1.)spong]} + print ${a[(ib.4.)spong]} + print ${a[(ib.10.)spong]} +0:In and out of range reverse matched indices without and with b: arrays +>3 +>5 +>3 +>5 +>5 + + a="thrimblewuddlefrong" + print ${a[(i)w]} + print ${a[(i)x]} + print ${a[(ib.3.)w]} + print ${a[(ib.10.)w]} + print ${a[(ib.30.)w]} +0:In and out of range reverse matched indices without and with b: strings +>9 +>20 +>9 +>20 +>20 + + foo="line:with::missing::fields:in:it" + print -l ${(s.:.)foo} +0:Removal of empty fields in unquoted splitting +>line +>with +>missing +>fields +>in +>it + + foo="line:with::missing::fields:in:it" + print -l "${(s.:.)foo}" +0:Hacky removal of empty fields in quoted splitting with no "@" +>line +>with +>missing +>fields +>in +>it + + foo="line:with::missing::fields:in:it:" + print -l "${(@s.:.)foo}" +0:Retention of empty fields in quoted splitting with "@" +>line +>with +> +>missing +> +>fields +>in +>it +> + + str=abcd + print -l ${(s..)str} + print -l "${(s..)str}" +0:splitting of strings into characters +>a +>b +>c +>d +>a +>b +>c +>d + + array=('%' '$' 'j' '*' '$foo') + print ${array[(i)*]} "${array[(i)*]}" + print ${array[(ie)*]} "${array[(ie)*]}" + key='$foo' + print ${array[(ie)$key]} "${array[(ie)$key]}" + key='*' + print ${array[(ie)$key]} "${array[(ie)$key]}" +0:Matching array indices with and without quoting +>1 1 +>4 4 +>5 5 +>4 4 + +# Ordering of associative arrays is arbitrary, so we need to use +# patterns that only match one element. + typeset -A assoc_r + assoc_r=(star '*' of '*this*' and '!that!' or '(the|other)') + print ${(kv)assoc_r[(re)*]} + print ${(kv)assoc_r[(re)*this*]} + print ${(kv)assoc_r[(re)!that!]} + print ${(kv)assoc_r[(re)(the|other)]} + print ${(kv)assoc_r[(r)*at*]} + print ${(kv)assoc_r[(r)*(ywis|bliss|kiss|miss|this)*]} + print ${(kv)assoc_r[(r)(this|that|\(the\|other\))]} +0:Reverse subscripting associative arrays with literal matching +>star * +>of *this* +>and !that! +>or (the|other) +>and !that! +>of *this* +>or (the|other) + + print $ZSH_SUBSHELL + (print $ZSH_SUBSHELL) + ( (print $ZSH_SUBSHELL) ) + ( (print $ZSH_SUBSHELL); print $ZSH_SUBSHELL ) + print $(print $ZSH_SUBSHELL) + cat =(print $ZSH_SUBSHELL) +0:ZSH_SUBSHELL +>0 +>1 +>2 +>2 +>1 +>1 +>1 + + foo=("|" "?") + [[ "|" = ${(j.|.)foo} ]] && print yes || print no + [[ "|" = ${(j.|.)~foo} ]] && print yes || print no + [[ "|" = ${(~j.|.)foo} ]] && print yes || print no + [[ "|" = ${(~~j.|.)foo} ]] && print yes || print no + [[ "|" = ${(j.|.~)foo} ]] && print yes || print no + [[ "x" = ${(j.|.)foo} ]] && print yes || print no + [[ "x" = ${(j.|.)~foo} ]] && print yes || print no + [[ "x" = ${(~j.|.)foo} ]] && print yes || print no + [[ "x" = ${(~~j.|.)foo} ]] && print yes || print no + [[ "x" = ${(j.|.~)foo} ]] && print yes || print no +0:GLOBSUBST only on parameter substitution arguments +>no +>yes +>yes +>no +>no +>no +>yes +>no +>no +>no + + rcexbug() { + emulate -L zsh + setopt rcexpandparam + local -A hash + local -a full empty + full=(X x) + hash=(X x) + print ORDINARY ARRAYS + : The following behaves as documented in zshoptions + print FULL expand=$full + : Empty arrays remove the adjacent argument + print EMPTY expand=$empty + print ASSOCIATIVE ARRAY + print Subscript flags returning many values + print FOUND key=$hash[(I)X] val=$hash[(R)x] + : This should behave like $empty, and does + print LOST key=$hash[(I)y] val=$hash[(R)Y] + print Subscript flags returning single values + : Doc says "substitutes ... empty string" + : so must not behave like an empty array + print STRING key=$hash[(i)y] val=$hash[(r)Y] + } + rcexbug +0:Lookup failures on elements of arrays with RC_EXPAND_PARAM +>ORDINARY ARRAYS +>FULL expand=X expand=x +>EMPTY +>ASSOCIATIVE ARRAY +>Subscript flags returning many values +>FOUND key=X val=x +>LOST +>Subscript flags returning single values +>STRING key= val= + + print $zsh_eval_context[1] + [[ $ZSH_EVAL_CONTEXT = ${(j.:.)zsh_eval_context} ]] || print Not equal! + (( icontext = ${#zsh_eval_context} + 1 )) + contextfn() { print $(print $zsh_eval_context[icontext,-1]); } + contextfn +0:$ZSH_EVAL_CONTEXT and $zsh_eval_context +>toplevel +>shfunc cmdsubst + + foo="123456789" + print ${foo:3} + print ${foo: 1 + 3} + print ${foo:$(( 2 + 3))} + print ${foo:$(echo 3 + 3)} + print ${foo:3:1} + print ${foo: 1 + 3:(4-2)/2} + print ${foo:$(( 2 + 3)):$(( 7 - 6 ))} + print ${foo:$(echo 3 + 3):`echo 4 - 3`} + print ${foo: -1} + print ${foo: -10} + print ${foo:5:-2} +0:Bash-style offsets, scalar +>456789 +>56789 +>6789 +>789 +>4 +>5 +>6 +>7 +>9 +>123456789 +>67 + + foo=(1 2 3 4 5 6 7 8 9) + print ${foo:3} + print ${foo: 1 + 3} + print ${foo:$(( 2 + 3))} + print ${foo:$(echo 3 + 3)} + print ${foo:3:1} + print ${foo: 1 + 3:(4-2)/2} + print ${foo:$(( 2 + 3)):$(( 7 - 6 ))} + print ${foo:$(echo 3 + 3):`echo 4 - 3`} + print ${foo: -1} + print ${foo: -10} + print ${foo:5:-2} +0:Bash-style offsets, array +>4 5 6 7 8 9 +>5 6 7 8 9 +>6 7 8 9 +>7 8 9 +>4 +>5 +>6 +>7 +>9 +>1 2 3 4 5 6 7 8 9 +>6 7 + + testfn() { + emulate -L sh + set -A foo 1 2 3 + set -- 1 2 3 + str=abc + echo ${foo[*]:0:1} + echo ${foo[*]:1:1} + echo ${foo[*]: -1:1} + : + echo ${*:0:1} + echo ${*:1:1} + echo ${*: -1:1} + : + echo ${str:0:1} + echo ${str:1:1} + echo ${str: -1:1} + } + testfn +0:Bash-style offsets, Bourne-style indexing +>1 +>2 +>3 +>testfn +>1 +>3 +>a +>b +>c + + printf "%n" '[0]' +1:Regression test for identifier test +?(eval):1: not an identifier: [0] + + str=rts + print ${str:0:} +1:Regression test for missing length after offset +?(eval):2: unrecognized modifier + + foo="123456789" + print ${foo:5:-6} +1:Regression test for total length < 0 in string +?(eval):2: substring expression: 3 < 5 + + foo=(1 2 3 4 5 6 7 8 9) + print ${foo:5:-6} +1:Regression test for total length < 0 in array +?(eval):2: substring expression: 3 < 5 + + foo=(${(0)"$(print -n)"}) + print ${#foo} +0:Nularg removed from split empty string +>0 + + (set -- a b c + setopt shwordsplit + IFS= + print -rl "$*" + unset IFS + print -rl "$*") +0:Regression test for shwordsplit with null or unset IFS and quoted array +>abc +>a b c + + foo= + print ${foo:wq} + print ${:wq} +0:Empty parameter should not cause modifiers to crash the shell +> +> + +# This used to cause uncontrolled behaviour, but at best +# you got the wrong output so the check is worth it. + args() { print $#; } + args ${:*} + args ${:|} +0:Intersection and disjunction with empty parameters +>0 +>0 + + foo=(a b c) + bar=(1 2 3) + print ${foo:^bar} + print ${foo:^^bar} + foo=(a b c d) + bar=(1 2) + print ${foo:^bar} + print ${foo:^^bar} + foo=('a a' b) + bar=(1 '2 2') + print -l "${foo:^bar}" + print -l "${(@)foo:^bar}" +0:Zipping arrays, correct output +>a 1 b 2 c 3 +>a 1 b 2 c 3 +>a 1 b 2 +>a 1 b 2 c 1 d 2 +# maybe this should be changed to output "a a b 1" +>a a b +>1 +>a a +>1 +>b +>2 2 + + foo=(a b c) + bar=() + print ${foo:^bar} + print ${foo:^^bar} + print ${bar:^foo} + print ${bar:^^foo} + print ${bar:^bar} + print ${bar:^^bar} +0:Zipping arrays, one or both inputs empty +> +>a b c +> +>a b c +> +> + + foo=text + bar=() + print ${foo:^bar} + print ${bar:^^foo} + bar=other + print ${foo:^bar} + bar=(array elements) + print ${foo:^bar} + print ${foo:^^bar} + print ${bar:^foo} + print ${bar:^^foo} +0:Zipping arrays, scalar input +> +>text +>text other +>text array +>text array text elements +>array text +>array text elements text + + foo=(a b c) + print ${foo:^^^bar} +1:Zipping arrays, parsing +?(eval):2: not an identifier: ^bar + + (setopt nounset + print ${foo:^noexist}) +1:Zipping arrays, NO_UNSET part 1 +?(eval):2: noexist: parameter not set + + (setopt nounset + print ${noexist:^foo}) +1:Zipping arrays, NO_UNSET part 2 +?(eval):2: noexist: parameter not set + + expr="a@b,c@d:e@f,g@h:i@j,k@l" + for sep in : , @; do + print -l ${(ps.$sep.)expr} + done +0:Use of variable to get separator when splitting parameter +>a@b,c@d +>e@f,g@h +>i@j,k@l +>a@b +>c@d:e@f +>g@h:i@j +>k@l +>a +>b,c +>d:e +>f,g +>h:i +>j,k +>l + + SHLVL=1 + $ZTST_testdir/../Src/zsh -fc 'echo $SHLVL' + $ZTST_testdir/../Src/zsh -fc '(echo $SHLVL)' +0:SHLVL appears sensible when about to exit shell +>2 +>2 + + # SHLVL is incremented twice and decremented once in between. + SHLVL=1 + $ZTST_testdir/../Src/zsh -fc $ZTST_testdir/../Src/zsh' -fc "echo \$SHLVL"' + $ZTST_testdir/../Src/zsh -fc '('$ZTST_testdir/../Src/zsh' -fc "echo \$SHLVL")' + $ZTST_testdir/../Src/zsh -fc '( ('$ZTST_testdir/../Src/zsh' -fc "echo \$SHLVL"))' +0:SHLVL decremented upon implicit exec optimisation +>2 +>2 +>2 + + # SHLVL is incremented twice with no decrement in between. + SHLVL=1 + $ZTST_testdir/../Src/zsh -fc '('$ZTST_testdir/../Src/zsh' -fc "echo \$SHLVL"); exit' + $ZTST_testdir/../Src/zsh -fc '(exec '$ZTST_testdir/../Src/zsh' -fc "echo \$SHLVL"); exit' + $ZTST_testdir/../Src/zsh -fc '( ('$ZTST_testdir/../Src/zsh' -fc "echo \$SHLVL"); exit)' +0:SHLVL not decremented upon exec in subshells +>3 +>3 +>3 + +# The following tests the return behaviour of parsestr/parsestrnoerr + alias param-test-alias='print $'\''\x45xpanded in substitution'\' + param='$(param-test-alias)' + print ${(e)param} +0:Alias expansion in command substitution in parameter evaluation +>Expanded in substitution + + a=1 b=2 c=3 + : One; + function { + : Two + echo $_ + print -l $argv + } $_ Three + print -l $_ Four; +0:$_ with anonymous function +>Two +>One +>Three +>Three +>Four + + a=1 b=2 c=3 + : One + function { + : Two + echo $_ + print -l $argv + } + print -l "$_" Four +0:$_ with anonymous function without arguments +>Two +> +> +>Four + + funnychars='The qu*nk br!wan f@x j/mps o[]r \(e la~# ^"&;' + [[ $funnychars = ${~${(b)funnychars}} ]] +0:${(b)...} quoting protects from GLOB_SUBST + + set -- foo + echo $(( $#*3 )) + emulate sh -c 'nolenwithoutbrace() { echo $#-1; }' + nolenwithoutbrace +0:Avoid confusion after overloaded characters in braceless substitution in sh +>13 +>0-1 + + a="aaa bab cac" + b=d + echo $a:gs/a/${b}/ + a=(aaa bab cac) + echo $a:gs/a/${b}/ +0:History modifier works the same for scalar and array substitution +>ddd bdb cdc +>ddd bdb cdc + + a=1_2_3_4_5_6 + print ${a#(*_)(#c2)} + print ${a#(*_)(#c5)} + print ${a#(*_)(#c7)} +0:Complicated backtracking with match counts +>3_4_5_6 +>6 +>1_2_3_4_5_6 + + (setopt shwordsplit + do_test() { + print $#: "$@" + } + foo=bar + foo2="bar bar" + do_test ${:- foo } + do_test ${:- foo bar } + do_test ${:- $foo } + do_test ${:- $foo2 } + do_test x${:- foo }y + do_test x${:- foo bar }y + do_test x${:- $foo }y + do_test x${:- $foo2 }y + do_test x${foo:+ $foo }y + ) +0:We Love SH_WORD_SPLIT Day celebrated with space at start of internal subst +>1: foo +>2: foo bar +>1: bar +>2: bar bar +>3: x foo y +>4: x foo bar y +>3: x bar y +>4: x bar bar y +>3: x bar y + + (unsetopt shwordsplit # default, for clarity + do_test() { + print $#: "$@" + } + foo=bar + foo2="bar bar" + do_test ${:- foo } + do_test ${:- foo bar } + do_test ${:- $foo } + do_test ${:- $foo2 } + do_test x${:- foo }y + do_test x${:- foo bar }y + do_test x${:- $foo }y + do_test x${:- $foo2 }y + do_test x${foo:+ $foo }y + ) +0:We Love NO_SH_WORD_SPLIT Even More Day celebrated as sanity check +>1: foo +>1: foo bar +>1: bar +>1: bar bar +>1: x foo y +>1: x foo bar y +>1: x bar y +>1: x bar bar y +>1: x bar y + + testfn() { + local scalar=obfuscation + local -a array=(alpha bravo charlie delta echo foxtrot) + local -A assoc=(one eins two zwei three drei four vier) + local name subscript + for name subscript in scalar 3 array 5 assoc three; do + print ${${(P)name}[$subscript]} + done + } + testfn +0:${(P)...} with normal subscripting +>f +>echo +>drei + + testfn() { + local s1=foo s2=bar + local -a val=(s1) + print ${${(P)val}[1,3]} + val=(s1 s2) + print ${${(P)val}[1,3]} + } + testfn +1:${(P)...} with array as name +>foo +?testfn:5: parameter name reference used with array + + testfn() { + local -A assoc=(one buckle two show three knock four door) + local name='assoc[two]' + print ${${(P)name}[2,3]} + } + testfn +0:${(P)...} with internal subscripting +>ho + + testfn() { + local one=two + local two=three + local three=four + local -a four=(all these worlds belong to foo) + print ${(P)${(P)${(P)one}}} + print ${${(P)${(P)${(P)one}}}[3]} + } + testfn +0:nested parameter name references +>all these worlds belong to foo +>worlds + + ( + path=(/random /value) + testfn1() { + local path= + print $#path + } + testfn1 + testfn2() { + local path=/somewhere + print $#path $path + } + testfn2 + print $#path $path + ) +0:Local special variables with loose typing +>0 +>1 /somewhere +>2 /random /value + + print -r -- ${(q+):-} + print -r -- ${(q+)IFS} + print -r -- ${(q+):-oneword} + print -r -- ${(q+):-two words} + print -r -- ${(q+):-three so-called \'words\'} + (setopt rcquotes; print -r -- ${(q+):-three so-called \'words\'}) +0:${(q+)...} +>'' +>$' \t\n\C-@' +>oneword +>'two words' +>'three so-called '\''words'\' +>'three so-called ''words''' + + array=(one two three) + array[1]=${nonexistent:-foo} + print $array +0:"-" works after "[" in same expression (Dash problem) +>foo two three + + ( + setopt shwordsplit + set -- whim:wham:whom + IFS=: + print -l $@ + ) +0:Splitting of $@ on IFS: single element +>whim +>wham +>whom + + ( + setopt shwordsplit + set -- one:two bucklemy:shoe + IFS=: + print -l $@ + ) +0:Splitting of $@ on IFS: multiple elements +# No forced joining in this case +>one +>two +>bucklemy +>shoe + + ( + set -- one:two bucklemy:shoe + print -l ${(s.:.)@} + ) +0:Splitting of $@ on (s): multiple elements +# Forced joining in this case +>one +>two bucklemy +>shoe + + ( + set -- one:two bucklemy:shoe + print -l ${(@s.:.)@} + ) +0:Splitting of $@ on (@s): multiple elements +# Forced non-joining in this case +>one +>two +>bucklemy +>shoe + + ( + set -- one:two bucklemy:shoe + IFS= + setopt shwordsplit + print -l ${@} ${(s.:.)*} ${(s.:.j.-.)*} + ) +0:Joining of $@ does not happen when IFS is empty, but splitting $* does +>one:two +>bucklemy:shoe +>one +>twobucklemy +>shoe +>one +>two-bucklemy +>shoe + + ( + set -- "one two" "bucklemy shoe" + IFS= + setopt shwordsplit rcexpandparam + print -l "X${(@j.-.)*}" + ) +0:Use of @ does not prevent forced join with j +>Xone two-bucklemy shoe + + () { print -r -- "${(q)1}" "${(b)1}" "${(qq)1}" } '=foo' +0:(q) and (b) quoting deal with the EQUALS option +>\=foo =foo '=foo' + + args() { print $#; } + a=(foo) + args "${a[3,-1]}" + args "${(@)a[3,-1]}" +0:Out-of-range multiple array subscripts with quoting, with and without (@) +>1 +>0 + + a='~-/'; echo $~a +0:Regression: "-" became Dash in workers/37689, breaking ~- expansion +*>* +F:We do not care what $OLDPWD is, as long as it doesn't cause an error diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D05array.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D05array.ztst new file mode 100644 index 00000000..1fa607dd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D05array.ztst @@ -0,0 +1,112 @@ +# Tests for array indexing + +%prep + + foo=(a b c d e f g) + arr=(foo bar baz) + mkdir array.tmp + touch array.tmp/{1..9} + +%test + + echo .$foo[1]. +0:The first element +>.a. + + echo .$foo[1,4]. +0:Normal multi-item indexing +>.a b c d. + + echo .$foo[1,0]. +0:This should be empty +>.. + + echo .$foo[4,1]. +0:Another empty slice +>.. + + echo .$foo[1,-8]. +0:An empty slice with a negative end +>.. + + echo .$foo[0]. +0:Treat 0 as empty +>.. + + echo .$foo[0,0]. +0:Treat 0,0 as empty +>.. + + echo .$foo[0,1]. +0:Another weird way to access the first element +>.a. + + echo .$foo[3]. +0:An inner element +>.c. + + echo .$foo[2,2]. +0:Another inner element +>.b. + + echo .$foo[2,-4]. +0:A slice with a negative end +>.b c d. + + echo .$foo[-4,5]. +0:A slice with a negative start +>.d e. + + echo .$foo[-6,-2]. +0:A slice with a negative start and end +>.b c d e f. + + echo .${${arr[2]}[1]}. + echo .${${arr[-2]}[1]}. + echo .${${arr[2,2]}[1]}. + echo .${${arr[-2,-2]}[1]}. + echo .${${arr[2,-2]}[1]}. + echo .${${arr[-2,2]}[1]}. +0:Slices should return an array, elements a scalar +>.b. +>.b. +>.bar. +>.bar. +>.bar. +>.bar. + + setopt ksh_arrays + echo .${foo[1,2]}. + unsetopt ksh_arrays +0:Ksh array indexing +>.b c. + + setopt ksh_arrays + echo .${foo[0,1]}. + unsetopt ksh_arrays +0:Ksh array indexing (ii) +>.a b. + + setopt ksh_arrays + echo .${foo[1,-1]}. + unsetopt ksh_arrays +0:Ksh array indexing (iii) +>.b c d e f g. + + cd array.tmp + echo . ?([3,5]) . + cd .. +0:Glob array indexing +>. 3 4 5 . + + cd array.tmp + echo . ?([2,-2]) . + cd .. +0:Glob array indexing (ii) +>. 2 3 4 5 6 7 8 . + + cd array.tmp + echo . ?([-6,-4]) . + cd .. +0:Glob array indexing (iii) +>. 4 5 6 . diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D06subscript.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D06subscript.ztst new file mode 100644 index 00000000..14492366 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D06subscript.ztst @@ -0,0 +1,268 @@ +# Test parameter subscripting. + +%prep + + s='Twinkle, twinkle, little *, [how] I [wonder] what? You are!' + a=('1' ']' '?' '\2' '\]' '\?' '\\3' '\\]' '\\?' '\\\4' '\\\]' '\\\?') + typeset -g -A A + A=($a) + +%test + + x=',' + print $s[(i)winkle] $s[(I)winkle] + print ${s[(i)You are]} $#s + print ${s[(r)$x,(R)$x]} +0:Scalar pattern subscripts without wildcards +>2 11 +>53 60 +>, twinkle, little *, + + x='*' + print $s[(i)*] $s[(i)\*] $s[(i)$x*] $s[(i)${(q)x}*] $s[(I)$x\*] + print $s[(r)?,(R)\?] $s[(r)\?,(R)?] + print $s[(r)\*,(R)*] + print $s[(r)\],(R)\[] +0:Scalar pattern subscripts with wildcards +>1 26 1 26 26 +>Twinkle, twinkle, little *, [how] I [wonder] what? ? You are! +>*, [how] I [wonder] what? You are! +>] I [ + + print $s[(i)x] : $s[(I)x] + print $s[(r)x] : $s[(R)x] +0:Scalar pattern subscripts that do not match +>61 : 0 +>: + + print -R $s[$s[(i)\[]] $s[(i)$s[(r)\*]] $s[(i)${(q)s[(r)\]]}] +0:Scalar subscripting using a pattern subscript to get the index +>[ 1 33 + + print -R $a[(r)?] $a[(R)?] + print $a[(n:2:i)?] $a[(n:2:I)?] + print $a[(i)\?] $a[(I)\?] + print $a[(i)*] $a[(i)\*] +0:Array pattern subscripts +>1 ? +>2 2 +>3 3 +>1 13 + + # It'd be nice to do some of the following with (r), but we run into + # limitations of the ztst script parsing of backslashes in the output. + print -R $a[(i)\\\\?] $a[(i)\\\\\?] + print -R $a[(i)\\\\\\\\?] $a[(i)\\\\\\\\\?] + print -R ${a[(i)\\\\\\\\?]} ${a[(i)\\\\\\\\\?]} + print -R "$a[(i)\\\\\\\\?] $a[(i)\\\\\\\\\?]" + print -R $a[(i)\]] $a[(i)\\\\\]] $a[(i)\\\\\\\\\]] $a[(i)\\\\\\\\\\\\\]] + print -R $a[(i)${(q)a[5]}] $a[(i)${(q)a[8]}] $a[(i)${(q)a[11]}] + print -R $a[(i)${a[3]}] $a[(i)${a[6]}] $a[(i)${a[9]}] $a[(i)${a[12]}] +0:Array pattern subscripts with multiple backslashes +>4 6 +>7 9 +>7 9 +>7 9 +>2 5 8 11 +>5 8 11 +>1 3 4 6 + + print -R $A[1] $A[?] $A[\\\\3] $A[\\\]] + print -R $A[$a[11]] + print -R $A[${(q)a[5]}] +0:Associative array lookup (direct subscripting) +>] \2 \\] \? +>\\\? +>\\\? + + # The (o) is necessary here for predictable output ordering + print -R $A[(I)\?] ${(o)A[(I)?]} + print -R $A[(i)\\\\\\\\3] + print -R $A[(I)\\\\\\\\\?] ${(o)A[(I)\\\\\\\\?]} +0:Associative array lookup (pattern subscripting) +>? 1 ? +>\\3 +>\\? \\3 \\? + + print -R $A[(R)\?] : ${(o)A[(R)?]} + print -R $A[(R)\\\\\?] ${(o)A[(R)\\\\?]} ${(o)A[(R)\\\\\?]} + print -R ${(o)A[(R)\\\\\\\\\]]} +0:Associative array lookup (reverse subscripting) +>: ] +>\? \2 \? \? +>\\] + + eval 'A[*]=star' +1:Illegal associative array assignment +?(eval):1: A: attempt to set slice of associative array + + x='*' + A[$x]=xstar + A[${(q)x}]=qxstar + print -R ${(k)A[(r)xstar]} $A[$x] + print -R ${(k)A[(r)qxstar]} $A[${(q)x}] + A[(e)*]=star + A[\*]=backstar + print -R ${(k)A[(r)star]} $A[(e)*] + print -R ${(k)A[(r)backstar]} $A[\*] +0:Associative array assignment +>* xstar +>\* qxstar +>* star +>\* backstar + + o='[' + c=']' + A[\]]=cbrack + A[\[]=obrack + A[\\\[]=backobrack + A[\\\]]=backcbrack + print -R $A[$o] $A[$c] $A[\[] $A[\]] $A[\\\[] $A[\\\]] + print -R $A[(i)\[] $A[(i)\]] $A[(i)\\\\\[] $A[(i)\\\\\]] +0:Associative array keys with open and close brackets +>obrack cbrack obrack cbrack backobrack backcbrack +>[ ] \[ \] + + print -R $A[$o] $A[$s[(r)\[]] + print -R $A[(r)$c] $A[(r)$s[(r)\]]] + print -R $A[$A[(i)\\\\\]]] +0:Associative array lookup using a pattern subscript to get the key +>obrack obrack +>] ] +>backcbrack + + print -R ${A[${A[(r)\\\\\\\\\]]}]::=zounds} + print -R ${A[${A[(r)\\\\\\\\\]]}]} + print -R $A[\\\\\]] +0:Associative array substitution-assignment with reverse pattern subscript key +>zounds +>zounds +>zounds + + print -R ${(o)A[(K)\]]} + print -R ${(o)A[(K)\\\]]} +0:Associative array keys interpreted as patterns +>\2 backcbrack cbrack star +>\\\4 \\\? star zounds + +# It doesn't matter which element we get, since we never guarantee +# ordering of an associative array. So just test the number of matches. + array=(${(o)A[(k)\]]}) + print ${#array} + array=(${(o)A[(k)\\\]]}) + print ${#array} +0:Associative array keys interpreted as patterns, single match +>1 +>1 + + typeset -g "A[one\"two\"three\"quotes]"=QQQ + typeset -g 'A[one\"two\"three\"quotes]'=qqq + print -R "$A[one\"two\"three\"quotes]" + print -R $A[one\"two\"three\"quotes] + A[one"two"three"four"quotes]=QqQq + print -R $A[one"two"three"four"quotes] + print -R $A[$A[(i)one\"two\"three\"quotes]] + print -R "$A[$A[(i)one\"two\"three\"quotes]]" +0:Associative array keys with double quotes +>QQQ +>qqq +>QqQq +>qqq +>QQQ + + print ${x::=$A[$A[(i)one\"two\"three\"quotes]]} + print $x + print ${x::="$A[$A[(i)one\"two\"three\"quotes]]"} + print $x +0:More keys with double quotes, used in assignment-expansion +>qqq +>qqq +>QQQ +>QQQ + + qqq=lower + QQQ=upper + print ${(P)A[one\"two\"three\"quotes]} + print "${(P)A[$A[(i)one\"two\"three\"quotes]]}" +0:Keys with double quotes and the (P) expansion flag +>lower +>upper + + typeset -ga empty + echo X${${empty##*}[-1]}X +0:Negative index applied to substition result from empty array +>XX + + print $empty[(i)] $empty[(I)] +0:(i) returns 1 for empty array, (I) returns 0. +>1 0 + + array=(one two three four) + print X$array[0]X +0:Element zero is empty if KSH_ZERO_SUBSCRIPT is off. +>XX + + array[0]=fumble +1:Can't set element zero if KSH_ZERO_SUBSCRIPT is off. +?(eval):1: array: assignment to invalid subscript range + + print X$array[(R)notfound]X +0:(R) returns empty if not found if KSH_ZERO_SUBSCRIPT is off. +>XX + + setopt KSH_ZERO_SUBSCRIPT + print X$array[0]X +0:Element zero is element one if KSH_ZERO_SUBSCRIPT is on. +>XoneX + + array[0]=fimble + print $array +0:Can set element zero if KSH_ZERO_SUBSCRIPT is on. +>fimble two three four + + print X$array[(R)notfound]X +0:(R) yuckily returns the first element on failure withe KSH_ZERO_SUBSCRIPT +>XfimbleX + + unsetopt KSH_ZERO_SUBSCRIPT + array[(R)notfound,(r)notfound]=(help help here come the seventies retreads) + print $array +0:[(R)notfound,(r)notfound] replaces the whole array +>help help here come the seventies retreads + + string="Why, if it isn't Officer Dibble" + print "[${string[0]}][${string[1]}][${string[0,3]}]" +0:String subscripts with KSH_ZERO_SUBSCRIPT unset +>[][W][Why] + + setopt KSH_ZERO_SUBSCRIPT + print "[${string[0]}][${string[1]}][${string[0,3]}]" +0:String subscripts with KSH_ZERO_SUBSCRIPT set +>[W][W][Why] + + unsetopt KSH_ZERO_SUBSCRIPT + string[0,3]="Goodness" + print $string +0:Assignment to chunk of string ignores element 0 +>Goodness, if it isn't Officer Dibble + + string[0]=! +1:Can't set only element zero of string +?(eval):1: string: assignment to invalid subscript range + + typeset -A assoc=(leader topcat officer dibble sidekick choochoo) + alias myind='echo leader' myletter='echo 1' myletter2='echo 4' + print ${assoc[$(myind)]} + print $assoc[$(myind)] + print ${assoc[$(myind)][$(myletter)]}${assoc[$(myind)][$(myletter2)]} + assoc[$(myind)]='of the gang' + print ${assoc[$(myind)]} + print $assoc[$(myind)] + print $assoc[leader] +0: Parsing subscript with non-trivial tokenisation +>topcat +>topcat +>tc +>of the gang +>of the gang +>of the gang diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D07multibyte.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D07multibyte.ztst new file mode 100644 index 00000000..e2031534 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D07multibyte.ztst @@ -0,0 +1,587 @@ +%prep + +# Find a UTF-8 locale. + setopt multibyte +# Don't let LC_* override our choice of locale. + unset -m LC_\* + mb_ok= + langs=(en_{US,GB}.{UTF-,utf}8 en.UTF-8 + $(locale -a 2>/dev/null | egrep 'utf8|UTF-8')) + for LANG in $langs; do + if [[ é = ? ]]; then + mb_ok=1 + break; + fi + done + if [[ -z $mb_ok ]]; then + ZTST_unimplemented="no UTF-8 locale or multibyte mode is not implemented" + else + print -u $ZTST_fd Testing multibyte with locale $LANG + mkdir multibyte.tmp && cd multibyte.tmp + fi + +%test + + a=ténébreux + for i in {1..9}; do + print ${a[i]} + for j in {$i..9}; do + print $i $j ${a[i,j]} ${a[-j,-i]} + done + done +0:Basic indexing with multibyte characters +>t +>1 1 t x +>1 2 té ux +>1 3 tén eux +>1 4 téné reux +>1 5 ténéb breux +>1 6 ténébr ébreux +>1 7 ténébre nébreux +>1 8 ténébreu énébreux +>1 9 ténébreux ténébreux +>é +>2 2 é u +>2 3 én eu +>2 4 éné reu +>2 5 énéb breu +>2 6 énébr ébreu +>2 7 énébre nébreu +>2 8 énébreu énébreu +>2 9 énébreux ténébreu +>n +>3 3 n e +>3 4 né re +>3 5 néb bre +>3 6 nébr ébre +>3 7 nébre nébre +>3 8 nébreu énébre +>3 9 nébreux ténébre +>é +>4 4 é r +>4 5 éb br +>4 6 ébr ébr +>4 7 ébre nébr +>4 8 ébreu énébr +>4 9 ébreux ténébr +>b +>5 5 b b +>5 6 br éb +>5 7 bre néb +>5 8 breu énéb +>5 9 breux ténéb +>r +>6 6 r é +>6 7 re né +>6 8 reu éné +>6 9 reux téné +>e +>7 7 e n +>7 8 eu én +>7 9 eux tén +>u +>8 8 u é +>8 9 ux té +>x +>9 9 x t + + s=é + print A${s[-2]}A B${s[-1]}B C${s[0]}C D${s[1]}D E${s[2]}E +0:Out of range subscripts with multibyte characters +>AA BéB CC DéD EE + + print ${a[(i)é]} ${a[(I)é]} ${a[${a[(i)é]},${a[(I)é]}]} +0:Reverse indexing with multibyte characters +>2 4 éné + + print ${a[(r)én,(r)éb]} +0:Subscript searching with multibyte characters +>énéb + + print ${a[(rb:1:)é,-1]} + print ${a[(rb:2:)é,-1]} + print ${a[(rb:3:)é,-1]} + print ${a[(rb:4:)é,-1]} + print ${a[(rb:5:)é,-1]} +0:Subscript searching with initial offset +>énébreux +>énébreux +>ébreux +>ébreux +> + + print ${a[(rn:1:)é,-1]} + print ${a[(rn:2:)é,-1]} + print ${a[(rn:3:)é,-1]} +0:Subscript searching with count +>énébreux +>ébreux +> + + print ${a[(R)én,(R)éb]} +0:Backward subscript searching with multibyte characters +>énéb + +# Starting offsets with (R) seem to be so strange as to be hardly +# worth testing. + + setopt extendedglob + [[ $a = (#b)t(én)(éb)reux ]] || print "Failed to match." >&2 + for i in {1..${#match}}; do + print $match[i] $mbegin[i] $mend[i] ${a[$mbegin[i],$mend[i]]} + done +0:Multibyte offsets in pattern tests +>én 2 3 én +>éb 4 5 éb + + b=${(U)a} + print $b + print ${(L)b} + desdichado="Je suis le $a, le veuf, l'inconsolé" + print ${(C)desdichado} + lxiv="l'état c'est moi" + print ${(C)lxiv} +0:Case modification of multibyte strings +>TÉNÉBREUX +>ténébreux +>Je Suis Le Ténébreux, Le Veuf, L'Inconsolé +>L'État C'Est Moi + + array=(ølaf ødd øpened án encyclopædia) + barray=(${(U)array}) + print $barray + print ${(L)barray} + print ${(C)array} + print ${(C)barray} +0:Case modification of arrays with multibyte strings +>ØLAF ØDD ØPENED ÁN ENCYCLOPÆDIA +>ølaf ødd øpened án encyclopædia +>Ølaf Ødd Øpened Án Encyclopædia +>Ølaf Ødd Øpened Án Encyclopædia + + print $(( ##¥ )) + pound=£ + print $(( #pound )) + alpha=α + print $(( ##α )) $(( #alpha )) +0:Conversion to Unicode in mathematical expressions +>165 +>163 +>945 945 + + unsetopt posix_identifiers + expr='hähä=3 || exit 1; print $hähä' + eval $expr + setopt posix_identifiers + (eval $expr) +1:POSIX_IDENTIFIERS option +>3 +?(eval):1: command not found: hähä=3 + + foo="Ølaf«Ødd«øpénëd«ån«àpple" + print -l ${(s.«.)foo} + ioh="Ἐν ἀρχῇ ἦν ὁ λόγος, καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ θεὸς ἦν ὁ λόγος." + print -l ${=ioh} + print ${(w)#ioh} +0:Splitting with multibyte characters +>Ølaf +>Ødd +>øpénëd +>ån +>àpple +>Ἐν +>ἀρχῇ +>ἦν +>ὁ +>λόγος, +>καὶ +>ὁ +>λόγος +>ἦν +>πρὸς +>τὸν +>θεόν, +>καὶ +>θεὸς +>ἦν +>ὁ +>λόγος. +>17 + + read -d £ one + read -d £ two + print $one + print $two +0:read with multibyte delimiter +first +>second + + (IFS=« + read -d » -A array + print -l $array) +0:read -A with multibyte IFS +dominus +>illuminatio +>mea + + read -k2 -u0 twochars + print $twochars +0:read multibyte characters +<«»ignored +>«» + + read -q -u0 mb + print $? +0:multibyte character makes read -q return false +<« +>1 + + # See if the system grokks first-century Greek... + ioh="Ἐν ἀρχῇ ἦν ὁ λόγος, καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ θεὸς ἦν ὁ λόγος." + for (( i = 1; i <= ${#ioh}; i++ )); do + # FC3 doesn't recognise ῇ (U+1FC7: Greek small letter eta with + # perispomeni and ypogegrammeni, of course) as a lower case character. + if [[ $ioh[i] != [[:lower:]] && $i != 7 ]]; then + for tp in upper space punct invalid; do + if [[ $tp = invalid || $ioh[i] = [[:${tp}:]] ]]; then + print "$i: $tp" + break + fi + done + fi + done +0:isw* functions on non-ASCII wide characters +>1: upper +>3: space +>8: space +>11: space +>13: space +>19: punct +>20: space +>24: space +>26: space +>32: space +>35: space +>40: space +>44: space +>49: punct +>50: space +>54: space +>59: space +>62: space +>64: space +>70: punct + + ioh="Ἐν ἀρχῇ ἦν ὁ λόγος, καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ θεὸς ἦν ὁ λόγος" + print ${ioh#[[:alpha:]]##} + print ${ioh##[[:alpha:]]##} + print ${ioh%[[:alpha:]]##} + print ${ioh%%[[:alpha:]]##} + print ${(S)ioh#λ*ς} + print ${(S)ioh##λ*ς} + print ${(S)ioh%θ*ς} + print ${(S)ioh%%θ*ς} +0:Parameter #, ##, %, %% with multibyte characters +>ν ἀρχῇ ἦν ὁ λόγος, καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ θεὸς ἦν ὁ λόγος +> ἀρχῇ ἦν ὁ λόγος, καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ θεὸς ἦν ὁ λόγος +>Ἐν ἀρχῇ ἦν ὁ λόγος, καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ θεὸς ἦν ὁ λόγο +>Ἐν ἀρχῇ ἦν ὁ λόγος, καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ θεὸς ἦν ὁ +>Ἐν ἀρχῇ ἦν ὁ , καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ θεὸς ἦν ὁ λόγος +>Ἐν ἀρχῇ ἦν ὁ +>Ἐν ἀρχῇ ἦν ὁ λόγος, καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ ἦν ὁ λόγος +>Ἐν ἀρχῇ ἦν ὁ λόγος, καὶ ὁ λόγος ἦν πρὸς τὸν θεόν, καὶ + + a="1ë34ë6" + print ${(BEN)a#*4} + print ${(BEN)a##*ë} + print ${(BEN)a%4*} + print ${(BEN)a%%ë*} + print ${(SBEN)a#ë3} + print ${(SBEN)a%4ë} +0:Flags B, E, N and S in ${...#...} and ${...%...} +>1 5 4 +>1 6 5 +>4 7 3 +>2 7 5 +>2 4 2 +>4 6 2 + + foo=(κατέβην χθὲς εἰς Πειραιᾶ) + print ${(l.3..¥.r.3..£.)foo} + print ${(l.4..¥.r.2..£.)foo} + print ${(l.5..¥.r.1..£.)foo} + print ${(l.4..¥..«.r.4..£..».)foo} + print ${(l.4..¥..Σωκράτης.r.4..£..Γλαύκωνος.)foo} +0:simultaneous left and right padding +>κατέβη ¥χθὲς£ ¥¥εἰς£ Πειραι +>¥κατέβ ¥¥χθὲς ¥¥¥εἰς ¥Πειρα +>¥¥κατέ ¥¥¥χθὲ ¥¥¥¥εἰ ¥¥Πειρ +>«κατέβην ¥«χθὲς»£ ¥¥«εἰς»£ «Πειραιᾶ +>ςκατέβην ηςχθὲςΓλ τηςεἰςΓλ ςΠειραιᾶ +# er... yeah, that looks right... + + foo=picobarn + print ${foo:s£bar£rod£:s¥rod¥stick¥} +0:Delimiters in modifiers +>picostickn + +# TODO: if we get paired multibyte bracket delimiters to work +# (as Emacs does, the smug so-and-so), the following should change. + foo=bar + print ${(r£5££X£)foo} + print ${(l«10««Y««HI«)foo} +0:Delimiters in parameter flags +>barXX +>YYYYYHIbar + + printf "%4.3s\n" főobar +0:Multibyte characters in printf widths +> főo + +# We ask for case-insensitive sorting here (and supply upper case +# characters) so that we exercise the logic in the shell that lowers the +# case of the string for case-insensitive sorting. + print -oi HÛH HÔH HÎH HÊH HÂH + (LC_ALL=C; print -oi HAH HUH HEH HÉH HÈH) +0:Multibyte characters in print sorting +>HÂH HÊH HÎH HÔH HÛH +>HAH HEH HUH HÈH HÉH + +# These are control characters in Unicode, so don't show up. +# We just want to check they're not being treated as tokens. + for x in {128..150}; do + print ${(#)x} + done | while read line; do + print ${#line} $(( #line )) + done +0:evaluated character number with multibyte characters +>1 128 +>1 129 +>1 130 +>1 131 +>1 132 +>1 133 +>1 134 +>1 135 +>1 136 +>1 137 +>1 138 +>1 139 +>1 140 +>1 141 +>1 142 +>1 143 +>1 144 +>1 145 +>1 146 +>1 147 +>1 148 +>1 149 +>1 150 + + touch ngs1txt ngs2txt ngs10txt ngs20txt ngs100txt ngs200txt + setopt numericglobsort + print -l ngs* +0:NUMERIC_GLOB_SORT option in UTF-8 locale +>ngs1txt +>ngs2txt +>ngs10txt +>ngs20txt +>ngs100txt +>ngs200txt + +# Not strictly multibyte, but gives us a well-defined locale for testing. + foo=$'X\xc0Y\x07Z\x7fT' + print -r ${(q)foo} +0:Backslash-quoting of unprintable/invalid characters uses $'...' +>X$'\300'Y$'\a'Z$'\177'T + +# This also isn't strictly multibyte and is here to reduce the +# likelihood of a "cannot do character set conversion" error. + (print $'\u00e9') 2>&1 | read + if [[ $REPLY != é ]]; then + print "warning: your system can't do simple Unicode conversion." >&$ZTST_fd + print "Check you have a correctly installed iconv library." >&$ZTST_fd + # cheat + repeat 4 print OK + else + testfn() { (LC_ALL=C; print $'\u00e9') } + repeat 4 testfn 2>&1 | while read line; do + if [[ $line = *"character not in range"* ]]; then + print OK + elif [[ $line = "?" ]]; then + print OK + else + print Failed: no error message and no question mark + fi + done + fi + true +0:error handling in Unicode quoting +>OK +>OK +>OK +>OK + + tmp1='glob/\(\)Ą/*' + [[ glob/'()Ą'/foo == $~tmp1 ]] && print "Matched against $tmp1" + tmp1='glob/\(\)Ā/*' + [[ glob/'()Ā'/bar == $~tmp1 ]] && print "Matched against $tmp1" +0:Backslashes and metafied characters in patterns +>Matched against glob/()Ą/* +>Matched against glob/()Ā/* + + mkdir 梶浦由記 'Пётр Ильич Чайковский' + (cd 梶浦由記; print ${${(%):-%~}:t}) + (cd 'Пётр Ильич Чайковский'; print ${${(%):-%~}:t}) +0:Metafied characters in prompt expansion +>梶浦由記 +>Пётр Ильич Чайковский + + ( + setopt nonomatch + tmp1=Ą + tmpA=(Ą 'Пётр Ильич Чайковский' 梶浦由記) + print ${tmp1} ${(%)tmp1} ${(%%)tmp1} + print ${#tmp1} ${#${(%)tmp1}} ${#${(%%)tmp1}} + print ${tmpA} + print ${(%)tmpA} + print ${(%%)tmpA} + ) +0:More metafied characters in prompt expansion +>Ą Ą Ą +>1 1 1 +>Ą Пётр Ильич Чайковский 梶浦由記 +>Ą Пётр Ильич Чайковский 梶浦由記 +>Ą Пётр Ильич Чайковский 梶浦由記 + + setopt cbases + print $'\xc5' | read + print $(( [#16] #REPLY )) +0:read passes through invalid multibyte characters +>0xC5 + + word=abcま + word[-1]= + print $word + word=abcま + word[-2]= + print $word + word=abcま + word[4]=d + print $word + word=abcま + word[3]=not_c + print $word +0:assignment with negative indices +>abc +>abま +>abcd +>abnot_cま + + # The following doesn't necessarily need UTF-8, but this gives + # us the full effect --- if we parse this wrongly the \xe9 + # in combination with the tokenized input afterwards looks like a + # valid UTF-8 character. But it isn't. + print $'$\xe9#``' >test_bad_param + (setopt nonomatch + . ./test_bad_param) +127:Invalid parameter name with following tokenized input +?./test_bad_param:1: command not found: $\M-i# + + lines=$'one\tZSH\tthree\nfour\tfive\tsix' + print -X8 -r -- $lines +0:Tab expansion with extra-wide characters +>one ZSH three +>four five six +# This doesn't look aligned in my editor because actually the characters +# aren't quite double width, but the arithmetic is correct. +# It appears just to be an effect of the font. + + () { + emulate -L zsh + setopt errreturn + local cdpath=(.) + mkdir ホ + cd ホ + cd .. + cd ./ホ + cd .. + } +0:cd with special characters + + test_array=( + '[[ \xcc = \xcc ]]' + '[[ \xcc != \xcd ]]' + '[[ \xcc != \ucc ]]' + '[[ \ucc = \ucc ]]' + '[[ \ucc = [\ucc] ]]' + '[[ \xcc != [\ucc] ]]' + # Not clear how useful the following is... + '[[ \xcc = [\xcc] ]]' + ) + for test in $test_array; do + if ! eval ${(g::)test} ; then + print -rl "Test $test failed" >&2 + fi + done +0:Invalid characters in pattern matching + + [[ $'\xe3' == [[:INCOMPLETE:]] ]] || print fail 1 + [[ $'\xe3\x83' == [[:INCOMPLETE:]][[:INVALID:]] ]] || print fail 2 + [[ $'\xe3\x83\x9b' != [[:INCOMPLETE:][:INVALID:]] ]] || print fail 3 + [[ $'\xe3\x83\x9b' = ? ]] || print fail 4 +0:Testing incomplete and invalid multibyte character components + + print -r -- ${(q+):-ホ} + foo='She said "ホ". I said "You can'\''t '\''ホ'\'' me!' + print -r -- ${(q+)foo} +0:${(q+)...} with printable multibyte characters +>ホ +>'She said "ホ". I said "You can'\''t '\''ホ'\'' me!' + +# This will silently succeed if zsh/parameter isn't available + (zmodload zsh/parameter >/dev/null 2>&1 + f() { + : $(:) + "↓" + } + : $functions) +0:Multibyte handling of functions parameter + +# c1=U+0104 (Ą) and c2=U+0120 (Ġ) are chosen so that +# u1 = utf8(c1) = c4 84 < u2 = utf8(c2) = c4 a0 +# metafy(u1) = c4 83 a4 > metafy(u2) = c4 83 80 +# in both UTF-8 and ASCII collations (the latter is used in macOS +# and some versions of BSDs). + local -a names=( $'\u0104' $'\u0120' ) + print -o $names + mkdir -p colltest + cd colltest + touch $names + print ? +0:Sorting of metafied characters +>Ą Ġ +>Ą Ġ + + printf '%q%q\n' 你你 +0:printf %q and quotestring and general metafy / token madness +>你你 + +# This test is kept last as it introduces an additional +# dependency on the system regex library. + if zmodload zsh/regex 2>/dev/null; then + [[ $'\ua0' =~ '^.$' ]] && print OK + [[ $'\ua0' =~ $'^\ua0$' ]] && print OK + [[ $'\ua0'X =~ '^X$' ]] || print OK + else + ZTST_skip="regexp library not found." + fi +0:Ensure no confusion on metafied input to regex module +>OK +>OK +>OK +F:A failure here may indicate the system regex library does not +F:support character sets outside the portable 7-bit range. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D08cmdsubst.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D08cmdsubst.ztst new file mode 100644 index 00000000..36253734 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D08cmdsubst.ztst @@ -0,0 +1,169 @@ +# Tests for command substitution. + +%prep + mkdir cmdsubst.tmp + touch cmdsubst.tmp/file{1,2}.txt + +%test + foo="two words" + print -l `echo $foo bar` +0:Basic `...` substitution +>two +>words +>bar + + foo="two words" + print -l $(echo $foo bar) +0:Basic $(...) substitution +>two +>words +>bar + + foo='intricate buffoonery' + print -l "`echo $foo and licentiousness`" +0:Quoted `...` substitution +>intricate buffoonery and licentiousness + + foo="more words" + print -l "$(echo $foo here)" +0:Quoted $(...) substitution +>more words here + +# we used never to get this one right, but I think it is now... + print -r "`print -r \\\\\\\\`" +0:Stripping of backslasshes in quoted `...` +>\\ + + print -r "$(print -r \\\\\\\\)" +0:Stripping of backslashes in quoted $(...) +>\\\\ + + fnify() { print \"$*\"; } + print `fnify \`fnify understatement\`` +0:Nested `...` +>""understatement"" + + print $(fnify $(fnify overboard)) +0:Nested $(...) +>""overboard"" + + fructify() { print \'$*\'; } + print "`fructify \`fructify indolence\``" +0:Nested quoted `...` +>''indolence'' + + print "$(fructify $(fructify obtuseness))" +0:Nested quoted $(...) +>''obtuseness'' + + gesticulate() { print \!$*\!; } + print $((gesticulate wildly); gesticulate calmly) +0:$(( ... ) ... ) is not arithmetic +>!wildly! !calmly! + + commencify() { print +$*+; } + print "$((commencify output); commencify input)" +0:quoted $(( ... ) .. ) is not arithmetic +>+output+ +>+input+ + + ( + cd cmdsubst.tmp + print first: ${$(print \*)} + print second: ${~$(print \*)} + print third: ${$(print *)} + print fourth: "${~$(print \*)}" + print fifth: ${~"$(print \*)"} + ) +0:mixing $(...) with parameter substitution and globbing +>first: * +>second: file1.txt file2.txt +>third: file1.txt file2.txt +>fourth: * +>fifth: file1.txt file2.txt + + $(exit 0) $(exit 3) || print $? +0:empty command uses exit value of last substitution +>3 + + X=$(exit 2) $(exit 0) || print $? +0:variable assignments processed after other substitutions +>2 + + false + `` +0:Empty command substitution resets status + + false + echo `echo $?` +0:Non-empty command substitution inherits status +>1 + + echo $(( ##\" )) + echo $(echo \") + echo $((echo \"); echo OK) +0:Handling of backslash double quote in parenthesised substitutions +>34 +>" +>" OK + + echo $(case foo in + foo) + echo This test worked. + ;; + bar) + echo This test failed in a rather bizarre way. + ;; + *) + echo This test failed. + ;; + esac) +0:Parsing of command substitution with unmatched parentheses: case, basic +>This test worked. + + echo "$(case bar in + foo) + echo This test spoobed. + ;; + bar) + echo This test plurbled. + ;; + *) + echo This test bzonked. + ;; + esac)" +0:Parsing of command substitution with unmatched parentheses: case with quotes +>This test plurbled. + + echo before $( + echo start; echo unpretentious | + while read line; do + case $line in + u*) + print Word began with u + print and ended with a crunch + ;; + esac + done | sed -e 's/Word/Universe/'; echo end + ) after +0:Parsing of command substitution with ummatched parentheses: with frills +>before start Universe began with u and ended with a crunch end after + + alias foo='echo $(' + eval 'foo echo this just works, OK\?)' +0:backtracking within command string parsing with alias still pending +>this just works, OK? + + ( + set errexit + show_nargs() { print $#; } + print a $() b + print c "$()" d + ) +0:Empty $() is a valid empty substitution. +>a b +>c d + + empty=$() && print "'$empty'" +0:Empty $() is a valid assignment +>'' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D09brace.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D09brace.ztst new file mode 100644 index 00000000..3e667a8d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/D09brace.ztst @@ -0,0 +1,114 @@ +# Tests for brace expansion + +%prep + + foo=(a b c) + arr=(foo bar baz) + +%test + + print X{1,2,{3..6},7,8}Y +0:Basic brace expansion +>X1Y X2Y X3Y X4Y X5Y X6Y X7Y X8Y + + print ${foo}{one,two,three}$arr +0:Brace expansion with arrays, no RC_EXPAND_PARAM +>a b conefoo ctwofoo cthreefoo bar baz + + print ${^foo}{one,two,three}$arr +0:Brace expansion with arrays, with RC_EXPAND_PARAM (1) +>aonefoo atwofoo athreefoo bonefoo btwofoo bthreefoo conefoo ctwofoo cthreefoo bar baz + + print ${foo}{one,two,three}$^arr +0:Brace expansion with arrays, with RC_EXPAND_PARAM (2) +>a b conefoo ctwofoo cthreefoo conebar ctwobar cthreebar conebaz ctwobaz cthreebaz + + print ${^foo}{one,two,three}$^arr +0:Brace expansion with arrays, with RC_EXPAND_PARAM (3) +>aonefoo atwofoo athreefoo aonebar atwobar athreebar aonebaz atwobaz athreebaz bonefoo btwofoo bthreefoo bonebar btwobar bthreebar bonebaz btwobaz bthreebaz conefoo ctwofoo cthreefoo conebar ctwobar cthreebar conebaz ctwobaz cthreebaz + + print X{01..4}Y +0:Numeric range expansion, padding (1) +>X01Y X02Y X03Y X04Y + + print X{1..04}Y +0:Numeric range expansion, padding (2) +>X01Y X02Y X03Y X04Y + + print X{7..12}Y +0:Numeric range expansion, padding (or not) (3) +>X7Y X8Y X9Y X10Y X11Y X12Y + + print X{07..12}Y +0:Numeric range expansion, padding (4) +>X07Y X08Y X09Y X10Y X11Y X12Y + + print X{7..012}Y +0:Numeric range expansion, padding (5) +>X007Y X008Y X009Y X010Y X011Y X012Y + + print X{4..1}Y +0:Numeric range expansion, decreasing +>X4Y X3Y X2Y X1Y + + print X{1..4}{1..4}Y +0:Numeric range expansion, combined braces +>X11Y X12Y X13Y X14Y X21Y X22Y X23Y X24Y X31Y X32Y X33Y X34Y X41Y X42Y X43Y X44Y + + print X{-4..4}Y +0:Numeric range expansion, negative numbers (1) +>X-4Y X-3Y X-2Y X-1Y X0Y X1Y X2Y X3Y X4Y + + print X{4..-4}Y +0:Numeric range expansion, negative numbers (2) +>X4Y X3Y X2Y X1Y X0Y X-1Y X-2Y X-3Y X-4Y + + print X{004..-4..2}Y +0:Numeric range expansion, stepping and padding (1) +>X004Y X002Y X000Y X-02Y X-04Y + + print X{4..-4..02}Y +0:Numeric range expansion, stepping and padding (1) +>X04Y X02Y X00Y X-2Y X-4Y + + print X{1..32..3}Y +0:Numeric range expansion, step alignment (1) +>X1Y X4Y X7Y X10Y X13Y X16Y X19Y X22Y X25Y X28Y X31Y + + print X{1..32..-3}Y +0:Numeric range expansion, step alignment (2) +>X31Y X28Y X25Y X22Y X19Y X16Y X13Y X10Y X7Y X4Y X1Y + + print X{32..1..3}Y +0:Numeric range expansion, step alignment (3) +>X32Y X29Y X26Y X23Y X20Y X17Y X14Y X11Y X8Y X5Y X2Y + + print X{32..1..-3}Y +0:Numeric range expansion, step alignment (4) +>X2Y X5Y X8Y X11Y X14Y X17Y X20Y X23Y X26Y X29Y X32Y + + setopt brace_ccl + print X{za-q521}Y + unsetopt brace_ccl +0:BRACE_CCL on +>X1Y X2Y X5Y XaY XbY XcY XdY XeY XfY XgY XhY XiY XjY XkY XlY XmY XnY XoY XpY XqY XzY + + print X{za-q521}Y +0:BRACE_CCL off +>X{za-q521}Y + + print -r hey{a..j}there +0:{char..char} ranges, simple case +>heyathere heybthere heycthere heydthere heyethere heyfthere heygthere heyhthere heyithere heyjthere + + print -r gosh{1,{Z..a},2}cripes +0:{char..char} ranges, ASCII ordering +>gosh1cripes goshZcripes gosh[cripes gosh\cripes gosh]cripes gosh^cripes gosh_cripes gosh`cripes goshacripes gosh2cripes + + print -r crumbs{y..p}ooh +0:{char..char} ranges, reverse +>crumbsyooh crumbsxooh crumbswooh crumbsvooh crumbsuooh crumbstooh crumbssooh crumbsrooh crumbsqooh crumbspooh + + print -r left{[..]}right +0:{char..char} ranges with tokenized characters +>left[right left\right left]right diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/E01options.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/E01options.ztst new file mode 100644 index 00000000..2bd4fdb1 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/E01options.ztst @@ -0,0 +1,1313 @@ +# Test various shell options. +# Interactive options not tested here: +# ALWAYS_LAST_PROMPT +# ALWAYS_TO_END +# APPEND_HISTORY (history not maintained) +# AUTO_LIST +# AUTO_MENU +# AUTO_NAME_DIRS (named directory table not maintained) +# AUTO_PARAM_KEYS +# AUTO_PARAM_SLASH +# AUTO_REMOVE_SLASH +# AUTO_RESUME +# BANG_HIST +# BASH_AUTO_LIST +# BEEP (!) +# BG_NICE +# CHECK_JOBS +# COMPLETE_ALIASES +# COMPLETE_IN_WORD +# CORRECT +# CORRECT_ALL +# CSH_JUNKIE_HISTORY +# DVORAK +# EXTENDED_HISTORY +# FLOW_CONTROL +# GLOB_COMPLETE +# HIST_ALLOW_CLOBBER +# HIST_BEEP +# HIST_EXPIRE_DUPS_FIRST +# HIST_FIND_NO_DUPS +# HIST_IGNORE_ALL_DUPS +# HIST_IGNORE_DUPS (-h) +# HIST_IGNORE_SPACE (-g) +# HIST_NO_FUNCTIONS +# HIST_NO_STORE +# HIST_REDUCE_BLANKS +# HIST_SAVE_NO_DUPS +# HIST_VERIFY +# HUP +# IGNORE_EOF +# INC_APPEND_HISTORY +# INTERACTIVE +# INTERACTIVE_COMMENTS +# LIST_AMBIGUOUS +# LIST_BEEP +# LIST_PACKED +# LIST_ROWS_FIRST +# LIST_TYPES +# LOGIN +# LONG_LIST_JOBS +# MAIL_WARNING +# MENU_COMPLETE +# MONITOR +# NOTIFY +# OVERSTRIKE +# PRINT_EIGHT_BIT +# PROMPT_CR +# PUSHD_SILENT +# REC_EXACT +# RM_STAR_SILENT +# RM_STAR_WAIT +# SHARE_HISTORY +# SINGLE_LINE_ZLE +# SUN_KEYBOARD_HACK +# ZLE +# The following require SHINSTDIN and are not (yet) tested: +# AUTO_CD +# SHINSTDIN +# +# Other difficult things I haven't done: +# GLOBAL_RCS (uses fixed files outside build area) +# HASH_CMDS ) +# HASH_DIRS ) fairly seriously internal, hard to test at all +# HASH_LIST_ALL ) +# PRINT_EXIT_STATUS haven't worked out what this does yet, although +# Bart suggested a fix. +# PRIVILEGED (similar to GLOBAL_RCS) +# RCS ( " " " " ) +# SH_OPTION_LETTERS even I found this too dull to set up a test for +# SINGLE_COMMAND kills shell +# VERBOSE hard because done on input (c.f. SHINSTDIN). + +%prep + mkdir options.tmp && cd options.tmp + + mkdir tmpcd homedir + + touch tmpfile1 tmpfile2 + + mydir=$PWD + mydirt=`print -P %~` + mydirhome=`export HOME=$mydir/homedir; print -P %~` + catpath=$(which cat) + lspath==ls + +%test + + alias echo='print foo' + unsetopt aliases + # use eval else aliases are all parsed at start + eval echo bar + setopt aliases + eval echo bar + unalias echo +0:ALIASES option +>bar +>foo bar + + setopt allexport + testpm1=exported + unsetopt allexport + testpm2=unexported + print ${(t)testpm1} + print ${(t)testpm2} +0:ALL_EXPORT option +>scalar-export +>scalar + + # Count the number of directories on the stack. Don't care what they are. + dircount() { dirs -v | tail -1 | awk '{ print $1 + 1}'; } + unsetopt autopushd + cd tmpcd + dircount + cd .. + setopt autopushd + cd tmpcd + dircount + unsetopt autopushd + popd >/dev/null +0:AUTO_PUSHD option +>1 +>2 + + unsetopt badpattern + print [a + setopt badpattern + print [b +1:BAD_PATTERN option +>[a +?(eval):4: bad pattern: [b + + unsetopt bareglobqual nomatch + print *(.) + setopt bareglobqual nomatch + print *(.) +0:BARE_GLOB_QUAL option +>*(.) +>tmpfile1 tmpfile2 + + setopt braceccl + print {abcd} + unsetopt braceccl + print {abcd} +0:BRACE_CCL option +>a b c d +>{abcd} + +# Don't use NUL as a field separator in the following. + setopt braceccl + print {$'\0'-$'\5'} | IFS=' ' read -A chars + for c in $chars; do print $(( #c )); done + unsetopt braceccl +0:BRACE_CCL option starting from NUL +>0 +>1 +>2 +>3 +>4 +>5 + + setopt bsdecho + echo "histon\nimpington" + echo -e "girton\ncottenham" + unsetopt bsdecho + echo "newnham\ncomberton" +0:BSD_ECHO option +>histon\nimpington +>girton +>cottenham +>newnham +>comberton + + unsetopt c_bases + print $(( [#16]15 )) + print $(( [#8]9 )) + setopt c_bases + print $(( [#16]31 )) + print $(( [#8]17 )) + setopt octal_zeroes + print $(( [#8]19 )) + unsetopt c_bases octal_zeroes +0:C_BASES option +>16#F +>8#11 +>0x1F +>8#21 +>023 + + setopt cdablevars + # only absolute paths are eligible for ~-expansion + cdablevar1=tmpcd + (cd cdablevar1) + cdablevar2=$PWD/tmpcd + cd cdablevar2 + cd .. + print back in ${PWD:t} + unsetopt cdablevars + cd cdablevar2 +1q:CDABLE_VARS option +>back in options.tmp +?(eval):cd:4: no such file or directory: cdablevar1 +?(eval):cd:10: no such file or directory: cdablevar2 + +# CHASE_DOTS should go with CHASE_LINKS in B01cd.ztst +# which saves me having to write it here. + + setopt noclobber + rm -f foo1 bar1 rod1 + echo waterbeach >foo1 + (echo landbeach >foo1) + cat foo1 + (echo lode >>bar1) + [[ -f bar1 ]] && print That shouldn\'t be there. + echo denny >rod1 + echo wicken >>rod1 + cat rod1 + unsetopt noclobber + rm -f foo2 bar2 rod2 + echo ely >foo2 + echo march >foo2 + cat foo2 + echo wimpole >>bar2 + cat bar2 + echo royston >rod2 + echo foxton >>rod2 + cat rod2 + rm -f foo* bar* rod* +0:CLOBBER option +>waterbeach +>denny +>wicken +>march +>wimpole +>royston +>foxton +?(eval):4: file exists: foo1 +?(eval):6: no such file or directory: bar1 + + setopt cshjunkieloops + eval 'for f in swaffham bulbeck; print $f; end' + print next one should fail >&2 + unsetopt cshjunkieloops + eval 'for f in chesterton arbury; print $f; end' +1:CSH_JUNKIE_LOOPS option (for loop) +>swaffham +>bulbeck +?next one should fail +?(eval):1: parse error near `end' + +# ` emacs deconfusion + + setopt cshjunkiequotes + print this should cause an error >&2 + eval "print 'line one + line two'" + print this should not >&2 + eval "print 'line three\\ + line four'" + unsetopt cshjunkiequotes +0:CSH_JUNKIE_QUOTES option +>line three +> line four +?this should cause an error +?(eval):1: unmatched ' +?this should not + +# ' emacs deconfusion + + nullcmd() { print '$NULLCMD run'; } + readnullcmd() { print 'Running $READNULLCMD'; cat; } + NULLCMD=nullcmd + READNULLCMD=readnullcmd + setopt cshnullcmd + rm -f foo + print "This should fail" >&2 + (>foo) + print "This should succeed" >&2 + print "These are the contents of foo" >foo + cat foo + print "This should also fail" >&2 + (foo + These are the contents of foo +>Running $READNULLCMD +>$NULLCMD run +?This should fail +?(eval):8: redirection with no command +?This should succeed +?This should also fail +?(eval):13: redirection with no command + +# nomatch should be overridden by cshnullglob + setopt nomatch cshnullglob + print tmp* nothing* blah + print -n 'hoping for no match: ' >&2 + (print nothing* blah) + print >&2 + unsetopt cshnullglob nomatch + print tmp* nothing* blah + print nothing* blah +0:CSH_NULL_GLOB option +>tmpcd tmpfile1 tmpfile2 blah +>tmpcd tmpfile1 tmpfile2 nothing* blah +>nothing* blah +?hoping for no match: (eval):4: no match +? + +# The trick is to avoid =cat being expanded in the output while $catpath is. + setopt NO_equals + print -n trick; print =cat + setopt equals + print -n trick; print =cat +0q:EQUALS option +>trick=cat +>trick$catpath + +# explanation of expected TRAPZERR output: from false and from +# testfn() with ERR_EXIT on (hmm, should we really get a second one from +# the function exiting?), then from the false only with ERR_EXIT off. + TRAPZERR() { print ZERR trapped; } + testfn() { setopt localoptions $2; print $1 before; false; print $1 after; } + (testfn on errexit) + testfn off + unfunction TRAPZERR testfn +0:ERR_EXIT option +>on before +>ZERR trapped +>ZERR trapped +>off before +>ZERR trapped +>off after + + (print before; setopt noexec; print after) +0:NO_EXEC option +>before + + (setopt noexec + typeset -A hash + hash['this is a string']) +0:NO_EXEC option should not attempt to parse subscripts + + (setopt noexec nomatch + echo *NonExistentFile*) +0:NO_EXEC option should not do globbing + + (setopt noexec + echo ${unset_var?Not an error}) +0:NO_EXEC should not test for unset variables + + (setopt noexec + : ${${string%[aeiou]*}/(#m)?(#e)/${(U)MATCH}} Rule 1 + : ${array[4,5][1][2,3]} Rule 2 + : ${${(P)foo[1,6]}[1,3]} Rule 3 + : "${${(@)array}[1,2]}" Rule 5 + : "${(@)${(@)array}[1,2]#?}" Rule 6 + : ${(el.20..X.)${bar}} Rule 11 success case) +0:NO_EXEC handles parameter substitution examples + + (setopt noexec + : ${(el.20..X.)$bar} Rule 11 failure case) +1:NO_EXEC does recognize bad substitution syntax +*?* bad substitution + + setopt NO_eval_lineno + eval 'print $LINENO' + setopt eval_lineno + eval 'print $LINENO' +0:EVAL_LINENO option +>2 +>1 + + # The EXTENDED_GLOB test doesn't test globbing fully --- it just tests + # that certain patterns are treated literally with the option off + # and as patterns with the option on. + testfn() { print -n "$1 $2 $3 "; if [[ $1 = ${~2} ]]; + then print yes; else print no; fi; } + tests=('a#' '?~b' '^aa') + strings=('a' 'aa' 'b' 'a#' '?~b' '^aa') + for opt in noextendedglob extendedglob; do + setopt $opt + for test in $tests; do + for string in $strings; do + testfn $string $test $opt + done + done + done +0:EXTENDED_GLOB option +>a a# noextendedglob no +>aa a# noextendedglob no +>b a# noextendedglob no +>a# a# noextendedglob yes +>?~b a# noextendedglob no +>^aa a# noextendedglob no +>a ?~b noextendedglob no +>aa ?~b noextendedglob no +>b ?~b noextendedglob no +>a# ?~b noextendedglob no +>?~b ?~b noextendedglob yes +>^aa ?~b noextendedglob no +>a ^aa noextendedglob no +>aa ^aa noextendedglob no +>b ^aa noextendedglob no +>a# ^aa noextendedglob no +>?~b ^aa noextendedglob no +>^aa ^aa noextendedglob yes +>a a# extendedglob yes +>aa a# extendedglob yes +>b a# extendedglob no +>a# a# extendedglob no +>?~b a# extendedglob no +>^aa a# extendedglob no +>a ?~b extendedglob yes +>aa ?~b extendedglob no +>b ?~b extendedglob no +>a# ?~b extendedglob no +>?~b ?~b extendedglob no +>^aa ?~b extendedglob no +>a ^aa extendedglob yes +>aa ^aa extendedglob no +>b ^aa extendedglob yes +>a# ^aa extendedglob yes +>?~b ^aa extendedglob yes +>^aa ^aa extendedglob yes + + foo() { print My name is $0; } + unsetopt functionargzero + foo + setopt functionargzero + foo + unfunction foo +0:FUNCTION_ARGZERO option +>My name is (anon) +>My name is foo + + setopt _NO_glob_ + print tmp* + set -o glob + print tmp* +0:GLOB option +>tmp* +>tmpcd tmpfile1 tmpfile2 + + showit() { local v; + for v in first second third; do + eval print \$$v \$\{\(t\)$v\} + done; + } + setit() { typeset -x first=inside1; + typeset +g -x second=inside2; + typeset -g -x third=inside3; + showit; + } + first=outside1 second=outside2 third=outside3 + unsetopt globalexport + setit + showit + setopt globalexport + setit + showit + unfunction setit showit +0:GLOBAL_EXPORT option +>inside1 scalar-local-export +>inside2 scalar-local-export +>inside3 scalar-export +>outside1 scalar +>outside2 scalar +>inside3 scalar-export +>inside1 scalar-export +>inside2 scalar-local-export +>inside3 scalar-export +>inside1 scalar-export +>outside2 scalar +>inside3 scalar-export + +# GLOB_ASSIGN is tested in A06assign.ztst. + + mkdir onlysomefiles + touch onlysomefiles/.thisfile onlysomefiles/thatfile + setopt globdots + print onlysomefiles/* + unsetopt globdots + print onlysomefiles/* + rm -rf onlysomefiles +0:GLOB_DOTS option +>onlysomefiles/.thisfile onlysomefiles/thatfile +>onlysomefiles/thatfile + + # we've tested this enough times already... + # could add some stuff for other sorts of expansion + foo='tmp*' + setopt globsubst + print ${foo} + unsetopt globsubst + print ${foo} +0:GLOB_SUBST option +>tmpcd tmpfile1 tmpfile2 +>tmp* + + setopt histsubstpattern + print *(:s/t??/TING/) + foo=(tmp*) + print ${foo:s/??p/THUMP/} + foo=(one.c two.c three.c) + print ${foo:s/#%(#b)t(*).c/T${match[1]}.X/} + print *(#q:s/#(#b)tmp(*e)/'scrunchy${match[1]}'/) + unsetopt histsubstpattern +0:HIST_SUBST_PATTERN option +>TINGcd TINGfile1 TINGfile2 homedir +>THUMPcd THUMPfile1 THUMPfile2 +>one.c Two.X Three.X +>homedir scrunchyfile1 scrunchyfile2 tmpcd + + setopt ignorebraces + echo X{a,b}Y + unsetopt ignorebraces + echo X{a,b}Y +0:IGNORE_BRACES option +>X{a,b}Y +>XaY XbY + + setopt ksh_arrays + array=(one two three) + print $array $array[2] + print ${array[0]} ${array[1]} ${array[2]} ${array[3]} + unsetopt ksh_arrays + print $array $array[2] + print ${array[0]} ${array[1]} ${array[2]} ${array[3]} + unset array +0:KSH_ARRAYS option +>one one[2] +>one two three +>one two three two +>one two three + + fpath=(.) + echo >foo 'echo foo loaded; foo() { echo foo run; }' + echo >bar 'bar() { echo bar run; }' + setopt kshautoload + autoload foo bar + foo + bar + unfunction foo bar + unsetopt kshautoload + autoload foo bar + foo + bar +0:KSH_AUTOLOAD option +>foo loaded +>foo run +>bar run +>foo loaded +>bar run + +# ksh_glob is tested by the glob tests. + + setopt kshoptionprint globassign + print set + setopt | grep kshoptionprint + setopt | grep globassign + unsetopt kshoptionprint + print unset + setopt | grep kshoptionprint + setopt | grep globassign + unsetopt globassign +0:KSH_OPTION_PRINT option +>set +>kshoptionprint on +>globassign on +>unset +>globassign + + # This test is now somewhat artificial as + # KSH_TYPESET only applies to the builtin + # interface. Tests to the more standard + # reserved word interface appear elsewhere. + ( + # reserved words are handled during parsing, + # hence eval... + disable -r typeset + eval ' + setopt kshtypeset + ktvars=(ktv1 ktv2) + typeset ktfoo=`echo arg1 arg2` $ktvars + print $+ktv1 $+ktv2 $+ktv3 + print $ktfoo + unsetopt kshtypeset + typeset noktfoo=`echo noktarg1 noktarg2` + print $noktfoo + print $+noktarg1 $+noktarg2 + unset ktfoo ktv1 ktv2 noktfoo noktarg2 + ' + ) +0:KSH_TYPESET option +>1 1 0 +>arg1 arg2 +>noktarg1 +>0 1 + + showopt() { setopt | egrep 'localoptions|ksharrays'; } + f1() { setopt localoptions ksharrays; showopt } + f2() { setopt ksharrays; showopt } + setopt kshoptionprint + showopt + f1 + showopt + f2 + showopt + unsetopt ksh_arrays +0:LOCAL_OPTIONS option +>ksharrays off +>localoptions off +>ksharrays on +>localoptions on +>ksharrays off +>localoptions off +>ksharrays on +>localoptions off +>ksharrays on +>localoptions off + +# LOCAL_TRAPS was tested in C03traps (phew). + + fn() { + local HOME=/any/old/name + print -l var=~ 'anything goes/here'=~ split=`echo maybe not`; + } + setopt magicequalsubst + fn + setopt kshtypeset + fn + unsetopt magicequalsubst kshtypeset + fn +0:MAGIC_EQUAL_SUBST option +>var=/any/old/name +>anything goes/here=/any/old/name +>split=maybe +>not +>var=/any/old/name +>anything goes/here=/any/old/name +>split=maybe not +>var=~ +>anything goes/here=~ +>split=maybe +>not + + setopt MARK_DIRS + print tmp* + unsetopt MARK_DIRS + print tmp* +0:MARK_DIRS option +>tmpcd/ tmpfile1 tmpfile2 +>tmpcd tmpfile1 tmpfile2 + +# maybe should be in A04redirect + print "This is in1" >in1 + print "This is in2" >in2 + unsetopt multios + print Test message >foo1 >foo2 + print foo1: $(foo1 >foo2 + sleep 1 # damn, race in multios + print foo1: $(foo1: +>foo2: Test message +>This is in2 +>foo1: Test message +>foo2: Test message +>This is in1 +>This is in2 + +# This is trickier than it looks. There's a hack at the end of +# execcmd() to catch the multio processes attached to the +# subshell, which otherwise sort of get lost in the general turmoil. +# Without that, the multios aren't synchronous with the subshell +# or the main shell starting the "cat", so the output files appear +# empty. + setopt multios + ( echo hello ) >multio_out1 >multio_out2 && cat multio_out* +0:Multios attached to a subshell +>hello +>hello + +# This tests for another race in multios. + print -u $ZTST_fd 'This test hangs the shell when it fails...' + setopt multios + echo These are the contents of the file >multio_race.out + multio_race_fn() { cat; } + multio_race_fn <$(echo multio_race.out multio_race.out) +0:Fix for race with input multios +>These are the contents of the file +>These are the contents of the file + +# tried this with other things, but not on its own, so much. + unsetopt nomatch + print with nonomatch: flooble* + setopt nomatch + print with nomatch flooble* +1:NOMATCH option +>with nonomatch: flooble* +?(eval):4: no matches found: flooble* + +# NULL_GLOB should override NONOMATCH... + setopt nullglob nomatch + print frooble* tmp* + unsetopt nullglob nomatch + print frooble* tmp* +0:NULL_GLOB option +>tmpcd tmpfile1 tmpfile2 +>frooble* tmpcd tmpfile1 tmpfile2 + + touch ngs1.txt ngs2.txt ngs10.txt ngs20.txt ngs100.txt ngs200.txt + setopt numericglobsort + print -l ngs* + unsetopt numericglobsort + print -l ngs* +0:NUMERIC_GLOB_SORT option +>ngs1.txt +>ngs2.txt +>ngs10.txt +>ngs20.txt +>ngs100.txt +>ngs200.txt +>ngs1.txt +>ngs10.txt +>ngs100.txt +>ngs2.txt +>ngs20.txt +>ngs200.txt + + typeset -i 10 oznum + setopt octalzeroes + (( oznum = 012 + 013 )) + print $oznum + unsetopt octalzeroes + (( oznum = 012 + 013 )) + print $oznum + unset oznum +0:OCTAL_ZEROES options +>21 +>25 + + typeset -a oldpath + oldpath=($path) + mkdir pdt_topdir pathtestdir pdt_topdir/pathtestdir + print "#!/bin/sh\necho File in upper dir" >pathtestdir/findme + print "#!/bin/sh\necho File in lower dir" >pdt_topdir/pathtestdir/findme + chmod u+x pathtestdir/findme pdt_topdir/pathtestdir/findme + pathtestdir/findme + rm -f pathtestdir/findme + setopt pathdirs + path=($PWD $PWD/pdt_topdir) + pathtestdir/findme + print unsetting option... + unsetopt pathdirs + pathtestdir/findme + path=($oldpath) + unset oldpath + rm -rf pdt_topdir pathtestdir +0:PATH_DIRS option +>File in upper dir +>File in lower dir +>unsetting option... +?(eval):14: no such file or directory: pathtestdir/findme + + (setopt pathdirs; path+=( /usr/bin ); type ./env) +1:whence honours PATH_DIRS option +>./env not found + + setopt posixbuiltins + PATH= command -v print + PATH= command -V print + PATH= command print foo + unsetopt posixbuiltins + print unsetting... + PATH= command -V print + PATH= command print foo +127:POSIX_BUILTINS option +>print +>print is a shell builtin +>foo +>unsetting... +>print is a shell builtin +?(eval):8: command not found: print + + # With non-special command: original value restored + # With special builtin: new value kept + # With special builtin preceeded by "command": original value restored. + (setopt posixbuiltins + FOO=val0 + FOO=val1 true; echo $FOO + FOO=val2 times 1>/dev/null 2>&1; echo $FOO + FOO=val3 command times 1>/dev/null 2>&1; echo $FOO) +0:POSIX_BUILTINS and restoring variables +>val0 +>val2 +>val2 + +# PRINTEXITVALUE only works if shell input is coming from standard input. +# Goodness only knows why. + $ZTST_testdir/../Src/zsh -f <<<' + setopt printexitvalue + func() { + false + } + func + ' +1:PRINT_EXIT_VALUE option +?zsh: exit 1 + + $ZTST_testdir/../Src/zsh -f <<<' + setopt printexitvalue + () { false; } + ' +1:PRINT_EXIT_VALUE option for anonymous function +?zsh: exit 1 + + setopt promptbang + print -P ! + setopt nopromptbang + print -P ! +0:PROMPT_BANG option +>0 +>! + + unsetopt promptpercent + print -P '%/' + setopt promptpercent + print -P '%/' +0q:PROMPT_PERCENT option +>%/ +>$mydir + + setopt promptsubst + print -P '`echo waaah`' + unsetopt promptsubst + print -P '`echo waaah`' +0:PROMPT_SUBST option +>waaah +>`echo waaah` + + dirs + pushd $mydir/tmpcd + dirs + pushd $mydir/tmpcd + dirs + setopt pushdignoredups + pushd $mydir/tmpcd + dirs + unsetopt pushdignoredups + popd >/dev/null + popd >/dev/null +0q:PUSHD_IGNOREDUPS option +>$mydirt +>$mydirt/tmpcd $mydirt +>$mydirt/tmpcd $mydirt/tmpcd $mydirt +>$mydirt/tmpcd $mydirt/tmpcd $mydirt + + mkdir newcd + cd $mydir + pushd $mydir/tmpcd + pushd $mydir/newcd + dirs + pushd -0 + dirs + setopt pushdminus pushdsilent + pushd -0 + dirs + unsetopt pushdminus + popd >/dev/null + popd >/dev/null + cd $mydir +0q:PUSHD_MINUS option +>$mydirt/newcd $mydirt/tmpcd $mydirt +>$mydirt $mydirt/newcd $mydirt/tmpcd +>$mydirt $mydirt/newcd $mydirt/tmpcd + +# Do you have any idea how dull this is? + + (export HOME=$mydir/homedir + pushd $mydir/tmpcd + pushd + dirs + setopt pushdtohome + pushd + dirs + unsetopt pushdtohome + popd + pushd + popd + dirs) +0q:PUSHD_TO_HOME option +>$mydirhome $mydirhome/tmpcd +>~ $mydirhome $mydirhome/tmpcd +>$mydirhome + + array=(one two three four) + setopt rcexpandparam + print aa${array}bb + unsetopt rcexpandparam + print aa${array}bb +0:RC_EXPAND_PARAM option +>aaonebb aatwobb aathreebb aafourbb +>aaone two three fourbb + + setopt rcquotes + # careful, this is done when parsing a complete block + eval "print 'one''quoted''expression'" + unsetopt rcquotes + eval "print 'another''quoted''expression'" +0:RC_QUOTES option +>one'quoted'expression +>anotherquotedexpression + +# too lazy to test jobs -Z and ARGV0. + (setopt restricted; cd /) + (setopt restricted; PATH=/bin:/usr/bin) + (setopt restricted; /bin/ls) + (setopt restricted; hash ls=/bin/ls) + (setopt restricted; print ha >outputfile) + (setopt restricted; exec ls) + (setopt restricted; unsetopt restricted) + : +0:RESTRICTED option +?(eval):cd:1: restricted +?(eval):2: PATH: restricted +?(eval):3: /bin/ls: restricted +?(eval):hash:4: restricted: /bin/ls +?(eval):5: writing redirection not allowed in restricted mode +?(eval):exec:6: ls: restricted +?(eval):unsetopt:7: can't change option: restricted + +# ' emacs deconfusion + + fn() { + print =ls ={ls,} + local foo='=ls' + print ${~foo} + } + setopt shfileexpansion + fn + unsetopt shfileexpansion + fn +0q:SH_FILE_EXPANSION option +>$lspath =ls = +>=ls +>$lspath $lspath = +>$lspath + + testpat() { + if [[ $1 = ${~2} ]]; then print $1 $2 yes; else print $1 $2 no; fi + } + print option on + setopt shglob + repeat 2; do + for str in 'a(b|c)' ab; do + testpat $str 'a(b|c)' + done + for str in 'a<1-10>' a9; do + testpat $str 'a<1-10>' + done + [[ ! -o shglob ]] && break + print option off + unsetopt shglob + done +0:SH_GLOB option +>option on +>a(b|c) a(b|c) yes +>ab a(b|c) no +>a<1-10> a<1-10> yes +>a9 a<1-10> no +>option off +>a(b|c) a(b|c) no +>ab a(b|c) yes +>a<1-10> a<1-10> no +>a9 a<1-10> yes + + print this is bar >bar + fn() { + local NULLCMD=cat READNULLCMD=cat + { echo hello | >foo } 2>/dev/null + cat foo + option set +>option unset +>hello +>this is bar + + fn() { + eval 'for f in foo bar; print $f' + eval 'for f (word1 word2) print $f' + eval 'repeat 3 print nonsense' + } + unsetopt shortloops + print option unset + fn + setopt shortloops + print option set + fn +0:SHORT_LOOPS option +>option unset +>option set +>foo +>bar +>word1 +>word2 +>nonsense +>nonsense +>nonsense +?(eval):1: parse error near `print' +?(eval):1: parse error near `print' +?(eval):1: parse error near `print' + + fn() { print -l $*; } + setopt shwordsplit + print option set + repeat 2; do + foo='two words' + fn $foo + fn "${=foo}" + [[ ! -o shwordsplit ]] && break + unsetopt shwordsplit + print option unset + done +0:SH_WORD_SPLIT option +>option set +>two +>words +>two +>words +>option unset +>two words +>two +>words + + fn() { unset foo; print value is $foo; } + setopt nounset + print option unset unset by setting nounset + eval fn + print option unset reset + setopt unset + fn +0:UNSET option +>option unset unset by setting nounset +>option unset reset +>value is +?fn: foo: parameter not set + + fn1() { unset foo; print value 1 is ${foo#bar}; } + fn2() { unset foo; print value 2 is ${foo%bar}; } + fn3() { unset foo; print value 3 is ${foo/bar}; } + setopt nounset + print option unset unset by setting nounset + eval fn1 + eval fn2 + eval fn3 + print option unset reset + setopt unset + fn1 + fn2 + fn3 +0:UNSET option with operators +>option unset unset by setting nounset +>option unset reset +>value 1 is +>value 2 is +>value 3 is +?fn1: foo: parameter not set +?fn2: foo: parameter not set +?fn3: foo: parameter not set + + fn() { + emulate -L zsh + setopt warncreateglobal + foo1=bar1 + unset foo1 + foo1=bar2 + local foo2=bar3 + unset foo2 + foo2=bar4 + typeset -g foo3 + foo3=bar5 + fn2() { + foo3=bar6 + } + foo4=bar7 =true + (( foo5=8 )) + integer foo6=9 + (( foo6=10 )) + } + # don't pollute the test environment with the variables... + (fn) +0:WARN_CREATE_GLOBAL option +?fn:3: scalar parameter foo1 created globally in function fn +?fn:5: scalar parameter foo1 created globally in function fn +?fn:15: numeric parameter foo5 created globally in function fn + + fn() { + emulate -L zsh + setopt warncreateglobal + TZ=UTC date >&/dev/null + local um=$(TZ=UTC date 2>/dev/null) + } + fn +0:WARN_CREATE_GLOBAL negative cases + + ( + foo1=global1 foo2=global2 foo3=global3 foo4=global4 + integer foo5=5 + # skip foo6, defined in fn_wnv + foo7=(one two) + fn_wnv() { + # warns + foo1=bar1 + # doesn't warn + local foo2=bar3 + unset foo2 + # still doesn't warn + foo2=bar4 + # doesn't warn + typeset -g foo3=bar5 + # warns + foo3=bar6 + fn2() { + # warns if global option, not attribute + foo3=bar6 + } + fn2 + # doesn't warn + foo4=bar7 =true + # warns + (( foo5=8 )) + integer foo6=9 + # doesn't warn + (( foo6=10 )) + foo7[3]=three + foo7[4]=(four) + } + print option off >&2 + fn_wnv + print option on >&2 + setopt warnnestedvar + fn_wnv + unsetopt warnnestedvar + print function attribute on >&2 + functions -W fn_wnv + fn_wnv + print all off again >&2 + functions +W fn_wnv + fn_wnv + ) +0:WARN_NESTED_VAR option +?option off +?option on +?fn_wnv:2: scalar parameter foo1 set in enclosing scope in function fn_wnv +?fn_wnv:11: scalar parameter foo3 set in enclosing scope in function fn_wnv +?fn2:2: scalar parameter foo3 set in enclosing scope in function fn2 +?fn_wnv:20: numeric parameter foo5 set in enclosing scope in function fn_wnv +?function attribute on +?fn_wnv:2: scalar parameter foo1 set in enclosing scope in function fn_wnv +?fn_wnv:11: scalar parameter foo3 set in enclosing scope in function fn_wnv +?fn_wnv:20: numeric parameter foo5 set in enclosing scope in function fn_wnv +?all off again + + + ( + setopt warnnestedvar + () { + typeset -A a + : ${a[hello world]::=foo} + print ${(t)a} + key="hello world" + print $a[$key] + } + ) +0:No false positive on parameter used with subscripted assignment +>association-local +>foo + + ( + setopt warnnestedvar + () { + local var=(one two) + () { var=three; } + print $var + } + ) +0:Warn when changing type of nested variable: array to scalar. +?(anon): scalar parameter var set in enclosing scope in function (anon) +>three + + ( + setopt warnnestedvar + () { + local var=three + () { var=(one two); } + print $var + } + ) +0:Warn when changing type of nested variable: scalar to array. +?(anon): array parameter var set in enclosing scope in function (anon) +>one two + +# This really just tests if XTRACE is egregiously broken. +# To test it properly would need a full set of its own. + fn() { print message; } + PS4='+%N:%i> ' + setopt xtrace + fn + unsetopt xtrace + fn +0:XTRACE option +>message +>message +?+(eval):4> fn +?+fn:0> print message +?+(eval):5> unsetopt xtrace + + setopt ignoreclosebraces + eval "icb_test() { echo this is OK; }" + icb_test + icb_args() { print $#; } + eval "icb_args { this, is, ok, too }" +0:IGNORE_CLOSE_BRACES option +>this is OK +>6 + + (setopt pipefail + true | true | true + print $? + true | false | true + print $? + exit 2 | false | true + print $? + false | exit 2 | true + print $?) +0:PIPE_FAIL option +>0 +>1 +>1 +>2 + + for (( i = 0; i < 10; i++ )); do + () { + print $i + break + } + done +0:NO_LOCAL_LOOPS +>0 + + () { + emulate -L zsh + setopt localloops + for (( i = 0; i < 10; i++ )); do + () { + setopt nolocalloops # ignored in parent + print $i + break + } + done + } +0:LOCAL_LOOPS +>0 +>1 +>2 +>3 +>4 +>5 +>6 +>7 +>8 +>9 +?(anon):4: `break' active at end of function scope +?(anon):4: `break' active at end of function scope +?(anon):4: `break' active at end of function scope +?(anon):4: `break' active at end of function scope +?(anon):4: `break' active at end of function scope +?(anon):4: `break' active at end of function scope +?(anon):4: `break' active at end of function scope +?(anon):4: `break' active at end of function scope +?(anon):4: `break' active at end of function scope +?(anon):4: `break' active at end of function scope diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/E02xtrace.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/E02xtrace.ztst new file mode 100644 index 00000000..da6191cd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/E02xtrace.ztst @@ -0,0 +1,148 @@ +# Test that xtrace output is correctly generated + +%prep + mkdir xtrace.tmp && cd xtrace.tmp + + function xtf { + local regression_test_dummy_variable + print "$*" + } + function xtfx { + local regression_test_dummy_variable + print "Tracing: (){ builtin 2>file }" 2>>xtrace.err + { print "Tracing: (){ { builtin } 2>file }" } 2>>xtrace.err + } + echo 'print "$*"' > xt.in + +%test + + PS4='+%N:%i> ' + set -x + print 'Tracing: builtin' + print 'Tracing: builtin 2>file' 2>xtrace.err + cat <<<'Tracing: external' + cat <<<'Tracing: external 2>file' 2>>xtrace.err + ( print 'Tracing: ( builtin )' ) + ( print 'Tracing: ( builtin ) 2>file' ) 2>>xtrace.err + ( cat <<<'Tracing: ( external )' ) + ( cat <<<'Tracing: ( external ) 2>file' ) 2>>xtrace.err + { print 'Tracing: { builtin }' } + { print 'Tracing: { builtin } 2>file' } 2>>xtrace.err + { cat <<<'Tracing: { external }' } + { cat <<<'Tracing: { external } 2>file' } 2>>xtrace.err + repeat 1 do print 'Tracing: do builtin done'; done + repeat 1 do print 'Tracing: do builtin done 2>file'; done 2>>xtrace.err + repeat 1 do cat <<<'Tracing: do external done'; done + repeat 1 do cat <<<'Tracing: do external done 2>file'; done 2>>xtrace.err + xtf 'Tracing: function' + xtf 'Tracing: function 2>file' 2>>xtrace.err + xtfx + . ./xt.in 'Tracing: source' + . ./xt.in 'Tracing: source 2>file' 2>>xtrace.err + set +x + cat xtrace.err +0:xtrace with and without redirection +>Tracing: builtin +>Tracing: builtin 2>file +>Tracing: external +>Tracing: external 2>file +>Tracing: ( builtin ) +>Tracing: ( builtin ) 2>file +>Tracing: ( external ) +>Tracing: ( external ) 2>file +>Tracing: { builtin } +>Tracing: { builtin } 2>file +>Tracing: { external } +>Tracing: { external } 2>file +>Tracing: do builtin done +>Tracing: do builtin done 2>file +>Tracing: do external done +>Tracing: do external done 2>file +>Tracing: function +>Tracing: function 2>file +>Tracing: (){ builtin 2>file } +>Tracing: (){ { builtin } 2>file } +>Tracing: source +>Tracing: source 2>file +>+(eval):8> print 'Tracing: ( builtin ) 2>file' +>+(eval):10> cat +>+(eval):12> print 'Tracing: { builtin } 2>file' +>+(eval):14> cat +>+(eval):16> print 'Tracing: do builtin done 2>file' +>+(eval):18> cat +>+xtf:1> local regression_test_dummy_variable +>+xtf:2> print 'Tracing: function 2>file' +>+xtfx:3> print 'Tracing: (){ { builtin } 2>file }' +?+(eval):3> print 'Tracing: builtin' +?+(eval):4> print 'Tracing: builtin 2>file' +?+(eval):5> cat +?+(eval):6> cat +?+(eval):7> print 'Tracing: ( builtin )' +?+(eval):9> cat +?+(eval):11> print 'Tracing: { builtin }' +?+(eval):13> cat +?+(eval):15> print 'Tracing: do builtin done' +?+(eval):17> cat +?+(eval):19> xtf 'Tracing: function' +?+xtf:1> local regression_test_dummy_variable +?+xtf:2> print 'Tracing: function' +?+(eval):20> xtf 'Tracing: function 2>file' +?+(eval):21> xtfx +?+xtfx:1> local regression_test_dummy_variable +?+xtfx:2> print 'Tracing: (){ builtin 2>file }' +?+(eval):22> . ./xt.in 'Tracing: source' +?+./xt.in:1> print 'Tracing: source' +?+(eval):23> . ./xt.in 'Tracing: source 2>file' +?+./xt.in:1> print 'Tracing: source 2>file' +?+(eval):24> set +x + + typeset -ft xtf + xtf 'Tracing: function' +0:tracing function +>Tracing: function +?+xtf:1> local regression_test_dummy_variable +?+xtf:2> print 'Tracing: function' + + echo 'PS4="+%x:%I> " + fn() { + print This is fn. + } + : + fn + ' >fnfile + $ZTST_testdir/../Src/zsh -fx ./fnfile 2>errfile + grep '\./fnfile' errfile 1>&2 +0:Trace output with sourcefile and line number. +>This is fn. +?+./fnfile:1> PS4='+%x:%I> ' +?+./fnfile:5> : +?+./fnfile:6> fn +?+./fnfile:3> print This is fn. + + set -x + [[ 'f o' == 'f x'* || 'b r' != 'z o' && 'squashy sound' < 'squishy sound' ]] + [[ 'f o' = 'f x'* || 'b r' != 'z o' && 'squashy sound' < 'squishy sound' ]] + [[ -e nonexistentfile || ( -z '' && -t 3 ) ]] + set +x +0:Trace for conditions +?+(eval):2> [[ 'f o' == f\ x* || 'b r' != z\ o && 'squashy sound' < 'squishy sound' ]] +?+(eval):3> [[ 'f o' = f\ x* || 'b r' != z\ o && 'squashy sound' < 'squishy sound' ]] +?+(eval):4> [[ -e nonexistentfile || -z '' && -t 3 ]] +?+(eval):5> set +x + + # Part 1: Recurses into nested anonymous functions + fn() { + () { () { true } } + } + functions -T fn + fn + # Part 2: Doesn't recurse into named functions + gn() { true } + fn() { gn } + functions -T fn + fn +0:tracing recurses into anonymous functions +?+fn:1> '(anon)' +?+(anon):0> '(anon)' +?+(anon):0> true +?+fn:0> gn diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/Makefile.in b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/Makefile.in new file mode 100644 index 00000000..083df494 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/Makefile.in @@ -0,0 +1,75 @@ +# +# Makefile for Test subdirectory +# +# Copyright (c) 1999 Peter Stephensons +# All rights reserved. +# +# Permission is hereby granted, without written agreement and without +# license or royalty fees, to use, copy, modify, and distribute this +# software and to distribute modified versions of this software for any +# purpose, provided that the above copyright notice and the following +# two paragraphs appear in all copies of this software. +# +# In no event shall Peter Stephenson or the Zsh Development Group be liable +# to any party for direct, indirect, special, incidental, or consequential +# damages arising out of the use of this software and its documentation, +# even if Peter Stephenson and the Zsh Development Group have been advised of +# the possibility of such damage. +# +# Peter Stephenson and the Zsh Development Group specifically disclaim any +# warranties, including, but not limited to, the implied warranties of +# merchantability and fitness for a particular purpose. The software +# provided hereunder is on an "as is" basis, and Peter Stephenson and the +# Zsh Development Group have no obligation to provide maintenance, +# support, updates, enhancements, or modifications. +# + +subdir = Test +dir_top = .. +SUBDIRS = + +@VERSION_MK@ + +# source/build directories +VPATH = @srcdir@ +sdir = @srcdir@ +sdir_top = @top_srcdir@ +INSTALL = @INSTALL@ + +@DEFS_MK@ + +# ========== DEPENDENCIES FOR TESTING ========== + +check test: + if test -n "$(DLLD)"; then \ + cd $(dir_top) && DESTDIR= \ + $(MAKE) MODDIR=`pwd`/$(subdir)/Modules install.modules > /dev/null; \ + fi + if ZTST_testlist="`for f in $(sdir)/$(TESTNUM)*.ztst; \ + do echo $$f; done`" \ + ZTST_srcdir="$(sdir)" \ + ZTST_exe=$(dir_top)/Src/zsh@EXEEXT@ \ + $(dir_top)/Src/zsh@EXEEXT@ +Z -f $(sdir)/runtests.zsh; then \ + stat=0; \ + else \ + stat=1; \ + fi; \ + sleep 1; \ + rm -rf Modules .zcompdump; \ + exit $$stat + +# ========== DEPENDENCIES FOR CLEANUP ========== + +@CLEAN_MK@ + +mostlyclean-here: + rm -rf Modules .zcompdump *.tmp + +distclean-here: + rm -f Makefile + +realclean-here: + +# ========== DEPENDENCIES FOR MAINTENANCE ========== + +@CONFIG_MK@ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/README b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/README new file mode 100644 index 00000000..d012277c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/README @@ -0,0 +1,30 @@ +There are now different sections, expressed by the first letter in the +scripts names: + + A: basic command parsing and execution + B: builtins + C: shell commands with special syntax + D: substititution + E: options + V: modules + W: builtin interactive commands and constructs + X: line editing + Y: completion + Z: separate systems and user contributions + +You will need to run these by using `make test' in the Test subdirectory of +the build area for your system (which may or may not be the same as the +Test subdirectory of the source tree), or the directory above. You can get +more information about the tests being performed with + ZTST_verbose=1 make check +(`test' is equivalent to `check') or change 1 to 2 for even more detail. + +Individual or groups of tests can be performed with + make TESTNUM=C02 check +or + make TESTNUM=C check +to perform just the test beginning C02, or all tests beginning C, +respectively. + +Instructions on how to write tests are given in B01cd.ztst, which acts as a +model. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V02zregexparse.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V02zregexparse.ztst new file mode 100644 index 00000000..b4cec424 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V02zregexparse.ztst @@ -0,0 +1,382 @@ +# Tests corresponding to the texinfo node `Conditional Expressions' + +%prep + + if ! zmodload zsh/zutil 2>/dev/null; then + ZTST_unimplemented="can't load the zsh/zutil module for testing" + fi + +%test + + zregexparse p1 p2 '' +0:empty + + zregexparse p1 p2 a /a/ +0:element + + zregexparse p1 p2 aaaaaa /a/ \# +0:closure + + zregexparse p1 p2 ab /a/ /b/ +0:concatenation + + zregexparse p1 p2 a /a/ \| /b/ +0:alternation 1 + + zregexparse p1 p2 b /a/ \| /b/ +0:alternation 2 + + zregexparse p1 p2 a \( /a/ \) +0:grouping + + zregexparse p1 p2 abbaaab \( /a/ \| /b/ \) \# +0:alternation, grouping and closure + + zregexparse p1 p2 abcdef /ab/ %cd% /cdef/ +0:lookahead 1 + + zregexparse p1 p2 abcdef /ab/ %ZZ% /cdef/ +1:lookahead 2 + + zregexparse p1 p2 abcd /ab/ %cd% '-print guard' ':print caction' /cd/ +0:pattern, lookahead, guard and completion action +>guard + + zregexparse p1 p2 abcd /ab/ %cd% '-print guard; false' ':print caction' /cd/ +1:guard failure +>guard +>caction + + zregexparse p1 p2 abcdef /ab/ '{print AB}' /cd/ '{print CD}' /ef/ '{print EF}' +0:action +>AB +>CD +>EF + + zregexparse p1 p2 aaa + print $? $p1 $p2 +0:aaa +>2 0 0 + + zregexparse p1 p2 aaa /a/ + print $? $p1 $p2 +0:aaa /a/ +>2 1 1 + + zregexparse p1 p2 aaa /a/ /a/ + print $? $p1 $p2 +0:aaa 2*/a/ +>2 2 2 + + zregexparse p1 p2 aaa /a/ /a/ /a/ + print $? $p1 $p2 +0:aaa 3*/a/ +>0 3 3 + + zregexparse p1 p2 aaa /a/ /a/ /a/ /a/ + print $? $p1 $p2 +0:aaa 4*/a/ +>1 3 3 + + zregexparse p1 p2 aaa /a/ /a/ /a/ /a/ /a/ + print $? $p1 $p2 +0:aaa 5*/a/ +>1 3 3 + + zregexparse p1 p2 aaa /aaa/ + print $? $p1 $p2 +0:aaa /aaa/ +>0 3 3 + + zregexparse p1 p2 aaa /aaa/ /a/ + print $? $p1 $p2 +0:aaa /aaa/ /a/ +>1 3 3 + + zregexparse p1 p2 aaa /a/ \# + print $? $p1 $p2 +0:aaa /aaa/ # +>0 3 3 + + zregexparse p1 p2 aaa /a/ \# \# + print $? $p1 $p2 +0:aaa /aaa/ # # +>0 3 3 + + zregexparse p1 p2 aaa \( /a/ \) + print $? $p1 $p2 +0:aaa ( /a/ ) +>2 1 1 + + zregexparse p1 p2 aaa \( /a/ \) \# + print $? $p1 $p2 +0:aaa ( /a/ ) # +>0 3 3 + + zregexparse p1 p2 aaa /a/ /b/ + print $? $p1 $p2 +0:aaa /a/ /b/ +>1 1 1 + + zregexparse p1 p2 a /a/ '{print A}' + print $? $p1 $p2 +0:a /a/ '{A}' +>A +>0 1 1 + + zregexparse p1 p2 a /b/ '{print A}' + print $? $p1 $p2 +0:a /b/ '{A}' +>1 0 0 + + zregexparse p1 p2 a /b/ ':print A' '{print B}' + print $? $p1 $p2 +0:a /b/ ':A' '{B}' +>A +>1 0 0 + + zregexparse p1 p2 ab /a/ '{print A}' + print $? $p1 $p2 +0:ab /a/ '{A}' +>2 1 1 + + zregexparse p1 p2 ab /a/ '{print A}' /b/ '{print B}' + print $? $p1 $p2 +0:ab /a/ '{A}' /b/ '{B}' +>A +>B +>0 2 2 + + zregexparse p1 p2 ab /a/ ':print A' '{print B}' /b/ ':print C' '{print D}' + print $? $p1 $p2 +0:ab /a/ ':A' '{B}' /b/ ':C' '{D}' +>B +>D +>0 2 2 + + zregexparse p1 p2 abc /a/ '{print A}' /b/ '{print B}' /c/ '{print C}' + print $? $p1 $p2 +0:abc /a/ '{A}' /b/ '{B}' /c/ '{C}' +>A +>B +>C +>0 3 3 + + zregexparse p1 p2 abz /a/ '{print A}' /b/ '{print B}' /c/ '{print C}' + print $? $p1 $p2 +0:abz /a/ '{A}' /b/ '{B}' /c/ '{C}' +>A +>1 2 2 + + zregexparse p1 p2 azz /a/ '{print A}' /b/ '{print B}' /c/ '{print C}' + print $? $p1 $p2 +0:azz /a/ '{A}' /b/ '{B}' /c/ '{C}' +>1 1 1 + + zregexparse p1 p2 aba '{print A}' /a/ '{print B}' /b/ '{print C}' /c/ '{print D}' + print $? $p1 $p2 +0:aba '{A}' /a/ '{B}' /b/ '{C}' /c/ '{D}' +>A +>B +>1 2 2 + + zregexparse p1 p2 a /a/ '{print "$match[1]"}' + print $? $p1 $p2 +0:a /a/ '{M1}' +>a +>0 1 1 + + zregexparse p1 p2 aaa /a/ '{print A}' // + print $? $p1 $p2 +0:aaa /a/ '{A}' // +>A +>2 1 1 + + zregexparse p1 p2 aaa /a/ '{print "$match[1]"}' // '{print A}' + print $? $p1 $p2 +0:aaa /a/ '{M1}' // '{A}' +>a +>2 1 1 + + zregexparse p1 p2 abcdef /a/ '{print $match[1]}' /b/ '{print $match[1]}' /c/ '{print $match[1]}' // '{print A}' + print $? $p1 $p2 +0:abcdef /a/ '{M1}' /b/ '{M1}' /c/ '{M1}' // '{A}' +>a +>b +>c +>2 3 3 + + zregexparse p1 p2 abcdef /a/ '{print A}' /b/ '{print B}' /c/ '{print C}' // '{print D}' + print $? $p1 $p2 +0:abcdef /a/ '{A}' /b/ '{B}' /c/ '{C}' // '{D}' +>A +>B +>C +>2 3 3 + + zregexparse p1 p2 a /a/ '{print A}' /b/ '{print B}' + print $? $p1 $p2 +0:a /a/ {A} /b/ {B} +>1 1 1 + + zregexparse p1 p2 abcdef \ + /a/ '-print Ga:$p1:$p2:$match[1]' '{print Aa:$p1:$p2:$match[1]}' \ + /b/ '-print Gb:$p1:$p2:$match[1]' '{print Ab:$p1:$p2:$match[1]}' \ + /c/ '-print Gc:$p1:$p2:$match[1]' '{print Ac:$p1:$p2:$match[1]}' \ + // + print $? $p1 $p2 +0:abcdef /a/ -Ga {Aa} /b/ -Gb {Aa} /c/ -Gc {Ac} // +>Ga:0:0:a +>Gb:1:1:b +>Aa:1:1:a +>Gc:2:2:c +>Ab:2:2:b +>Ac:3:3:c +>2 3 3 + + zregexparse p1 p2 abcdef \ + /a/ '-print Ga:$p1:$p2:$match[1]' '{print Aa:$p1:$p2:$match[1]}' \ + /b/ '-print Gb:$p1:$p2:$match[1]' '{print Ab:$p1:$p2:$match[1]}' \ + /c/ '-print Gc:$p1:$p2:$match[1]' '{print Ac:$p1:$p2:$match[1]}' \ + '/[]/' ':print F:$p1:$p2' + print $? $p1 $p2 +0:abcdef /a/ -Ga {Aa} /b/ -Gb {Ab} /c/ -Gc {Ac} /[]/ :F +>Ga:0:0:a +>Gb:1:1:b +>Aa:1:1:a +>Gc:2:2:c +>Ab:2:2:b +>F:3:3 +>1 3 3 + + zregexparse p1 p2 abcdef \ + /a/ '-print Ga:$p1:$p2:$match[1]' '{print Aa:$p1:$p2:$match[1]}' \ + /b/ '-print Gb:$p1:$p2:$match[1]' '{print Ab:$p1:$p2:$match[1]}' \ + /c/ '-print Gc:$p1:$p2:$match[1]' '{print Ac:$p1:$p2:$match[1]}' \ + \( '/[]/' ':print F1:$p1:$p2' \| /z/ ':print F2' \) + print $? $p1 $p2 +0:abcdef /a/ -Ga {Aa} /b/ -Gb {Ab} /c/ -Gc {Ac} ( /[]/ :F1 | /z/ :F2 ) +>Ga:0:0:a +>Gb:1:1:b +>Aa:1:1:a +>Gc:2:2:c +>Ab:2:2:b +>F1:3:3 +>F2 +>1 3 3 + + zregexparse p1 p2 a '/[]/' ':print A' + print $? $p1 $p2 +0:a /[]/ :A +>A +>1 0 0 + + zregexparse p1 p2 $'\0' $'/\0/' '{print A}' + print $? $p1 $p2 +0:"\0" /\0/ {A} +>A +>0 1 1 + + zregexparse p1 p2 $'\0' $'/\0/' '{print A}' '/ /' '{print B}' + print $? $p1 $p2 +0:"\0" /\0/ {A} / / {B} +>1 1 1 + + zregexparse p1 p2 abcdef \( '/?/' '{print $match[1]}' \) \# + print $? $p1 $p2 +0:abcdef ( /?/ {M1} ) # +>a +>b +>c +>d +>e +>f +>0 6 6 + + zregexparse p1 p2 abcdef \( '/c?|?/' '{print $match[1]}' \) \# + print $? $p1 $p2 +0:abcdef ( /c?|?/ {M1} ) # +>a +>b +>cd +>e +>f +>0 6 6 + + zregexparse p1 p2 abcacdef \( /a/ '{print $match[1]}' \| /b/ '{print $match[1]}' \| /c/ '{print $match[1]}' \) \# + print $? $p1 $p2 +0:abcacdef ( /a/ {M1} | /b/ {M1} | /c/ {M1} ) # +>a +>b +>c +>a +>1 5 5 + + zregexparse p1 p2 abcdef \( /a/ ':print A' \| /b/ ':print B' \| /c/ ':print C' \) \# + print $? $p1 $p2 +0:abcdef ( /a/ :A | /b/ :B | /c/ :C ) # +>A +>B +>C +>1 3 3 + + zregexparse p1 p2 abcdef \( /a/ ':print A' '{print $match[1]}' \| /b/ ':print B' '{print $match[1]}' \| /c/ ':print C' '{print $match[1]}' \) \# + print $? $p1 $p2 +0:abcdef ( /a/ :A {M1} | /b/ :B {M1} | /c/ :C {M1} ) # +>a +>b +>A +>B +>C +>1 3 3 + + zregexparse p1 p2 $'com\0xx' /$'[^\0]#\0'/ \( /$'[^\0]#\0'/ :'print A' /$'[^\0]#\0'/ :'print B' \) \# + print $? $p1 $p2 +0:"com\0xx" /W/ ( /W/ :A /W/ :B ) # +>A +>1 4 4 + + zregexparse p1 p2 $'com\0xx\0yy' /$'[^\0]#\0'/ \( /$'[^\0]#\0'/ :'print A' /$'[^\0]#\0'/ :'print B' \) \# + print $? $p1 $p2 +0:"com\0xx\0yy" /W/ ( /W/ :A /W/ :B ) # +>B +>1 7 7 + + zregexparse p1 p2 $'com\0xx\0yy\0zz' /$'[^\0]#\0'/ \( /$'[^\0]#\0'/ :'print A' /$'[^\0]#\0'/ :'print B' \) \# + print $? $p1 $p2 +0:"com\0xx\0yy\0zz" /W/ ( /W/ :A /W/ :B ) # +>A +>1 10 10 + + zregexparse p1 p2 abcdez /abc/ ':print A:$p1:$p2' /def/ ':print B:$p1:$p2' + print $? $p1 $p2 +0:abcdez /abc/ :A /def/ :B +>B:3:3 +>1 3 3 + + zregexparse p1 p2 abcdez /abc/+ ':print A:$p1:$p2' /def/ ':print B:$p1:$p2' + print $? $p1 $p2 +0:abcdez /abc/+ :A /def/ :B +>A:0:3 +>B:0:3 +>1 0 3 + + zregexparse p1 p2 abcdez /abc/+ ':print A:$p1:$p2' // /def/ ':print B:$p1:$p2' + print $? $p1 $p2 +0:abcdez /abc/+ :A // /def/ :B +>A:0:3 +>B:0:3 +>1 0 3 + + zregexparse p1 p2 abcdez /abc/+ ':print A:$p1:$p2' //- /def/ ':print B:$p1:$p2' + print $? $p1 $p2 +0:abcdez /abc/+ :A //- /def/ :B +>B:3:3 +>1 3 3 + + zregexparse p1 p2 $'ZZZZ\0abcdef' $'/ZZZZ\0/' /abc/+ ':print A:$p1:$p2' /dee/ ':print B:$p1:$p2' + print $? $p1 $p2 +0:"ZZZZ\0abcdef" /ZZZZ\0/ /abc/+ :A /dee/ :B +>A:5:8 +>B:5:8 +>1 5 8 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V03mathfunc.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V03mathfunc.ztst new file mode 100644 index 00000000..1edb7a27 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V03mathfunc.ztst @@ -0,0 +1,141 @@ +# Tests for the module zsh/mathfunc + +%prep + if ! zmodload zsh/mathfunc 2>/dev/null; then + ZTST_unimplemented="The module zsh/mathfunc is not available." + fi + +%test + # -g makes pi available in later tests + float -gF 5 pi + (( pi = 4 * atan(1.0) )) + print $pi +0:Basic operation with atan +>3.14159 + + float -F 5 result + (( result = atan(3,2) )) + print $result +0:atan with two arguments +>0.98279 + + print $(( atan(1,2,3) )) +1:atan can't take three arguments +?(eval):1: wrong number of arguments: atan(1,2,3) + + float r1=$(( rand48() )) + float r2=$(( rand48() )) + float r3=$(( rand48() )) + # Yes, this is a floating point equality test like they tell + # you not to do. As the pseudrandom sequence is deterministic, + # this is the right thing to do in this case. + if (( r1 == r2 )); then + print "Seed not updated correctly the first time" + else + print "First two random numbers differ, OK" + fi + if (( r2 == r3 )); then + print "Seed not updated correctly the second time" + else + print "Second two random numbers differ, OK" + fi +0:rand48 with default initialisation +F:This test fails if your math library doesn't have erand48(). +>First two random numbers differ, OK +>Second two random numbers differ, OK + + seed=f45677a6cbe4 + float r1=$(( rand48(seed) )) + float r2=$(( rand48(seed) )) + seed2=$seed + float r3=$(( rand48(seed) )) + float r4=$(( rand48(seed2) )) + # Yes, this is a floating point equality test like they tell + # you not to do. As the pseudrandom sequence is deterministic, + # this is the right thing to do in this case. + if (( r1 == r2 )); then + print "Seed not updated correctly the first time" + else + print "First two random numbers differ, OK" + fi + if (( r2 == r3 )); then + print "Seed not updated correctly the second time" + else + print "Second two random numbers differ, OK" + fi + if (( r3 == r4 )); then + print "Identical seeds generate identical numbers, OK" + else + print "Indeterminate result from identical seeds" + fi +0:rand48 with pre-generated seed +F:This test fails if your math library doesn't have erand48(). +>First two random numbers differ, OK +>Second two random numbers differ, OK +>Identical seeds generate identical numbers, OK + + float -F 5 pitest + (( pitest = 4.0 * atan(1) )) + # This is a string test of the output to 5 digits. + if [[ $pi = $pitest ]]; then + print "OK, atan on an integer seemed to work" + else + print "BAD: got $pitest instead of $pi" + fi +0:Conversion of arguments from integer +>OK, atan on an integer seemed to work + + float -F 5 result + typeset str + for str in 0 0.0 1 1.5 -1 -1.5; do + (( result = abs($str) )) + print $result + done +0:Use of abs on various numbers +>0.00000 +>0.00000 +>1.00000 +>1.50000 +>1.00000 +>1.50000 + + print $(( sqrt(-1) )) +1:Non-negative argument checking for square roots. +?(eval):1: math: argument to sqrt out of range + +# Simple test that the pseudorandom number generators are producing +# something that could conceivably be pseudorandom numbers in a +# linear range. Not a detailed quantitative verification. + integer N=10000 isource ok=1 + float -F f sum sumsq max max2 av sd + typeset -a randoms + randoms=('f = RANDOM' 'f = rand48()') + for isource in 1 2; do + (( sum = sumsq = max = 0 )) + repeat $N; do + let $randoms[$isource] + (( f > max )) && (( max = f )) + (( sum += f, sumsq += f * f )) + done + (( av = sum / N )) + (( sd = sqrt((sumsq - N * av * av) / (N-1)) )) + (( max2 = 0.5 * max )) + if (( av > max2 * 1.1 )) || (( av < max2 * 0.9 )); then + print "WARNING: average of random numbers is suspicious. + Was testing: $randoms[$isource]" + (( ok = 0 )) + fi + if (( sd < max / 4 )); then + print "WARNING: distribution of random numbers is suspicious. + Was testing: $randoms[$isource]" + (( ok = 0 )) + fi + done + (( ok )) +0:Test random number generator distributions are not grossly broken + + float -F 5 g l + (( g = gamma(2), l = lgamma(2) )) + print $g, $l +0:Test Gamma function gamma and lgamma +>1.00000, 0.00000 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V04features.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V04features.ztst new file mode 100644 index 00000000..6939053e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V04features.ztst @@ -0,0 +1,172 @@ +%prep + +# Do some tests on handling of features. +# This also does some slightly more sophisticated loading and +# unloading tests than we did in V01zmodload.ztst. +# +# We use zsh/datetime because it has a list of features that is short +# but contains two types. + + # Subshell for prep test so we can load individual features later + if ! (zmodload zsh/datetime 2>/dev/null); then + ZTST_unimplemented="can't load the zsh/datetime module for testing" + fi + +%test + zmodload -F zsh/datetime + zmodload -lF zsh/datetime +0:Loading modules with no features +>-b:strftime +>-p:EPOCHSECONDS +>-p:EPOCHREALTIME +>-p:epochtime + + zmodload -F zsh/datetime b:strftime + zmodload -lF zsh/datetime +0:Enabling features +>+b:strftime +>-p:EPOCHSECONDS +>-p:EPOCHREALTIME +>-p:epochtime + + zmodload -F zsh/datetime +p:EPOCHSECONDS -b:strftime + zmodload -lF zsh/datetime +0:Disabling features +>-b:strftime +>+p:EPOCHSECONDS +>-p:EPOCHREALTIME +>-p:epochtime + + zmodload -Fe zsh/datetime p:EPOCHSECONDS b:strftime +0:Testing existing features + + zmodload -Fe zsh/datetime +p:EPOCHSECONDS +0:Testing features are in given state (on feature is on) + + zmodload -Fe zsh/datetime -p:EPOCHSECONDS +1:Testing features are in given state (on feature is not off + + zmodload -Fe zsh/datetime +p:strftime +1:Testing features are in given state (off feature is not on) + + zmodload -Fe zsh/datetime -b:strftime +0:Testing features are in given state (off feature is off + + zmodload -Fe zsh/datetime p:EPOCHSECONDS b:strftime b:mktimebetter +1:Testing non-existent features + + zmodload -FlP dtf zsh/datetime + for feature in b:strftime p:EPOCHSECONDS; do + if [[ ${${dtf[(R)?$feature]}[1]} = + ]]; then + print $feature is enabled + else + print $feature is disabled + fi + done +0:Testing features via array parameter +>b:strftime is disabled +>p:EPOCHSECONDS is enabled + + fn() { + local EPOCHSECONDS=scruts + print $EPOCHSECONDS + print ${(t)EPOCHSECONDS} + } + fn + if [[ $EPOCHSECONDS = <-> ]]; then + print EPOCHSECONDS is a number + else + print EPOCHSECONDS is some random piece of junk + fi + print ${(t)EPOCHSECONDS} +0:Module special parameter is hidden by a local parameter +>scruts +>scalar-local +>EPOCHSECONDS is a number +>integer-readonly-hide-hideval-special + + typeset +h EPOCHSECONDS + fn() { + local EPOCHSECONDS=scruts + print Didn\'t get here >&2 + } + fn +1:Unhidden readonly special can't be assigned to when made local +?fn:1: read-only variable: EPOCHSECONDS + + zmodload -u zsh/datetime +0:Module unloaded + + zmodload -e zsh/datetime +1:Module doesn't exist when unloaded + + zmodload -Fe zsh/datetime p:EPOCHSECONDS +1:Module doesn't have features when unloaded + + fn() { + local EPOCHSECONDS=scrimf + zmodload zsh/datetime + } + fn +2:Failed to add parameter if local parameter present +?fn:2: Can't add module parameter `EPOCHSECONDS': local parameter exists +?fn:zsh/datetime:2: error when adding parameter `EPOCHSECONDS' + + zmodload -lF zsh/datetime +0:Feature state with loading after error enabling +>+b:strftime +>-p:EPOCHSECONDS +>+p:EPOCHREALTIME +>+p:epochtime + + zmodload -F zsh/datetime p:EPOCHSECONDS + zmodload -Fe zsh/datetime +p:EPOCHSECONDS +0:Successfully added feature parameter that previously failed + + fn() { + local EPOCHSECONDS=scrooble + zmodload -u zsh/datetime + print $EPOCHSECONDS + } + fn + print ${+EPOCHSECONDS} +0:Successfully unloaded a module despite a parameter being hidden +>scrooble +>0 + + EPOCHSECONDS=(any old parameter) + print -l $EPOCHSECONDS +0:Using parameter as normal after unloading is OK +>any +>old +>parameter + + print strftime is ${builtins[strftime]:-undefined} + zmodload -F zsh/datetime b:strftime + print strftime is ${builtins[strftime]:-undefined} + zmodload -F zsh/datetime -b:strftime + print strftime is ${builtins[strftime]:-undefined} +0:Enabling and disabling of builtins as features +>strftime is undefined +>strftime is defined +>strftime is undefined + + zmodload -u zsh/datetime + zmodload zsh/datetime +2:Loading won't override global parameter +?(eval):2: Can't add module parameter `EPOCHSECONDS': parameter already exists +?(eval):zsh/datetime:2: error when adding parameter `EPOCHSECONDS' + + unset EPOCHSECONDS + zmodload -F zsh/datetime p:EPOCHSECONDS + zmodload -Fe zsh/datetime +p:EPOCHSECONDS +0:unsetting a global parameter allows feature parameter to be enabled + + zmodload -F zsh/datetime -b:strftime -p:EPOCHSECONDS + zmodload zsh/datetime + zmodload -lF zsh/datetime +0:zmodload with no -F enables all features +>+b:strftime +>+p:EPOCHSECONDS +>+p:EPOCHREALTIME +>+p:epochtime diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V05styles.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V05styles.ztst new file mode 100644 index 00000000..ca95b634 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V05styles.ztst @@ -0,0 +1,143 @@ +%prep + +# Test the use of styles, if the zsh/zutil module is available. + + if ! zmodload zsh/zutil 2>/dev/null; then + ZTST_unimplemented="can't load the zsh/zutil module for testing" + fi + +%test + zstyle :random:stuff any-old-style with any old value + zstyle :randomly:chosen some-other-style I can go on and on + zstyle -d + zstyle +0:zstyle -d restores a pristine state + +# patterns should be ordered by weight, so add in reverse order to check + zstyle ':ztst:context*' scalar-style other-scalar-value + zstyle ':ztst:context:*' scalar-style second-scalar-value + zstyle ':ztst:context:sub1' scalar-style scalar-value + zstyle ':ztst:context:sub1' array-style array value elements 'with spaces' + zstyle ':ztst:context*' boolean-style false + zstyle ':ztst:context:sub1' boolean-style true +0:defining styles + +# styles are now sorted, but patterns are in order of definition + zstyle +0:listing styles in default format +>array-style +> :ztst:context:sub1 array value elements 'with spaces' +>boolean-style +> :ztst:context:sub1 true +> :ztst:context* false +>scalar-style +> :ztst:context:sub1 scalar-value +> :ztst:context:* second-scalar-value +> :ztst:context* other-scalar-value + + zstyle -L +0:listing styles in zstyle format +>zstyle :ztst:context:sub1 array-style array value elements 'with spaces' +>zstyle :ztst:context:sub1 boolean-style true +>zstyle ':ztst:context*' boolean-style false +>zstyle :ztst:context:sub1 scalar-style scalar-value +>zstyle ':ztst:context:*' scalar-style second-scalar-value +>zstyle ':ztst:context*' scalar-style other-scalar-value + + zstyle -b :ztst:context:sub1 boolean-style bool; print $bool + zstyle -t :ztst:context:sub1 boolean-style +0:boolean test -b/-t + true +>yes + + zstyle -b :ztst:context:sub2 boolean-style bool; print $bool + zstyle -t :ztst:context:sub2 boolean-style +1:boolean test -b/-t + false +>no + + zstyle -b :ztst:context:sub1 boolean-unset-style bool; print $bool + zstyle -t :ztst:context:sub1 boolean-unset-style +2:boolean test -b/-t + unset +>no + + zstyle -T :ztst:context:sub1 boolean-style +0:boolean test -T + true + + zstyle -T :ztst:context:sub2 boolean-style +1:boolean test -T + false + + zstyle -T :ztst:context:sub1 boolean-unset-style +0:boolean test -T + unset + + zstyle -s :ztst:context:sub1 scalar-style scalar && print $scalar + zstyle -s :ztst:context:sub2 scalar-style scalar && print $scalar + zstyle -s :ztst:contextual-psychedelia scalar-style scalar && print $scalar + zstyle -s :ztst:contemplative scalar-style scalar || print no match +0:pattern matching rules +>scalar-value +>second-scalar-value +>other-scalar-value +>no match + + zstyle -s :ztst:context:sub1 array-style scalar + && print $scalar +0:scalar with separator +>array+value+elements+with spaces + + zstyle -e :ztst:\* eval-style 'reply=($something)' + something=(one two three) + zstyle -a :ztst:eval eval-style array && print -l $array +0:zstyle -e evaluations +>one +>two +>three + +# pattern ordering on output is not specified, so although in the +# current implementation it's deterministic we shouldn't +# assume it's always the same. Thus we sort the array. +# (It might be a nice touch to order patterns by weight, which is +# the way they are stored for each separate style.) + zstyle -g array && print -l ${(o)array} +0:retrieving patterns +>:ztst:* +>:ztst:context* +>:ztst:context:* +>:ztst:context:sub1 + + zstyle -m :ztst:context:sub1 array-style 'w* *s' +0:positive pattern match + + zstyle -m :ztst:context:sub1 array-style 'v' +1:negative pattern match + + zstyle -g array ':ztst:context*' && print -l $array +0:retrieving styles by pattern +>boolean-style +>scalar-style + + zstyle -g array ':ztst:context:sub1' array-style && print -l $array +0:retrieving values by pattern and name +>array +>value +>elements +>with spaces + + zstyle -d :ztst:context:sub1 + zstyle +0:deleting styles by pattern only +>boolean-style +> :ztst:context* false +>eval-style +>(eval) :ztst:* 'reply=($something)' +>scalar-style +> :ztst:context:* second-scalar-value +> :ztst:context* other-scalar-value + + zstyle -d :ztst:context\* scalar-style + zstyle +0:deleting styles by pattern and style name +>boolean-style +> :ztst:context* false +>eval-style +>(eval) :ztst:* 'reply=($something)' +>scalar-style +> :ztst:context:* second-scalar-value + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V07pcre.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V07pcre.ztst new file mode 100644 index 00000000..ad177071 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V07pcre.ztst @@ -0,0 +1,139 @@ +%prep + + if ! zmodload -F zsh/pcre C:pcre-match 2>/dev/null + then + ZTST_unimplemented="the zsh/pcre module is not available" + return 0 + fi +# Load the rest of the builtins + zmodload zsh/pcre + setopt rematch_pcre +# Find a UTF-8 locale. + setopt multibyte +# Don't let LC_* override our choice of locale. + unset -m LC_\* + mb_ok= + langs=(en_{US,GB}.{UTF-,utf}8 en.UTF-8 + $(locale -a 2>/dev/null | egrep 'utf8|UTF-8')) + for LANG in $langs; do + if [[ é = ? ]]; then + mb_ok=1 + break; + fi + done + if [[ -z $mb_ok ]]; then + ZTST_unimplemented="no UTF-8 locale or multibyte mode is not implemented" + else + print -u $ZTST_fd Testing PCRE multibyte with locale $LANG + mkdir multibyte.tmp && cd multibyte.tmp + fi + +%test + + [[ 'foo→bar' =~ .([^[:ascii:]]). ]] + print $MATCH + print $match[1] +0:Basic non-ASCII regexp matching +>o→b +>→ + + unset match mend + s=$'\u00a0' + [[ $s =~ '^.$' ]] && print OK + [[ A${s}B =~ .(.). && $match[1] == $s ]] && print OK + [[ A${s}${s}B =~ A([^[:ascii:]]*)B && $mend[1] == 3 ]] && print OK + unset s +0:Raw IMETA characters in input string +>OK +>OK +>OK + + [[ foo =~ f.+ ]] ; print $? + [[ foo =~ x.+ ]] ; print $? + [[ ! foo =~ f.+ ]] ; print $? + [[ ! foo =~ x.+ ]] ; print $? + [[ foo =~ f.+ && bar =~ b.+ ]] ; print $? + [[ foo =~ x.+ && bar =~ b.+ ]] ; print $? + [[ foo =~ f.+ && bar =~ x.+ ]] ; print $? + [[ ! foo =~ f.+ && bar =~ b.+ ]] ; print $? + [[ foo =~ f.+ && ! bar =~ b.+ ]] ; print $? + [[ ! ( foo =~ f.+ && bar =~ b.+ ) ]] ; print $? + [[ ! foo =~ x.+ && bar =~ b.+ ]] ; print $? + [[ foo =~ x.+ && ! bar =~ b.+ ]] ; print $? + [[ ! ( foo =~ x.+ && bar =~ b.+ ) ]] ; print $? +0:Regex result inversion detection +>0 +>1 +>1 +>0 +>0 +>1 +>1 +>1 +>1 +>1 +>0 +>1 +>0 + +# Note that PCRE_ANCHORED only means anchored at the start +# Also note that we don't unset MATCH/match on failed match (and it's an +# open issue as to whether or not we should) + pcre_compile '.(→.)' + pcre_match foo→bar + print $? $MATCH $match ; unset MATCH match + pcre_match foo.bar + print $? $MATCH $match ; unset MATCH match + pcre_match foo†bar + print $? $MATCH $match ; unset MATCH match + pcre_match foo→†ar + print $? $MATCH $match ; unset MATCH match + pcre_study + pcre_match foo→bar + print $? $MATCH $match ; unset MATCH match + pcre_compile -a '.(→.)' + pcre_match foo→bar + print $? $MATCH $match ; unset MATCH match + pcre_match o→bar + print $? $MATCH $match ; unset MATCH match + pcre_match o→b + print $? $MATCH $match ; unset MATCH match + pcre_compile 'x.(→.)' + pcre_match xo→t + print $? $MATCH $match ; unset MATCH match + pcre_match Xo→t + print $? $MATCH $match ; unset MATCH match + pcre_compile -i 'x.(→.)' + pcre_match xo→t + print $? $MATCH $match ; unset MATCH match + pcre_match Xo→t + print $? $MATCH $match ; unset MATCH match +0:pcre_compile interface testing: basic, anchored & case-insensitive +>0 o→b →b +>1 +>1 +>0 o→† →† +>0 o→b →b +>1 +>0 o→b →b +>0 o→b →b +>0 xo→t →t +>1 +>0 xo→t →t +>0 Xo→t →t + + string="The following zip codes: 78884 90210 99513" + pcre_compile -m "\d{5}" + pcre_match -b -- $string && print "$MATCH; ZPCRE_OP: $ZPCRE_OP" + pcre_match -b -n $ZPCRE_OP[(w)2] -- $string || print failed + print "$MATCH; ZPCRE_OP: $ZPCRE_OP" +0:pcre_match -b and pcre_match -n +>78884; ZPCRE_OP: 25 30 +>90210; ZPCRE_OP: 31 36 + +# Subshell because crash on failure + ( setopt re_match_pcre + [[ test.txt =~ '^(.*_)?(test)' ]] + echo $match[2] ) +0:regression for segmentation fault, workers/38307 +>test diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V08zpty.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V08zpty.ztst new file mode 100644 index 00000000..b0cbfa05 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V08zpty.ztst @@ -0,0 +1,29 @@ +# zpty is required by tests of interactive modes of the shell itself. +# This tests some extra things. + +%prep + + if ! zmodload zsh/zpty 2>/dev/null + then + ZTST_unimplemented="the zsh/zpty module is not available" + elif [[ $OSTYPE = cygwin ]]; then + ZTST_unimplemented="the zsh/zpty module does not work on Cygwin" + fi + +%test + + zpty cat cat + zpty -w cat a line of text + var= + zpty -r cat var && print -r -- ${var%%$'\r\n'} + zpty -d cat +0:zpty with a process that does not set up the terminal: internal write +>a line of text + + zpty cat cat + print a line of text | zpty -w cat + var= + zpty -r cat var && print -r -- ${var%%$'\r\n'} + zpty -d cat +0:zpty with a process that does not set up the terminal: write via stdin +>a line of text diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V09datetime.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V09datetime.ztst new file mode 100644 index 00000000..7905155d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V09datetime.ztst @@ -0,0 +1,74 @@ +%prep + + if zmodload zsh/datetime 2>/dev/null; then + setopt multibyte + unset LC_ALL + LC_TIME=C + TZ=UTC+0 + # It's not clear this skip_extensions is correct, but the + # format in question is causing problems on Solaris. + # We'll revist this after the release. + [[ "$(strftime %^_10B 0)" = " JANUARY" ]] || skip_extensions=1 + [[ "$(LC_TIME=ja_JP.UTF-8 strftime %OS 1)" = 一 ]] || skip_japanese=1 + else + ZTST_unimplemented="can't load the zsh/datetime module for testing" + fi + +%test + + strftime %y 0 + strftime %Y 1000000000 + strftime %x 1200000000 + strftime %X 1200000001 +0:basic format specifiers +>70 +>2001 +>01/10/08 +>21:20:01 + + strftime %-m_%f_%K_%L 1181100000 + strftime %6. 0 +0:zsh extensions +>6_6_3_3 +>000000 + + if [[ $skip_extensions = 1 ]]; then + ZTST_skip="strftime extensions not supported" + elif [[ $skip_japanese = 1 ]]; then + ZTST_skip="Japanese UTF-8 locale not supported" + else + ( + LC_TIME=ja_JP.UTF-8 + strftime %Ey 1000000000 + strftime %Oy 1000000000 + strftime %Ex 1000000000 + strftime %OS 1000000000 + strftime %03Ey 650000000 + ) + fi +0:alternate format extensions +>13 +>一 +>平成13年09月09日 +>四十 +>002 + + if [[ $skip_extensions = 1 ]]; then + ZTST_skip="strftime extensions not supported" + else + ( + strftime '%#A' 0 + strftime '%^_10B' 0 + strftime %03Ey 650000000 + strftime %-Oe 0 + ) + fi +0:various extensions +>THURSDAY +> JANUARY +>090 +>1 + + print -r -- ${(V)"$(strftime $'%Y\0%m\0%d' 100000000)"} +0:Embedded nulls +>1973^@03^@03 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V10private.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V10private.ztst new file mode 100644 index 00000000..78ecd48e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/V10private.ztst @@ -0,0 +1,304 @@ +# Tests for the zsh/param/private module + +%prep + + if ! zmodload zsh/param/private 2>/dev/null; then + ZTST_unimplemented="can't load the zsh/param/private module for testing" + else + # Do not use .tmp here, ztst.zsh will remove it too soon (see %cleanup) + mkdir private.TMP + sed -e 's,# test_zsh_param_private,zmodload zsh/param/private,' < $ZTST_srcdir/B02typeset.ztst > private.TMP/B02 + fi + +%test + + (zmodload -u zsh/param/private && zmodload zsh/param/private) +0:unload and reload the module without crashing + + typeset scalar_test=toplevel + () { + print $scalar_test + private scalar_test + print $+scalar_test + unset scalar_test + print $+scalar_test + } + print $scalar_test +0:basic scope hiding +>toplevel +>1 +>0 +>toplevel + + typeset scalar_test=toplevel + print $scalar_test + () { + private scalar_test=function + print $scalar_test + } + print $scalar_test +0:enter and exit a scope +>toplevel +>function +>toplevel + + print $+unset_test + () { + private unset_test + print $+unset_test + unset_test=setme + print $unset_test + } + print $+unset_test +0:variable defined only in scope +>0 +>1 +>setme +>0 + + # Depends on zsh-5.0.9 typeset keyword + typeset -a array_test=(top level) + () { + local -Pa array_test=(in function) + () { + private array_test + print $+array_test + } + print $array_test + } + print $array_test +0:nested scope with different type, correctly restored +>1 +>in function +>top level + + typeset -a array_test=(top level) + () { + private array_test + array_test=(in function) + } +1:type of private may not be changed by assignment +?(anon):2: array_test: attempt to assign array value to non-array + + typeset -A hash_test=(top level) + () { + setopt localoptions noglob + private hash_test[top] + } +1:associative array fields may not be private +?(anon):private:2: hash_test[top]: can't create local array elements + + () { + private path + } +1:tied params may not be private, part 1 +?(anon):private:1: can't change scope of existing param: path + + () { + private PATH + } +1:tied params may not be private, part 2 +?(anon):private:1: can't change scope of existing param: PATH + + () { + private -h path + print X$path + } +0:privates may hide tied paramters +>X + + # Deliberate type mismatch here + typeset -a hash_test=(top level) + typeset -p hash_test + inner () { + private -p hash_test + print ${(t)hash_test} ${(kv)hash_test} + } + outer () { + local -PA hash_test=(in function) + typeset -p hash_test + inner + } + outer + print ${(kv)hash_test} +0:private hides value from surrounding scope in nested scope +>typeset -a hash_test=( top level ) +>typeset -A hash_test=( in function ) +>typeset -g -a hash_test=( top level ) +>array-local top level +>top level +F:note "typeset" rather than "private" in output from outer + + () { + private -a array_test + local array_test=scalar + } +1:private cannot be re-declared as local +?(anon):local:2: array_test: inconsistent type for assignment + + () { + local hash_test=scalar + private -A hash_test + } +1:local cannot be re-declared as private +?(anon):private:2: can't change scope of existing param: hash_test + + inner () { + print $+scalar_test + $ZTST_testdir/../Src/zsh -fc 'print X $scalar_test' + } + () { + private -x scalar_test=whaat + $ZTST_testdir/../Src/zsh -fc 'print X $scalar_test' + inner + print Y $scalar_test + } +0:exported private behaves like a local, part 1 +>X whaat +>0 +>X whaat +>Y whaat + + inner () { + typeset -p array_test + $ZTST_testdir/../Src/zsh -fc 'print X $array_test' + } + () { + local -Pax array_test=(whaat) + print Y $array_test + $ZTST_testdir/../Src/zsh -fc 'print X $array_test' + inner + } +0:exported private behaves like a local, part 2 (arrays do not export) +?inner:typeset:1: no such variable: array_test +>Y whaat +>X +>X + + inner () { + print $+scalar_test + $ZTST_testdir/../Src/zsh -fc 'print X $scalar_test' + } + () { + private scalar_test=whaat + export scalar_test + $ZTST_testdir/../Src/zsh -fc 'print X $scalar_test' + inner + () { + print $+scalar_test + $ZTST_testdir/../Src/zsh -fc 'print X $scalar_test' + } + print Y $scalar_test + } +0:exported private behaves like a local, part 3 (export does not change scope) +>X whaat +>0 +>X whaat +>0 +>X whaat +>Y whaat + + typeset -A hash_test=(top level) + () { + local -PA hash_test=(in function) + () { + print X ${(kv)hash_test} + } + print Y ${(kv)hash_test} + } + print ${(kv)hash_test} +0:privates are not visible in anonymous functions, part 1 +>X top level +>Y in function +>top level + + typeset -A hash_test=(top level) + () { + local -PA hash_test=(in function) + () { + print X ${(kv)hash_test} + hash_test[in]=deeper + } + print Y ${(kv)hash_test} + } + print ${(okv)hash_test} +0:privates are not visible in anonymous functions, part 2 +>X top level +>Y in function +>deeper in level top + + typeset -A hash_test=(top level) + () { + local -Pa array_test=(in function) + local -PA hash_test=($array_test) + () { + print X ${(kv)hash_test} + hash_test=(even deeper) + { + array_test+=(${(kv)hash_test}) + } always { + print ${array_test-array_test not set} ${(t)array_test} + } + } + print Y ${(kv)hash_test} Z $array_test + } + print ${(kv)hash_test} ${(t)array_test} +1:privates are not visible in anonymous functions, part 3 +>X top level +>array_test not set +?(anon):4: array_test: attempt to assign private in nested scope +F:future revision will create a global with this assignment + + typeset -a array_test + typeset -A hash_test=(top level) + () { + local -Pa array_test=(in function) + local -PA hash_test=($array_test) + () { + print X ${(kv)hash_test} + hash_test=(even deeper) + array_test+=(${(kv)hash_test}) + } + print Y ${(kv)hash_test} Z $array_test + } + print ${(kv)hash_test} $array_test +0:privates are not visible in anonymous functions, part 4 +>X top level +>Y in function Z in function +>even deeper even deeper + + typeset -A hash_test=(top level) + () { + local -PA hash_test=(in function) + () { + print X ${(kv)hash_test} + unset hash_test + } + print Y ${(kv)hash_test} + } + print ${(t)hash_test} ${(kv)hash_test} +0:privates are not visible in anonymous functions, part 5 +>X top level +>Y in function +> + + # Subshell because otherwise this silently dumps core when broken + ( () { private SECONDS } ) +1:special parameters cannot be made private +?(anon):private: can't change scope of existing param: SECONDS + + () { private -h SECONDS } +0:private parameter may hide a special parameter + + if (( UID )); then + ZTST_verbose=0 $ZTST_exe +Z -f $ZTST_srcdir/ztst.zsh private.TMP/B02 + else + ZTST_skip="cannot re-run typeset tests when tests run as superuser" + fi +0:typeset still works with zsh/param/private module loaded +*>* +*>* + +%clean + + rm -r private.TMP diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/W01history.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/W01history.ztst new file mode 100644 index 00000000..6ef9b11c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/W01history.ztst @@ -0,0 +1,60 @@ +# Tests for BANG_HIST replacements + +%prep + + if [[ -t 0 ]]; then print -u $ZTST_fd History tests write to /dev/tty; fi + +%test + + $ZTST_testdir/../Src/zsh -fis <<<' + print one two three four five six seven eight nine ten + print !:$ !:10 !:9 !:1 !:0 + print one two three four five six seven eight nine ten + print !:0-$ !:1-2 + ' 2>/dev/null +0:History word references +>one two three four five six seven eight nine ten +>ten ten nine one print +>one two three four five six seven eight nine ten +>print one two three four five six seven eight nine ten one two + + $ZTST_testdir/../Src/zsh -fis <<<' + print line one of an arbitrary series + print issue two for some mystery sequence + print !-1:5-$ + print !1:2 + print !2:2 + print !-3:1-$ + ' 2>/dev/null +0:History line numbering +>line one of an arbitrary series +>issue two for some mystery sequence +>mystery sequence +>one +>two +>mystery sequence + + $ZTST_testdir/../Src/zsh -fis <<<' + print All metaphor, Malachi, stilts and all + print !1:2:s/,/\\\\?/ !1:2:s/m/shm/:s/,/\!/ + print !1:2:& + print -l !1:2-3:gs/a/o/ + ' 2>/dev/null +0:History substitution +>All metaphor, Malachi, stilts and all +>metaphor? shmetaphor! +>metaphor! +>metophor, +>Molochi, + + $ZTST_testdir/../Src/zsh -fis <<<' + echo foo bar + echo $(!!) again + echo more $( !! )' 2>/dev/null +0:Regression test for history references in command substitution +>foo bar +>foo bar again +>more foo bar again +*?* +F:Check that a history bug introduced by workers/34160 is working again. +# Discarded line of error output consumes prompts printed by "zsh -i". diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/comptest b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/comptest new file mode 100644 index 00000000..166d0b40 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/comptest @@ -0,0 +1,177 @@ +comptestinit () { + setopt extendedglob + [[ -d $ZTST_testdir/Modules/zsh ]] && module_path=( $ZTST_testdir/Modules ) + fpath=( $ZTST_srcdir/../Functions/*~*/CVS(/) + $ZTST_srcdir/../Completion + $ZTST_srcdir/../Completion/*/*~*/CVS(/) ) + + zmodload zsh/zpty || return $? + + comptest_zsh=${ZSH:-zsh} + comptest_keymap=e + + while getopts vz: opt; do + case $opt in + z) comptest_zsh="$OPTARG";; + v) comptest_keymap="v";; + esac + done + (( OPTIND > 1 )) && shift $(( OPTIND - 1 )) + + export PS1="" + zpty zsh "$comptest_zsh -f +Z" + + zpty -r zsh log1 "**" || { + print "first prompt hasn't appeared." + return 1 + } + + comptesteval \ +"export LC_ALL=${ZSH_TEST_LANG:-C}" \ +"emulate -R zsh" \ +"export ZDOTDIR=$ZTST_testdir" \ +"module_path=( $module_path )" \ +"fpath=( $fpath )" \ +"bindkey -$comptest_keymap" \ +'LISTMAX=10000000 +stty 38400 columns 80 rows 24 tabs -icanon -iexten +TERM=vt100 +KEYTIMEOUT=1 +setopt zle +autoload -U compinit +compinit -u +zstyle ":completion:*:default" list-colors "no=" "fi=" "di=" "ln=" "pi=" "so=" "bd=" "cd=" "ex=" "mi=" "tc=" "sp=" "lc=" "ec=\n" "rc=" +zstyle ":completion:*" group-name "" +zstyle ":completion:*:messages" format "%d +" +zstyle ":completion:*:descriptions" format "%d +" +zstyle ":completion:*:options" verbose yes +zstyle ":completion:*:values" verbose yes +setopt noalwayslastprompt listrowsfirst completeinword +zmodload zsh/complist +expand-or-complete-with-report () { + print -lr "" + zle expand-or-complete + print -lr - "$LBUFFER" "$RBUFFER" + zle clear-screen + zle -R +} +list-choices-with-report () { + print -lr "" + zle list-choices + zle clear-screen + zle -R +} +comp-finish () { + print "" + zle kill-whole-line + zle clear-screen + zle -R +} +zle-finish () { + local buffer="$BUFFER" cursor="$CURSOR" mark="$MARK" + (( region_active)) || unset mark + BUFFER="" + zle -I + zle clear-screen + zle redisplay + print -lr "" "BUFFER: $buffer" "CURSOR: $cursor" + (( $+mark )) && print -lr "MARK: $mark" + zle accept-line +} +zle -N expand-or-complete-with-report +zle -N list-choices-with-report +zle -N comp-finish +zle -N zle-finish +bindkey "^I" expand-or-complete-with-report +bindkey "^D" list-choices-with-report +bindkey "^Z" comp-finish +bindkey "^X" zle-finish +bindkey -a "^X" zle-finish +' +} + +zpty_flush() { + local junk + if zpty -r -t zsh junk \*; then + (( ZTST_verbose > 2 )) && print -n -u $ZTST_fd "$*: ${(V)junk}" + while zpty -r -t zsh junk \* ; do + (( ZTST_verbose > 2 )) && print -n -u $ZTST_fd "${(V)junk}" + done + (( ZTST_verbose > 2 )) && print -u $ZTST_fd '' + fi +} + +zpty_run() { + zpty -w zsh "$*" + zpty -r -m zsh log "**" || { + print "prompt hasn't appeared." + return 1 + } +} + +comptesteval () { + local tmp=/tmp/comptest.$$ + + print -lr - "$@" > $tmp + # zpty_flush Before comptesteval + zpty -w zsh ". $tmp" + zpty -r -m zsh log_eval "**" || { + print "prompt hasn't appeared." + return 1 + } + zpty_flush After comptesteval + rm $tmp +} + +comptest () { + input="$*" + zpty -n -w zsh "$input"$'\C-Z' + zpty -r -m zsh log "***" || { + print "failed to invoke finish widget." + return 1 + } + + logs=(${(s::)log}) + shift logs + + for log in "$logs[@]"; do + if [[ "$log" = (#b)*$''(*)$'\r\n'(*)$''* ]]; then + print -lr "line: {$match[1]}{$match[2]}" + fi + while (( ${(N)log#*(#b)(<(??)>(*)|(*)|(*)|(*)|(*))} )); do + log="${log[$mend[1]+1,-1]}" + if (( 0 <= $mbegin[2] )); then + if [[ $match[2] != TC && $match[3] != \ # ]]; then + print -lr "$match[2]:{${match[3]%${(%):-%E}}}" + fi + elif (( 0 <= $mbegin[4] )); then + print -lr "DESCRIPTION:{$match[4]}" + elif (( 0 <= $mbegin[5] )); then + print -lr "MESSAGE:{$match[5]}" + elif (( 0 <= $mbegin[6] )); then + print -lr "COMPADD:{${${match[6]}//[$'\r\n']/}}" + elif (( 0 <= $mbegin[7] )); then + print -lr "INSERT_POSITIONS:{${${match[7]}//[$'\r\n']/}}" + fi + done + done +} + +zletest () { + local first=0 + for input; do + # zpty_flush Before zletest + # sleep for $KEYTIMEOUT + (( first++ )) && { sleep 2 & } | read -t 0.011 -u 0 -k 1 + zpty -n -w zsh "$input" + done + zpty -n -w zsh $'\C-X' + zpty -r -m zsh log "***" || { + print "failed to invoke finish widget." + return 1 + } + # zpty_flush After zletest + print -lr "${(@)${(@ps:\r\n:)log##*}[2,-2]}" +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/runtests.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/runtests.zsh new file mode 100644 index 00000000..562234d9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/runtests.zsh @@ -0,0 +1,27 @@ +#!/bin/zsh -f + +emulate zsh + +# Run all specified tests, keeping count of which succeeded. +# The reason for this extra layer above the test script is to +# protect from catastrophic failure of an individual test. +# We could probably do that with subshells instead. + +integer success failure skipped retval +for file in "${(f)ZTST_testlist}"; do + $ZTST_exe +Z -f $ZTST_srcdir/ztst.zsh $file + retval=$? + if (( $retval == 2 )); then + (( skipped++ )) + elif (( $retval )); then + (( failure++ )) + else + (( success++ )) + fi +done +print "************************************** +$success successful test script${${success:#1}:+s}, \ +$failure failure${${failure:#1}:+s}, \ +$skipped skipped +**************************************" +return $(( failure ? 1 : 0 )) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/ztst.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/ztst.zsh new file mode 100755 index 00000000..f172ae14 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/Test/ztst.zsh @@ -0,0 +1,547 @@ +#!/bin/zsh -f +# The line above is just for convenience. Normally tests will be run using +# a specified version of zsh. With dynamic loading, any required libraries +# must already have been installed in that case. +# +# Takes one argument: the name of the test file. Currently only one such +# file will be processed each time ztst.zsh is run. This is slower, but +# much safer in terms of preserving the correct status. +# To avoid namespace pollution, all functions and parameters used +# only by the script begin with ZTST_. +# +# Options (without arguments) may precede the test file argument; these +# are interpreted as shell options to set. -x is probably the most useful. + +# Produce verbose messages if non-zero. +# If 1, produce reports of tests executed; if 2, also report on progress. +# Defined in such a way that any value from the environment is used. +: ${ZTST_verbose:=0} + +# We require all options to be reset, not just emulation options. +# Unfortunately, due to the crud which may be in /etc/zshenv this might +# still not be good enough. Maybe we should trick it somehow. +emulate -R zsh + +# Ensure the locale does not screw up sorting. Don't supply a locale +# unless there's one set, to minimise problems. +[[ -n $LC_ALL ]] && LC_ALL=C +[[ -n $LC_COLLATE ]] && LC_COLLATE=C +[[ -n $LC_NUMERIC ]] && LC_NUMERIC=C +[[ -n $LC_MESSAGES ]] && LC_MESSAGES=C +[[ -n $LANG ]] && LANG=C + +# Don't propagate variables that are set by default in the shell. +typeset +x WORDCHARS + +# Set the module load path to correspond to this build of zsh. +# This Modules directory should have been created by "make check". +[[ -d Modules/zsh ]] && module_path=( $PWD/Modules ) +# Allow this to be passed down. +export MODULE_PATH + +# We need to be able to save and restore the options used in the test. +# We use the $options variable of the parameter module for this. +zmodload zsh/parameter + +# Note that both the following are regular arrays, since we only use them +# in whole array assignments to/from $options. +# Options set in test code (i.e. by default all standard options) +ZTST_testopts=(${(kv)options}) + +setopt extendedglob nonomatch +while [[ $1 = [-+]* ]]; do + set $1 + shift +done +# Options set in main script +ZTST_mainopts=(${(kv)options}) + +# We run in the current directory, so remember it. +ZTST_testdir=$PWD +ZTST_testname=$1 + +integer ZTST_testfailed + +# This is POSIX nonsense. Because of the vague feeling someone, somewhere +# may one day need to examine the arguments of "tail" using a standard +# option parser, every Unix user in the world is expected to switch +# to using "tail -n NUM" instead of "tail -NUM". Older versions of +# tail don't support this. +tail() { + emulate -L zsh + + if [[ -z $TAIL_SUPPORTS_MINUS_N ]]; then + local test + test=$(echo "foo\nbar" | command tail -n 1 2>/dev/null) + if [[ $test = bar ]]; then + TAIL_SUPPORTS_MINUS_N=1 + else + TAIL_SUPPORTS_MINUS_N=0 + fi + fi + + integer argi=${argv[(i)-<->]} + + if [[ $argi -le $# && $TAIL_SUPPORTS_MINUS_N = 1 ]]; then + argv[$argi]=(-n ${argv[$argi][2,-1]}) + fi + + command tail "$argv[@]" +} + +# The source directory is not necessarily the current directory, +# but if $0 doesn't contain a `/' assume it is. +if [[ $0 = */* ]]; then + ZTST_srcdir=${0%/*} +else + ZTST_srcdir=$PWD +fi +[[ $ZTST_srcdir = /* ]] || ZTST_srcdir="$ZTST_testdir/$ZTST_srcdir" + +# Set the function autoload paths to correspond to this build of zsh. +fpath=( $ZTST_srcdir/../Functions/*~*/CVS(/) + $ZTST_srcdir/../Completion + $ZTST_srcdir/../Completion/*/*~*/CVS(/) ) + +: ${TMPPREFIX:=/tmp/zsh} +ZTST_tmp=${TMPPREFIX}.ztst.$$ +if ! rm -f $ZTST_tmp || ! mkdir -p $ZTST_tmp || ! chmod go-w $ZTST_tmp; then + print "Can't create $ZTST_tmp for exclusive use." >&2 + exit 1 +fi +# Temporary files for redirection inside tests. +ZTST_in=${ZTST_tmp}/ztst.in +# hold the expected output +ZTST_out=${ZTST_tmp}/ztst.out +ZTST_err=${ZTST_tmp}/ztst.err +# hold the actual output from the test +ZTST_tout=${ZTST_tmp}/ztst.tout +ZTST_terr=${ZTST_tmp}/ztst.terr + +ZTST_cleanup() { + cd $ZTST_testdir + rm -rf $ZTST_testdir/dummy.tmp $ZTST_testdir/*.tmp(N) ${ZTST_tmp} +} + +# This cleanup always gets performed, even if we abort. Later, +# we should try and arrange that any test-specific cleanup +# always gets called as well. +##trap 'print cleaning up... +##ZTST_cleanup' INT QUIT TERM +# Make sure it's clean now. +rm -rf dummy.tmp *.tmp + +# Report failure. Note that all output regarding the tests goes to stdout. +# That saves an unpleasant mixture of stdout and stderr to sort out. +ZTST_testfailed() { + print -r "Test $ZTST_testname failed: $1" + if [[ -n $ZTST_message ]]; then + print -r "Was testing: $ZTST_message" + fi + print -r "$ZTST_testname: test failed." + if [[ -n $ZTST_failmsg ]]; then + print -r "The following may (or may not) help identifying the cause: +$ZTST_failmsg" + fi + ZTST_testfailed=1 + return 1 +} + +# Print messages if $ZTST_verbose is non-empty +ZTST_verbose() { + local lev=$1 + shift + if [[ -n $ZTST_verbose && $ZTST_verbose -ge $lev ]]; then + print -r -u $ZTST_fd -- $* + fi +} +ZTST_hashmark() { + if [[ ZTST_verbose -le 0 && -t $ZTST_fd ]]; then + print -n -u$ZTST_fd -- ${(pl:SECONDS::\#::\#\r:)} + fi + (( SECONDS > COLUMNS+1 && (SECONDS -= COLUMNS) )) +} + +if [[ ! -r $ZTST_testname ]]; then + ZTST_testfailed "can't read test file." + exit 1 +fi + +exec {ZTST_fd}>&1 +exec {ZTST_input}<$ZTST_testname + +# The current line read from the test file. +ZTST_curline='' +# The current section being run +ZTST_cursect='' + +# Get a new input line. Don't mangle spaces; set IFS locally to empty. +# We shall skip comments at this level. +ZTST_getline() { + local IFS= + while true; do + read -u $ZTST_input -r ZTST_curline || return 1 + [[ $ZTST_curline == \#* ]] || return 0 + done +} + +# Get the name of the section. It may already have been read into +# $curline, or we may have to skip some initial comments to find it. +# If argument present, it's OK to skip the reset of the current section, +# so no error if we find garbage. +ZTST_getsect() { + local match mbegin mend + + while [[ $ZTST_curline != '%'(#b)([[:alnum:]]##)* ]]; do + ZTST_getline || return 1 + [[ $ZTST_curline = [[:blank:]]# ]] && continue + if [[ $# -eq 0 && $ZTST_curline != '%'[[:alnum:]]##* ]]; then + ZTST_testfailed "bad line found before or after section: +$ZTST_curline" + exit 1 + fi + done + # have the next line ready waiting + ZTST_getline + ZTST_cursect=${match[1]} + ZTST_verbose 2 "ZTST_getsect: read section name: $ZTST_cursect" + return 0 +} + +# Read in an indented code chunk for execution +ZTST_getchunk() { + # Code chunks are always separated by blank lines or the + # end of a section, so if we already have a piece of code, + # we keep it. Currently that shouldn't actually happen. + ZTST_code='' + # First find the chunk. + while [[ $ZTST_curline = [[:blank:]]# ]]; do + ZTST_getline || break + done + while [[ $ZTST_curline = [[:blank:]]##[^[:blank:]]* ]]; do + ZTST_code="${ZTST_code:+${ZTST_code} +}${ZTST_curline}" + ZTST_getline || break + done + ZTST_verbose 2 "ZTST_getchunk: read code chunk: +$ZTST_code" + [[ -n $ZTST_code ]] +} + +# Read in a piece for redirection. +ZTST_getredir() { + local char=${ZTST_curline[1]} fn + ZTST_redir=${ZTST_curline[2,-1]} + while ZTST_getline; do + [[ $ZTST_curline[1] = $char ]] || break + ZTST_redir="${ZTST_redir} +${ZTST_curline[2,-1]}" + done + ZTST_verbose 2 "ZTST_getredir: read redir for '$char': +$ZTST_redir" + + case $char in + ('<') fn=$ZTST_in + ;; + ('>') fn=$ZTST_out + ;; + ('?') fn=$ZTST_err + ;; + (*) ZTST_testfailed "bad redir operator: $char" + return 1 + ;; + esac + if [[ $ZTST_flags = *q* && $char = '<' ]]; then + # delay substituting output until variables are set + print -r -- "${(e)ZTST_redir}" >>$fn + else + print -r -- "$ZTST_redir" >>$fn + fi + + return 0 +} + +# Execute an indented chunk. Redirections will already have +# been set up, but we need to handle the options. +ZTST_execchunk() { + setopt localloops # don't let continue & break propagate out + options=($ZTST_testopts) + () { + unsetopt localloops + eval "$ZTST_code" + } + ZTST_status=$? + # careful... ksh_arrays may be in effect. + ZTST_testopts=(${(kv)options[*]}) + options=(${ZTST_mainopts[*]}) + ZTST_verbose 2 "ZTST_execchunk: status $ZTST_status" + return $ZTST_status +} + +# Functions for preparation and cleaning. +# When cleaning up (non-zero string argument), we ignore status. +ZTST_prepclean() { + # Execute indented code chunks. + while ZTST_getchunk; do + ZTST_execchunk >/dev/null || [[ -n $1 ]] || { + [[ -n "$ZTST_unimplemented" ]] || + ZTST_testfailed "non-zero status from preparation code: +$ZTST_code" && return 0 + } + done +} + +# diff wrapper +ZTST_diff() { + emulate -L zsh + setopt extendedglob + + local diff_out + integer diff_pat diff_ret + + case $1 in + (p) + diff_pat=1 + ;; + + (d) + ;; + + (*) + print "Bad ZTST_diff code: d for diff, p for pattern match" + ;; + esac + shift + + if (( diff_pat )); then + local -a diff_lines1 diff_lines2 + integer failed i + + diff_lines1=("${(f)$(<$argv[-2])}") + diff_lines2=("${(f)$(<$argv[-1])}") + if (( ${#diff_lines1} != ${#diff_lines2} )); then + failed=1 + else + for (( i = 1; i <= ${#diff_lines1}; i++ )); do + if [[ ${diff_lines2[i]} != ${~diff_lines1[i]} ]]; then + failed=1 + break + fi + done + fi + if (( failed )); then + print -rl "Pattern match failed:" \<${^diff_lines1} \>${^diff_lines2} + diff_ret=1 + fi + else + diff_out=$(diff "$@") + diff_ret="$?" + if [[ "$diff_ret" != "0" ]]; then + print -r -- "$diff_out" + fi + fi + + return "$diff_ret" +} + +ZTST_test() { + local last match mbegin mend found substlines + local diff_out diff_err + local ZTST_skip + + while true; do + rm -f $ZTST_in $ZTST_out $ZTST_err + touch $ZTST_in $ZTST_out $ZTST_err + ZTST_message='' + ZTST_failmsg='' + found=0 + diff_out=d + diff_err=d + + ZTST_verbose 2 "ZTST_test: looking for new test" + + while true; do + ZTST_verbose 2 "ZTST_test: examining line: +$ZTST_curline" + case $ZTST_curline in + (%*) if [[ $found = 0 ]]; then + break 2 + else + last=1 + break + fi + ;; + ([[:space:]]#) + if [[ $found = 0 ]]; then + ZTST_getline || break 2 + continue + else + break + fi + ;; + ([[:space:]]##[^[:space:]]*) ZTST_getchunk + if [[ $ZTST_curline == (#b)([-0-9]##)([[:alpha:]]#)(:*)# ]]; then + ZTST_xstatus=$match[1] + ZTST_flags=$match[2] + ZTST_message=${match[3]:+${match[3][2,-1]}} + else + ZTST_testfailed "expecting test status at: +$ZTST_curline" + return 1 + fi + ZTST_getline + found=1 + ;; + ('<'*) ZTST_getredir || return 1 + found=1 + ;; + ('*>'*) + ZTST_curline=${ZTST_curline[2,-1]} + diff_out=p + ;& + ('>'*) + ZTST_getredir || return 1 + found=1 + ;; + ('*?'*) + ZTST_curline=${ZTST_curline[2,-1]} + diff_err=p + ;& + ('?'*) + ZTST_getredir || return 1 + found=1 + ;; + ('F:'*) ZTST_failmsg="${ZTST_failmsg:+${ZTST_failmsg} +} ${ZTST_curline[3,-1]}" + ZTST_getline + found=1 + ;; + (*) ZTST_testfailed "bad line in test block: +$ZTST_curline" + return 1 + ;; + esac + done + + # If we found some code to execute... + if [[ -n $ZTST_code ]]; then + ZTST_hashmark + ZTST_verbose 1 "Running test: $ZTST_message" + ZTST_verbose 2 "ZTST_test: expecting status: $ZTST_xstatus" + ZTST_verbose 2 "Input: $ZTST_in, output: $ZTST_out, error: $ZTST_terr" + + ZTST_execchunk <$ZTST_in >$ZTST_tout 2>$ZTST_terr + + if [[ -n $ZTST_skip ]]; then + ZTST_verbose 0 "Test case skipped: $ZTST_skip" + ZTST_skip= + if [[ -n $last ]]; then + break + else + continue + fi + fi + + # First check we got the right status, if specified. + if [[ $ZTST_xstatus != - && $ZTST_xstatus != $ZTST_status ]]; then + ZTST_testfailed "bad status $ZTST_status, expected $ZTST_xstatus from: +$ZTST_code${$(<$ZTST_terr):+ +Error output: +$(<$ZTST_terr)}" + return 1 + fi + + ZTST_verbose 2 "ZTST_test: test produced standard output: +$(<$ZTST_tout) +ZTST_test: and standard error: +$(<$ZTST_terr)" + + # Now check output and error. + if [[ $ZTST_flags = *q* && -s $ZTST_out ]]; then + substlines="$(<$ZTST_out)" + rm -rf $ZTST_out + print -r -- "${(e)substlines}" >$ZTST_out + fi + if [[ $ZTST_flags != *d* ]] && ! ZTST_diff $diff_out -u $ZTST_out $ZTST_tout; then + ZTST_testfailed "output differs from expected as shown above for: +$ZTST_code${$(<$ZTST_terr):+ +Error output: +$(<$ZTST_terr)}" + return 1 + fi + if [[ $ZTST_flags = *q* && -s $ZTST_err ]]; then + substlines="$(<$ZTST_err)" + rm -rf $ZTST_err + print -r -- "${(e)substlines}" >$ZTST_err + fi + if [[ $ZTST_flags != *D* ]] && ! ZTST_diff $diff_err -u $ZTST_err $ZTST_terr; then + ZTST_testfailed "error output differs from expected as shown above for: +$ZTST_code" + return 1 + fi + fi + ZTST_verbose 1 "Test successful." + [[ -n $last ]] && break + done + + ZTST_verbose 2 "ZTST_test: all tests successful" + + # reset message to keep ZTST_testfailed output correct + ZTST_message='' +} + + +# Remember which sections we've done. +typeset -A ZTST_sects +ZTST_sects=(prep 0 test 0 clean 0) + +print "$ZTST_testname: starting." + +# Now go through all the different sections until the end. +# prep section may set ZTST_unimplemented, in this case the actual +# tests will be skipped +ZTST_skipok= +ZTST_unimplemented= +while [[ -z "$ZTST_unimplemented" ]] && ZTST_getsect $ZTST_skipok; do + case $ZTST_cursect in + (prep) if (( ${ZTST_sects[prep]} + ${ZTST_sects[test]} + \ + ${ZTST_sects[clean]} )); then + ZTST_testfailed "\`prep' section must come first" + exit 1 + fi + ZTST_prepclean + ZTST_sects[prep]=1 + ;; + (test) + if (( ${ZTST_sects[test]} + ${ZTST_sects[clean]} )); then + ZTST_testfailed "bad placement of \`test' section" + exit 1 + fi + # careful here: we can't execute ZTST_test before || or && + # because that affects the behaviour of traps in the tests. + ZTST_test + (( $? )) && ZTST_skipok=1 + ZTST_sects[test]=1 + ;; + (clean) + if (( ${ZTST_sects[test]} == 0 || ${ZTST_sects[clean]} )); then + ZTST_testfailed "bad use of \`clean' section" + else + ZTST_prepclean 1 + ZTST_sects[clean]=1 + fi + ZTST_skipok= + ;; + *) ZTST_testfailed "bad section name: $ZTST_cursect" + ;; + esac +done + +if [[ -n "$ZTST_unimplemented" ]]; then + print "$ZTST_testname: skipped ($ZTST_unimplemented)" + ZTST_testfailed=2 +elif (( ! $ZTST_testfailed )); then + print "$ZTST_testname: all tests successful." +fi +ZTST_cleanup +exit $(( ZTST_testfailed )) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/aclocal.m4 b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/aclocal.m4 new file mode 100644 index 00000000..e91be3c0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/aclocal.m4 @@ -0,0 +1,77 @@ +# Local additions to Autoconf macros. +# Copyright (C) 1992, 1994 Free Software Foundation, Inc. +# Francois Pinard , 1992. + +# @defmac fp_PROG_CC_STDC +# @maindex PROG_CC_STDC +# @ovindex CC +# If the C compiler in not in ANSI C mode by default, try to add an option +# to output variable @code{CC} to make it so. This macro tries various +# options that select ANSI C on some system or another. It considers the +# compiler to be in ANSI C mode if it defines @code{__STDC__} to 1 and +# handles function prototypes correctly. +# +# If you use this macro, you should check after calling it whether the C +# compiler has been set to accept ANSI C; if not, the shell variable +# @code{fp_cv_prog_cc_stdc} is set to @samp{no}. If you wrote your source +# code in ANSI C, you can make an un-ANSIfied copy of it by using the +# program @code{ansi2knr}, which comes with Ghostscript. +# @end defmac + +define(fp_PROG_CC_STDC, +[AC_CACHE_CHECK(for ${CC-cc} option to accept ANSI C, +fp_cv_prog_cc_stdc, +[fp_cv_prog_cc_stdc=no +ac_save_CFLAGS="$CFLAGS" +# Don't try gcc -ansi; that turns off useful extensions and +# breaks some systems' header files. +# AIX -qlanglvl=ansi +# Ultrix and OSF/1 -std1 +# HP-UX -Ae or -Aa -D_HPUX_SOURCE +# SVR4 -Xc +# For HP-UX, we try -Ae first; this turns on ANSI but also extensions, +# as well as defining _HPUX_SOURCE, and we can then use long long. +# We keep the old version for backward compatibility. +for ac_arg in "" -qlanglvl=ansi -std1 -Ae "-Aa -D_HPUX_SOURCE" -Xc +do + CFLAGS="$ac_save_CFLAGS $ac_arg" + AC_TRY_COMPILE( +[#ifndef __STDC__ +choke me +#endif +], [int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);};], +[fp_cv_prog_cc_stdc="$ac_arg"; break]) +done +CFLAGS="$ac_save_CFLAGS" +]) +case "x$fp_cv_prog_cc_stdc" in + x|xno) ;; + *) CC="$CC $fp_cv_prog_cc_stdc" ;; +esac +]) + +AC_DEFUN(AC_PROG_LN, +[AC_MSG_CHECKING(whether ln works) +AC_CACHE_VAL(ac_cv_prog_LN, +[rm -f conftestdata conftestlink +echo > conftestdata +if ln conftestdata conftestlink 2>/dev/null +then + rm -f conftestdata conftestlink + ac_cv_prog_LN="ln" +else + rm -f conftestdata + ac_cv_prog_LN="cp" +fi])dnl +LN="$ac_cv_prog_LN" +if test "$ac_cv_prog_LN" = "ln"; then + AC_MSG_RESULT(yes) +else + AC_MSG_RESULT(no) +fi +AC_SUBST(LN)dnl +]) + +builtin(include, aczsh.m4) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/aczsh.m4 b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/aczsh.m4 new file mode 100644 index 00000000..0219ae2f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/aczsh.m4 @@ -0,0 +1,690 @@ +dnl +dnl Autconf tests for zsh. +dnl +dnl Copyright (c) 1995-1997 Richard Coleman +dnl All rights reserved. +dnl +dnl Permission is hereby granted, without written agreement and without +dnl license or royalty fees, to use, copy, modify, and distribute this +dnl software and to distribute modified versions of this software for any +dnl purpose, provided that the above copyright notice and the following +dnl two paragraphs appear in all copies of this software. +dnl +dnl In no event shall Richard Coleman or the Zsh Development Group be liable +dnl to any party for direct, indirect, special, incidental, or consequential +dnl damages arising out of the use of this software and its documentation, +dnl even if Richard Coleman and the Zsh Development Group have been advised of +dnl the possibility of such damage. +dnl +dnl Richard Coleman and the Zsh Development Group specifically disclaim any +dnl warranties, including, but not limited to, the implied warranties of +dnl merchantability and fitness for a particular purpose. The software +dnl provided hereunder is on an "as is" basis, and Richard Coleman and the +dnl Zsh Development Group have no obligation to provide maintenance, +dnl support, updates, enhancements, or modifications. +dnl + +dnl +dnl zsh_64_BIT_TYPE +dnl Check whether the first argument works as a 64-bit type. +dnl If there is a non-zero third argument, we just assume it works +dnl when we're cross compiling. This is to allow a type to be +dnl specified directly as --enable-lfs="long long". +dnl Sets the variable given in the second argument to the first argument +dnl if the test worked, `no' otherwise. Be careful testing this, as it +dnl may produce two words `long long' on an unquoted substitution. +dnl Also check that the compiler does not mind it being cast to int. +dnl This macro does not produce messages as it may be run several times +dnl before finding the right type. +dnl + +AC_DEFUN(zsh_64_BIT_TYPE, +[AC_TRY_RUN([ +#ifdef HAVE_SYS_TYPES_H +#include +#endif + +main() +{ + $1 foo = 0; + int bar = (int) foo; + return sizeof($1) != 8; +} +], $2="$1", $2=no, + [if test x$3 != x ; then + $2="$1" + else + $2=no + fi]) +]) + + +dnl +dnl zsh_SHARED_FUNCTION +dnl +dnl This is just a frontend to zsh_SHARED_SYMBOL +dnl +dnl Usage: zsh_SHARED_FUNCTION(name[,rettype[,paramtype]]) +dnl + +AC_DEFUN(zsh_SHARED_FUNCTION, +[zsh_SHARED_SYMBOL($1, ifelse([$2], ,[int ],[$2]) $1 [(]ifelse([$3], ,[ ],[$3])[)], $1)]) + +dnl +dnl zsh_SHARED_VARIABLE +dnl +dnl This is just a frontend to zsh_SHARED_SYMBOL +dnl +dnl Usage: zsh_SHARED_VARIABLE(name[,type]) +dnl + +AC_DEFUN(zsh_SHARED_VARIABLE, +[zsh_SHARED_SYMBOL($1, ifelse([$2], ,[int ],[$2]) $1, [&$1])]) + +dnl +dnl zsh_SHARED_SYMBOL +dnl Check whether symbol is available in static or shared library +dnl +dnl On some systems, static modifiable library symbols (such as environ) +dnl may appear only in statically linked libraries. If this is the case, +dnl then two shared libraries that reference the same symbol, each linked +dnl with the static library, could be given distinct copies of the symbol. +dnl +dnl Usage: zsh_SHARED_SYMBOL(name,declaration,address) +dnl Sets zsh_cv_shared_$1 cache variable to yes/no +dnl + +AC_DEFUN(zsh_SHARED_SYMBOL, +[AC_CACHE_CHECK([if $1 is available in shared libraries], +zsh_cv_shared_$1, +[if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ +else + us= +fi +echo ' +void *zsh_getaddr1() +{ +#ifdef __CYGWIN__ + __attribute__((__dllimport__)) +#endif + extern $2; + return $3; +}; +' > conftest1.c +sed 's/zsh_getaddr1/zsh_getaddr2/' < conftest1.c > conftest2.c +if AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&AC_FD_CC) && +AC_TRY_COMMAND($DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS 1>&AC_FD_CC) && +AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest2.c 1>&AC_FD_CC) && +AC_TRY_COMMAND($DLLD -o conftest2.$DL_EXT $LDFLAGS $DLLDFLAGS conftest2.o $LIBS 1>&AC_FD_CC); then + AC_TRY_RUN([ +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +main() +{ + void *handle1, *handle2; + void *(*zsh_getaddr1)(), *(*zsh_getaddr2)(); + void *sym1, *sym2; + handle1 = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle1) exit(1); + handle2 = dlopen("./conftest2.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle2) exit(1); + zsh_getaddr1 = (void *(*)()) dlsym(handle1, "${us}zsh_getaddr1"); + zsh_getaddr2 = (void *(*)()) dlsym(handle2, "${us}zsh_getaddr2"); + sym1 = zsh_getaddr1(); + sym2 = zsh_getaddr2(); + if(!sym1 || !sym2) exit(1); + if(sym1 != sym2) exit(1); + dlclose(handle1); + handle1 = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle1) exit(1); + zsh_getaddr1 = (void *(*)()) dlsym(handle1, "${us}zsh_getaddr1"); + sym1 = zsh_getaddr1(); + if(!sym1) exit(1); + if(sym1 != sym2) exit(1); + exit(0); +} +], [zsh_cv_shared_$1=yes], +[zsh_cv_shared_$1=no], +[zsh_cv_shared_$1=no] +) +else + zsh_cv_shared_$1=no +fi +]) +]) + +dnl +dnl zsh_SYS_DYNAMIC_CLASH +dnl Check whether symbol name clashes in shared libraries are acceptable. +dnl + +AC_DEFUN(zsh_SYS_DYNAMIC_CLASH, +[AC_CACHE_CHECK([if name clashes in shared objects are OK], +zsh_cv_sys_dynamic_clash_ok, +[if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ +else + us= +fi +echo 'int fred () { return 42; }' > conftest1.c +echo 'int fred () { return 69; }' > conftest2.c +if AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&AC_FD_CC) && +AC_TRY_COMMAND($DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS 1>&AC_FD_CC) && +AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest2.c 1>&AC_FD_CC) && +AC_TRY_COMMAND($DLLD -o conftest2.$DL_EXT $LDFLAGS $DLLDFLAGS conftest2.o $LIBS 1>&AC_FD_CC); then + AC_TRY_RUN([ +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + + +main() +{ + void *handle1, *handle2; + int (*fred1)(), (*fred2)(); + handle1 = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle1) exit(1); + handle2 = dlopen("./conftest2.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle2) exit(1); + fred1 = (int (*)()) dlsym(handle1, "${us}fred"); + fred2 = (int (*)()) dlsym(handle2, "${us}fred"); + if(!fred1 || !fred2) exit(1); + exit((*fred1)() != 42 || (*fred2)() != 69); +} +], [zsh_cv_sys_dynamic_clash_ok=yes], +[zsh_cv_sys_dynamic_clash_ok=no], +[zsh_cv_sys_dynamic_clash_ok=no] +) +else + zsh_cv_sys_dynamic_clash_ok=no +fi +]) +if test "$zsh_cv_sys_dynamic_clash_ok" = yes; then + AC_DEFINE(DYNAMIC_NAME_CLASH_OK) +fi +]) + +dnl +dnl zsh_SYS_DYNAMIC_GLOBAL +dnl Check whether symbols in one dynamically loaded library are +dnl available to another dynamically loaded library. +dnl + +AC_DEFUN(zsh_SYS_DYNAMIC_GLOBAL, +[AC_CACHE_CHECK([for working RTLD_GLOBAL], +zsh_cv_sys_dynamic_rtld_global, +[if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ +else + us= +fi +echo 'int fred () { return 42; }' > conftest1.c +echo 'extern int fred(); int barney () { return fred() + 27; }' > conftest2.c +if AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&AC_FD_CC) && +AC_TRY_COMMAND($DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS 1>&AC_FD_CC) && +AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest2.c 1>&AC_FD_CC) && +AC_TRY_COMMAND($DLLD -o conftest2.$DL_EXT $LDFLAGS $DLLDFLAGS conftest2.o $LIBS 1>&AC_FD_CC); then + AC_TRY_RUN([ +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +main() +{ + void *handle; + int (*barneysym)(); + handle = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle) exit(1); + handle = dlopen("./conftest2.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle) exit(1); + barneysym = (int (*)()) dlsym(handle, "${us}barney"); + if(!barneysym) exit(1); + exit((*barneysym)() != 69); +} +], [zsh_cv_sys_dynamic_rtld_global=yes], +[zsh_cv_sys_dynamic_rtld_global=no], +[zsh_cv_sys_dynamic_rtld_global=no] +) +else + zsh_cv_sys_dynamic_rtld_global=no +fi +]) +]) + +dnl +dnl zsh_SYS_DYNAMIC_EXECSYMS +dnl Check whether symbols in the executable are available to dynamically +dnl loaded libraries. +dnl + +AC_DEFUN(zsh_SYS_DYNAMIC_EXECSYMS, +[AC_CACHE_CHECK([whether symbols in the executable are available], +zsh_cv_sys_dynamic_execsyms, +[if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ +else + us= +fi +echo 'extern int fred(); int barney () { return fred() + 27; }' > conftest1.c +if AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&AC_FD_CC) && +AC_TRY_COMMAND($DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS 1>&AC_FD_CC); then + save_ldflags=$LDFLAGS + LDFLAGS="$LDFLAGS $EXTRA_LDFLAGS" + AC_TRY_RUN([ +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +main() +{ + void *handle; + int (*barneysym)(); + handle = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle) exit(1); + barneysym = (int (*)()) dlsym(handle, "${us}barney"); + if(!barneysym) exit(1); + exit((*barneysym)() != 69); +} + +int fred () { return 42; } +], [zsh_cv_sys_dynamic_execsyms=yes], +[zsh_cv_sys_dynamic_execsyms=no], +[zsh_cv_sys_dynamic_execsyms=no] +) + LDFLAGS=$save_ldflags +else + zsh_cv_sys_dynamic_execsyms=no +fi +]) +]) + +dnl +dnl zsh_SYS_DYNAMIC_STRIP_EXE +dnl Check whether it is safe to strip executables. +dnl + +AC_DEFUN(zsh_SYS_DYNAMIC_STRIP_EXE, +[AC_REQUIRE([zsh_SYS_DYNAMIC_EXECSYMS]) +AC_CACHE_CHECK([whether executables can be stripped], +zsh_cv_sys_dynamic_strip_exe, +[if test "$zsh_cv_sys_dynamic_execsyms" != yes; then + zsh_cv_sys_dynamic_strip_exe=yes +elif + if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ + else + us= + fi + echo 'extern int fred(); int barney() { return fred() + 27; }' > conftest1.c + AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&AC_FD_CC) && + AC_TRY_COMMAND($DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS 1>&AC_FD_CC); then + save_ldflags=$LDFLAGS + LDFLAGS="$LDFLAGS $EXTRA_LDFLAGS -s" + AC_TRY_RUN([ +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +main() +{ + void *handle; + int (*barneysym)(); + handle = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle) exit(1); + barneysym = (int (*)()) dlsym(handle, "${us}barney"); + if(!barneysym) exit(1); + exit((*barneysym)() != 69); +} + +int fred () { return 42; } +], [zsh_cv_sys_dynamic_strip_exe=yes], +[zsh_cv_sys_dynamic_strip_exe=no], +[zsh_cv_sys_dynamic_strip_exe=no] +) + LDFLAGS=$save_ldflags +else + zsh_cv_sys_dynamic_strip_exe=no +fi +]) +]) + +dnl +dnl zsh_SYS_DYNAMIC_STRIP_EXE +dnl Check whether it is safe to strip dynamically loaded libraries. +dnl + +AC_DEFUN(zsh_SYS_DYNAMIC_STRIP_LIB, +[AC_CACHE_CHECK([whether libraries can be stripped], +zsh_cv_sys_dynamic_strip_lib, +[if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ +else + us= +fi +echo 'int fred () { return 42; }' > conftest1.c +if AC_TRY_COMMAND($CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&AC_FD_CC) && +AC_TRY_COMMAND($DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS -s conftest1.o $LIBS 1>&AC_FD_CC); then + AC_TRY_RUN([ +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +main() +{ + void *handle; + int (*fredsym)(); + handle = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle) exit(1); + fredsym = (int (*)()) dlsym(handle, "${us}fred"); + if(!fredsym) exit(1); + exit((*fredsym)() != 42); +} +], [zsh_cv_sys_dynamic_strip_lib=yes], +[zsh_cv_sys_dynamic_strip_lib=no], +[zsh_cv_sys_dynamic_strip_lib=no] +) +else + zsh_cv_sys_dynamic_strip_lib=no +fi +]) +]) + +dnl +dnl zsh_PATH_UTMP(filename) +dnl Search for a specified utmp-type file. +dnl + +AC_DEFUN(zsh_PATH_UTMP, +[AC_CACHE_CHECK([for $1 file], [zsh_cv_path_$1], +[for dir in /etc /usr/etc /var/adm /usr/adm /var/run /var/log ./conftest; do + zsh_cv_path_$1=${dir}/$1 + test -f $zsh_cv_path_$1 && break + zsh_cv_path_$1=no +done +]) +AH_TEMPLATE([PATH_]translit($1, [a-z], [A-Z])[_FILE], +[Define to be location of ]$1[ file.]) +if test $zsh_cv_path_$1 != no; then + AC_DEFINE_UNQUOTED([PATH_]translit($1, [a-z], [A-Z])[_FILE], + "$zsh_cv_path_$1") +fi +]) + +dnl +dnl zsh_TYPE_EXISTS(#includes, type name) +dnl Check whether a specified type exists. +dnl + +AC_DEFUN(zsh_TYPE_EXISTS, +[AC_CACHE_CHECK([for $2], [zsh_cv_type_exists_[]translit($2, [ ], [_])], +[AC_TRY_COMPILE([$1], [$2 testvar;], +[zsh_cv_type_exists_[]translit($2, [ ], [_])=yes], +[zsh_cv_type_exists_[]translit($2, [ ], [_])=no]) +]) +AH_TEMPLATE([HAVE_]translit($2, [ a-z], [_A-Z]), +[Define to 1 if ]$2[ is defined by a system header]) +if test $zsh_cv_type_exists_[]translit($2, [ ], [_]) = yes; then + AC_DEFINE([HAVE_]translit($2, [ a-z], [_A-Z])) +fi +]) + +dnl +dnl zsh_STRUCT_MEMBER(#includes, type name, member name) +dnl Check whether a specified aggregate type exists and contains +dnl a specified member. +dnl + +AC_DEFUN(zsh_STRUCT_MEMBER, +[AC_CACHE_CHECK([for $3 in $2], [zsh_cv_struct_member_[]translit($2, [ ], [_])_$3], +[AC_TRY_COMPILE([$1], [$2 testvar; testvar.$3;], +[zsh_cv_struct_member_[]translit($2, [ ], [_])_$3=yes], +[zsh_cv_struct_member_[]translit($2, [ ], [_])_$3=no]) +]) +AH_TEMPLATE([HAVE_]translit($2_$3, [ a-z], [_A-Z]), +[Define if your system's ]$2[ has a member named ]$3[.]) +if test $zsh_cv_struct_member_[]translit($2, [ ], [_])_$3 = yes; then + AC_DEFINE([HAVE_]translit($2_$3, [ a-z], [_A-Z])) +fi +]) + +dnl +dnl zsh_ARG_PROGRAM +dnl Handle AC_ARG_PROGRAM substitutions into other zsh configure macros. +dnl After processing this macro, the configure script may refer to +dnl and $tzsh_name, and @tzsh@ is defined for make substitutions. +dnl + +AC_DEFUN(zsh_ARG_PROGRAM, +[AC_ARG_PROGRAM +# Un-double any \ or $ (doubled by AC_ARG_PROGRAM). +cat <<\EOF_SED > conftestsed +s,\\\\,\\,g; s,\$\$,$,g +EOF_SED +zsh_transform_name=`echo "${program_transform_name}" | sed -f conftestsed` +rm -f conftestsed +tzsh_name=`echo zsh | sed -e "${zsh_transform_name}"` +# Double any \ or $ in the transformed name that results. +cat <<\EOF_SED >> conftestsed +s,\\,\\\\,g; s,\$,$$,g +EOF_SED +tzsh=`echo ${tzsh_name} | sed -f conftestsed` +rm -f conftestsed +AC_SUBST(tzsh)dnl +]) + +AC_DEFUN(zsh_COMPILE_FLAGS, + [AC_ARG_ENABLE(cppflags, + AC_HELP_STRING([--enable-cppflags=...], [specify C preprocessor flags]), + if test "$enableval" = "yes" + then CPPFLAGS="$1" + else CPPFLAGS="$enable_cppflags" + fi) + AC_ARG_ENABLE(cflags, + AC_HELP_STRING([--enable-cflags=...], [specify C compiler flags]), + if test "$enableval" = "yes" + then CFLAGS="$2" + else CFLAGS="$enable_cflags" + fi) + AC_ARG_ENABLE(ldflags, + AC_HELP_STRING([--enable-ldflags=...], [specify linker flags]), + if test "$enableval" = "yes" + then LDFLAGS="$3" + else LDFLAGS="$enable_ldflags" + fi) + AC_ARG_ENABLE(libs, + AC_HELP_STRING([--enable-libs=...], [specify link libraries]), + if test "$enableval" = "yes" + then LIBS="$4" + else LIBS="$enable_libs" + fi)]) + +dnl +dnl zsh_CHECK_SOCKLEN_T +dnl +dnl check type of third argument of some network functions; currently +dnl tested are size_t *, unsigned long *, int *. +dnl call the result ZSOCKLEN_T since some systems have SOCKLEN_T already +dnl +AC_DEFUN([zsh_CHECK_SOCKLEN_T],[ + AC_CACHE_CHECK( + [base type of the third argument to accept], + [zsh_cv_type_socklen_t], + [zsh_cv_type_socklen_t= + for zsh_type in socklen_t int "unsigned long" size_t ; do + AC_TRY_COMPILE( + [#include + #include ], + [extern int accept (int, struct sockaddr *, $zsh_type *);], + [zsh_cv_type_socklen_t="$zsh_type"; break], + [] + ) + done + if test -z "$zsh_cv_type_socklen_t"; then + zsh_cv_type_socklen_t=int + fi] + ) + AC_DEFINE_UNQUOTED([ZSOCKLEN_T], [$zsh_cv_type_socklen_t], + [Define to the base type of the third argument of accept])] +) + +dnl Check for limit $1 e.g. RLIMIT_RSS. +AC_DEFUN(zsh_LIMIT_PRESENT, +[AH_TEMPLATE([HAVE_]$1, +[Define to 1 if ]$1[ is present (whether or not as a macro).]) +AC_CACHE_CHECK([for limit $1], +zsh_cv_have_$1, +[AC_TRY_COMPILE([ +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include ], +[$1], + zsh_cv_have_$1=yes, + zsh_cv_have_$1=no)]) + +if test $zsh_cv_have_$1 = yes; then + AC_DEFINE(HAVE_$1) +fi]) + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/config.guess b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/config.guess new file mode 100755 index 00000000..dc84c68e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/config.guess @@ -0,0 +1,1501 @@ +#! /bin/sh +# Attempt to guess a canonical system name. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 +# Free Software Foundation, Inc. + +timestamp='2009-11-20' + +# This file is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, but +# WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU +# General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA +# 02110-1301, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + + +# Originally written by Per Bothner. Please send patches (context +# diff format) to and include a ChangeLog +# entry. +# +# This script attempts to guess a canonical system name similar to +# config.sub. If it succeeds, it prints the system name on stdout, and +# exits with 0. Otherwise, it exits with 1. +# +# You can get the latest version of this script from: +# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.guess;hb=HEAD + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] + +Output the configuration name of the system \`$me' is run on. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.guess ($timestamp) + +Originally written by Per Bothner. +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, +2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" >&2 + exit 1 ;; + * ) + break ;; + esac +done + +if test $# != 0; then + echo "$me: too many arguments$help" >&2 + exit 1 +fi + +trap 'exit 1' 1 2 15 + +# CC_FOR_BUILD -- compiler used by this script. Note that the use of a +# compiler to aid in system detection is discouraged as it requires +# temporary files to be created and, as you can see below, it is a +# headache to deal with in a portable fashion. + +# Historically, `CC_FOR_BUILD' used to be named `HOST_CC'. We still +# use `HOST_CC' if defined, but it is deprecated. + +# Portable tmp directory creation inspired by the Autoconf team. + +set_cc_for_build=' +trap "exitcode=\$?; (rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null) && exit \$exitcode" 0 ; +trap "rm -f \$tmpfiles 2>/dev/null; rmdir \$tmp 2>/dev/null; exit 1" 1 2 13 15 ; +: ${TMPDIR=/tmp} ; + { tmp=`(umask 077 && mktemp -d "$TMPDIR/cgXXXXXX") 2>/dev/null` && test -n "$tmp" && test -d "$tmp" ; } || + { test -n "$RANDOM" && tmp=$TMPDIR/cg$$-$RANDOM && (umask 077 && mkdir $tmp) ; } || + { tmp=$TMPDIR/cg-$$ && (umask 077 && mkdir $tmp) && echo "Warning: creating insecure temp directory" >&2 ; } || + { echo "$me: cannot create a temporary directory in $TMPDIR" >&2 ; exit 1 ; } ; +dummy=$tmp/dummy ; +tmpfiles="$dummy.c $dummy.o $dummy.rel $dummy" ; +case $CC_FOR_BUILD,$HOST_CC,$CC in + ,,) echo "int x;" > $dummy.c ; + for c in cc gcc c89 c99 ; do + if ($c -c -o $dummy.o $dummy.c) >/dev/null 2>&1 ; then + CC_FOR_BUILD="$c"; break ; + fi ; + done ; + if test x"$CC_FOR_BUILD" = x ; then + CC_FOR_BUILD=no_compiler_found ; + fi + ;; + ,,*) CC_FOR_BUILD=$CC ;; + ,*,*) CC_FOR_BUILD=$HOST_CC ;; +esac ; set_cc_for_build= ;' + +# This is needed to find uname on a Pyramid OSx when run in the BSD universe. +# (ghazi@noc.rutgers.edu 1994-08-24) +if (test -f /.attbin/uname) >/dev/null 2>&1 ; then + PATH=$PATH:/.attbin ; export PATH +fi + +UNAME_MACHINE=`(uname -m) 2>/dev/null` || UNAME_MACHINE=unknown +UNAME_RELEASE=`(uname -r) 2>/dev/null` || UNAME_RELEASE=unknown +UNAME_SYSTEM=`(uname -s) 2>/dev/null` || UNAME_SYSTEM=unknown +UNAME_VERSION=`(uname -v) 2>/dev/null` || UNAME_VERSION=unknown + +# Note: order is significant - the case branches are not exclusive. + +case "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" in + *:NetBSD:*:*) + # NetBSD (nbsd) targets should (where applicable) match one or + # more of the tupples: *-*-netbsdelf*, *-*-netbsdaout*, + # *-*-netbsdecoff* and *-*-netbsd*. For targets that recently + # switched to ELF, *-*-netbsd* would select the old + # object file format. This provides both forward + # compatibility and a consistent mechanism for selecting the + # object file format. + # + # Note: NetBSD doesn't particularly care about the vendor + # portion of the name. We always set it to "unknown". + sysctl="sysctl -n hw.machine_arch" + UNAME_MACHINE_ARCH=`(/sbin/$sysctl 2>/dev/null || \ + /usr/sbin/$sysctl 2>/dev/null || echo unknown)` + case "${UNAME_MACHINE_ARCH}" in + armeb) machine=armeb-unknown ;; + arm*) machine=arm-unknown ;; + sh3el) machine=shl-unknown ;; + sh3eb) machine=sh-unknown ;; + sh5el) machine=sh5le-unknown ;; + *) machine=${UNAME_MACHINE_ARCH}-unknown ;; + esac + # The Operating System including object format, if it has switched + # to ELF recently, or will in the future. + case "${UNAME_MACHINE_ARCH}" in + arm*|i386|m68k|ns32k|sh3*|sparc|vax) + eval $set_cc_for_build + if echo __ELF__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ELF__ + then + # Once all utilities can be ECOFF (netbsdecoff) or a.out (netbsdaout). + # Return netbsd for either. FIX? + os=netbsd + else + os=netbsdelf + fi + ;; + *) + os=netbsd + ;; + esac + # The OS release + # Debian GNU/NetBSD machines have a different userland, and + # thus, need a distinct triplet. However, they do not need + # kernel version information, so it can be replaced with a + # suitable tag, in the style of linux-gnu. + case "${UNAME_VERSION}" in + Debian*) + release='-gnu' + ;; + *) + release=`echo ${UNAME_RELEASE}|sed -e 's/[-_].*/\./'` + ;; + esac + # Since CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM: + # contains redundant information, the shorter form: + # CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM is used. + echo "${machine}-${os}${release}" + exit ;; + *:OpenBSD:*:*) + UNAME_MACHINE_ARCH=`arch | sed 's/OpenBSD.//'` + echo ${UNAME_MACHINE_ARCH}-unknown-openbsd${UNAME_RELEASE} + exit ;; + *:ekkoBSD:*:*) + echo ${UNAME_MACHINE}-unknown-ekkobsd${UNAME_RELEASE} + exit ;; + *:SolidBSD:*:*) + echo ${UNAME_MACHINE}-unknown-solidbsd${UNAME_RELEASE} + exit ;; + macppc:MirBSD:*:*) + echo powerpc-unknown-mirbsd${UNAME_RELEASE} + exit ;; + *:MirBSD:*:*) + echo ${UNAME_MACHINE}-unknown-mirbsd${UNAME_RELEASE} + exit ;; + alpha:OSF1:*:*) + case $UNAME_RELEASE in + *4.0) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $3}'` + ;; + *5.*) + UNAME_RELEASE=`/usr/sbin/sizer -v | awk '{print $4}'` + ;; + esac + # According to Compaq, /usr/sbin/psrinfo has been available on + # OSF/1 and Tru64 systems produced since 1995. I hope that + # covers most systems running today. This code pipes the CPU + # types through head -n 1, so we only detect the type of CPU 0. + ALPHA_CPU_TYPE=`/usr/sbin/psrinfo -v | sed -n -e 's/^ The alpha \(.*\) processor.*$/\1/p' | head -n 1` + case "$ALPHA_CPU_TYPE" in + "EV4 (21064)") + UNAME_MACHINE="alpha" ;; + "EV4.5 (21064)") + UNAME_MACHINE="alpha" ;; + "LCA4 (21066/21068)") + UNAME_MACHINE="alpha" ;; + "EV5 (21164)") + UNAME_MACHINE="alphaev5" ;; + "EV5.6 (21164A)") + UNAME_MACHINE="alphaev56" ;; + "EV5.6 (21164PC)") + UNAME_MACHINE="alphapca56" ;; + "EV5.7 (21164PC)") + UNAME_MACHINE="alphapca57" ;; + "EV6 (21264)") + UNAME_MACHINE="alphaev6" ;; + "EV6.7 (21264A)") + UNAME_MACHINE="alphaev67" ;; + "EV6.8CB (21264C)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8AL (21264B)") + UNAME_MACHINE="alphaev68" ;; + "EV6.8CX (21264D)") + UNAME_MACHINE="alphaev68" ;; + "EV6.9A (21264/EV69A)") + UNAME_MACHINE="alphaev69" ;; + "EV7 (21364)") + UNAME_MACHINE="alphaev7" ;; + "EV7.9 (21364A)") + UNAME_MACHINE="alphaev79" ;; + esac + # A Pn.n version is a patched version. + # A Vn.n version is a released version. + # A Tn.n version is a released field test version. + # A Xn.n version is an unreleased experimental baselevel. + # 1.2 uses "1.2" for uname -r. + echo ${UNAME_MACHINE}-dec-osf`echo ${UNAME_RELEASE} | sed -e 's/^[PVTX]//' | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + exit ;; + Alpha\ *:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # Should we change UNAME_MACHINE based on the output of uname instead + # of the specific Alpha model? + echo alpha-pc-interix + exit ;; + 21064:Windows_NT:50:3) + echo alpha-dec-winnt3.5 + exit ;; + Amiga*:UNIX_System_V:4.0:*) + echo m68k-unknown-sysv4 + exit ;; + *:[Aa]miga[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-amigaos + exit ;; + *:[Mm]orph[Oo][Ss]:*:*) + echo ${UNAME_MACHINE}-unknown-morphos + exit ;; + *:OS/390:*:*) + echo i370-ibm-openedition + exit ;; + *:z/VM:*:*) + echo s390-ibm-zvmoe + exit ;; + *:OS400:*:*) + echo powerpc-ibm-os400 + exit ;; + arm:RISC*:1.[012]*:*|arm:riscix:1.[012]*:*) + echo arm-acorn-riscix${UNAME_RELEASE} + exit ;; + arm:riscos:*:*|arm:RISCOS:*:*) + echo arm-unknown-riscos + exit ;; + SR2?01:HI-UX/MPP:*:* | SR8000:HI-UX/MPP:*:*) + echo hppa1.1-hitachi-hiuxmpp + exit ;; + Pyramid*:OSx*:*:* | MIS*:OSx*:*:* | MIS*:SMP_DC-OSx*:*:*) + # akee@wpdis03.wpafb.af.mil (Earle F. Ake) contributed MIS and NILE. + if test "`(/bin/universe) 2>/dev/null`" = att ; then + echo pyramid-pyramid-sysv3 + else + echo pyramid-pyramid-bsd + fi + exit ;; + NILE*:*:*:dcosx) + echo pyramid-pyramid-svr4 + exit ;; + DRS?6000:unix:4.0:6*) + echo sparc-icl-nx6 + exit ;; + DRS?6000:UNIX_SV:4.2*:7* | DRS?6000:isis:4.2*:7*) + case `/usr/bin/uname -p` in + sparc) echo sparc-icl-nx7; exit ;; + esac ;; + s390x:SunOS:*:*) + echo ${UNAME_MACHINE}-ibm-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4H:SunOS:5.*:*) + echo sparc-hal-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:5.*:* | tadpole*:SunOS:5.*:*) + echo sparc-sun-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + i86pc:AuroraUX:5.*:* | i86xen:AuroraUX:5.*:*) + echo i386-pc-auroraux${UNAME_RELEASE} + exit ;; + i86pc:SunOS:5.*:* | i86xen:SunOS:5.*:*) + eval $set_cc_for_build + SUN_ARCH="i386" + # If there is a compiler, see if it is configured for 64-bit objects. + # Note that the Sun cc does not turn __LP64__ into 1 like gcc does. + # This test works for both compilers. + if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then + if (echo '#ifdef __amd64'; echo IS_64BIT_ARCH; echo '#endif') | \ + (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null + then + SUN_ARCH="x86_64" + fi + fi + echo ${SUN_ARCH}-pc-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:6*:*) + # According to config.sub, this is the proper way to canonicalize + # SunOS6. Hard to guess exactly what SunOS6 will be like, but + # it's likely to be more like Solaris than SunOS4. + echo sparc-sun-solaris3`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + sun4*:SunOS:*:*) + case "`/usr/bin/arch -k`" in + Series*|S4*) + UNAME_RELEASE=`uname -v` + ;; + esac + # Japanese Language versions have a version number like `4.1.3-JL'. + echo sparc-sun-sunos`echo ${UNAME_RELEASE}|sed -e 's/-/_/'` + exit ;; + sun3*:SunOS:*:*) + echo m68k-sun-sunos${UNAME_RELEASE} + exit ;; + sun*:*:4.2BSD:*) + UNAME_RELEASE=`(sed 1q /etc/motd | awk '{print substr($5,1,3)}') 2>/dev/null` + test "x${UNAME_RELEASE}" = "x" && UNAME_RELEASE=3 + case "`/bin/arch`" in + sun3) + echo m68k-sun-sunos${UNAME_RELEASE} + ;; + sun4) + echo sparc-sun-sunos${UNAME_RELEASE} + ;; + esac + exit ;; + aushp:SunOS:*:*) + echo sparc-auspex-sunos${UNAME_RELEASE} + exit ;; + # The situation for MiNT is a little confusing. The machine name + # can be virtually everything (everything which is not + # "atarist" or "atariste" at least should have a processor + # > m68000). The system name ranges from "MiNT" over "FreeMiNT" + # to the lowercase version "mint" (or "freemint"). Finally + # the system name "TOS" denotes a system which is actually not + # MiNT. But MiNT is downward compatible to TOS, so this should + # be no problem. + atarist[e]:*MiNT:*:* | atarist[e]:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + atari*:*MiNT:*:* | atari*:*mint:*:* | atarist[e]:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + *falcon*:*MiNT:*:* | *falcon*:*mint:*:* | *falcon*:*TOS:*:*) + echo m68k-atari-mint${UNAME_RELEASE} + exit ;; + milan*:*MiNT:*:* | milan*:*mint:*:* | *milan*:*TOS:*:*) + echo m68k-milan-mint${UNAME_RELEASE} + exit ;; + hades*:*MiNT:*:* | hades*:*mint:*:* | *hades*:*TOS:*:*) + echo m68k-hades-mint${UNAME_RELEASE} + exit ;; + *:*MiNT:*:* | *:*mint:*:* | *:*TOS:*:*) + echo m68k-unknown-mint${UNAME_RELEASE} + exit ;; + m68k:machten:*:*) + echo m68k-apple-machten${UNAME_RELEASE} + exit ;; + powerpc:machten:*:*) + echo powerpc-apple-machten${UNAME_RELEASE} + exit ;; + RISC*:Mach:*:*) + echo mips-dec-mach_bsd4.3 + exit ;; + RISC*:ULTRIX:*:*) + echo mips-dec-ultrix${UNAME_RELEASE} + exit ;; + VAX*:ULTRIX*:*:*) + echo vax-dec-ultrix${UNAME_RELEASE} + exit ;; + 2020:CLIX:*:* | 2430:CLIX:*:*) + echo clipper-intergraph-clix${UNAME_RELEASE} + exit ;; + mips:*:*:UMIPS | mips:*:*:RISCos) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c +#ifdef __cplusplus +#include /* for printf() prototype */ + int main (int argc, char *argv[]) { +#else + int main (argc, argv) int argc; char *argv[]; { +#endif + #if defined (host_mips) && defined (MIPSEB) + #if defined (SYSTYPE_SYSV) + printf ("mips-mips-riscos%ssysv\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_SVR4) + printf ("mips-mips-riscos%ssvr4\n", argv[1]); exit (0); + #endif + #if defined (SYSTYPE_BSD43) || defined(SYSTYPE_BSD) + printf ("mips-mips-riscos%sbsd\n", argv[1]); exit (0); + #endif + #endif + exit (-1); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && + dummyarg=`echo "${UNAME_RELEASE}" | sed -n 's/\([0-9]*\).*/\1/p'` && + SYSTEM_NAME=`$dummy $dummyarg` && + { echo "$SYSTEM_NAME"; exit; } + echo mips-mips-riscos${UNAME_RELEASE} + exit ;; + Motorola:PowerMAX_OS:*:*) + echo powerpc-motorola-powermax + exit ;; + Motorola:*:4.3:PL8-*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:*:*:PowerMAX_OS | Synergy:PowerMAX_OS:*:*) + echo powerpc-harris-powermax + exit ;; + Night_Hawk:Power_UNIX:*:*) + echo powerpc-harris-powerunix + exit ;; + m88k:CX/UX:7*:*) + echo m88k-harris-cxux7 + exit ;; + m88k:*:4*:R4*) + echo m88k-motorola-sysv4 + exit ;; + m88k:*:3*:R3*) + echo m88k-motorola-sysv3 + exit ;; + AViiON:dgux:*:*) + # DG/UX returns AViiON for all architectures + UNAME_PROCESSOR=`/usr/bin/uname -p` + if [ $UNAME_PROCESSOR = mc88100 ] || [ $UNAME_PROCESSOR = mc88110 ] + then + if [ ${TARGET_BINARY_INTERFACE}x = m88kdguxelfx ] || \ + [ ${TARGET_BINARY_INTERFACE}x = x ] + then + echo m88k-dg-dgux${UNAME_RELEASE} + else + echo m88k-dg-dguxbcs${UNAME_RELEASE} + fi + else + echo i586-dg-dgux${UNAME_RELEASE} + fi + exit ;; + M88*:DolphinOS:*:*) # DolphinOS (SVR3) + echo m88k-dolphin-sysv3 + exit ;; + M88*:*:R3*:*) + # Delta 88k system running SVR3 + echo m88k-motorola-sysv3 + exit ;; + XD88*:*:*:*) # Tektronix XD88 system running UTekV (SVR3) + echo m88k-tektronix-sysv3 + exit ;; + Tek43[0-9][0-9]:UTek:*:*) # Tektronix 4300 system running UTek (BSD) + echo m68k-tektronix-bsd + exit ;; + *:IRIX*:*:*) + echo mips-sgi-irix`echo ${UNAME_RELEASE}|sed -e 's/-/_/g'` + exit ;; + ????????:AIX?:[12].1:2) # AIX 2.2.1 or AIX 2.1.1 is RT/PC AIX. + echo romp-ibm-aix # uname -m gives an 8 hex-code CPU id + exit ;; # Note that: echo "'`uname -s`'" gives 'AIX ' + i*86:AIX:*:*) + echo i386-ibm-aix + exit ;; + ia64:AIX:*:*) + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${UNAME_MACHINE}-ibm-aix${IBM_REV} + exit ;; + *:AIX:2:3) + if grep bos325 /usr/include/stdio.h >/dev/null 2>&1; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + + main() + { + if (!__power_pc()) + exit(1); + puts("powerpc-ibm-aix3.2.5"); + exit(0); + } +EOF + if $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` + then + echo "$SYSTEM_NAME" + else + echo rs6000-ibm-aix3.2.5 + fi + elif grep bos324 /usr/include/stdio.h >/dev/null 2>&1; then + echo rs6000-ibm-aix3.2.4 + else + echo rs6000-ibm-aix3.2 + fi + exit ;; + *:AIX:*:[456]) + IBM_CPU_ID=`/usr/sbin/lsdev -C -c processor -S available | sed 1q | awk '{ print $1 }'` + if /usr/sbin/lsattr -El ${IBM_CPU_ID} | grep ' POWER' >/dev/null 2>&1; then + IBM_ARCH=rs6000 + else + IBM_ARCH=powerpc + fi + if [ -x /usr/bin/oslevel ] ; then + IBM_REV=`/usr/bin/oslevel` + else + IBM_REV=${UNAME_VERSION}.${UNAME_RELEASE} + fi + echo ${IBM_ARCH}-ibm-aix${IBM_REV} + exit ;; + *:AIX:*:*) + echo rs6000-ibm-aix + exit ;; + ibmrt:4.4BSD:*|romp-ibm:BSD:*) + echo romp-ibm-bsd4.4 + exit ;; + ibmrt:*BSD:*|romp-ibm:BSD:*) # covers RT/PC BSD and + echo romp-ibm-bsd${UNAME_RELEASE} # 4.3 with uname added to + exit ;; # report: romp-ibm BSD 4.3 + *:BOSX:*:*) + echo rs6000-bull-bosx + exit ;; + DPX/2?00:B.O.S.:*:*) + echo m68k-bull-sysv3 + exit ;; + 9000/[34]??:4.3bsd:1.*:*) + echo m68k-hp-bsd + exit ;; + hp300:4.4BSD:*:* | 9000/[34]??:4.3bsd:2.*:*) + echo m68k-hp-bsd4.4 + exit ;; + 9000/[34678]??:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + case "${UNAME_MACHINE}" in + 9000/31? ) HP_ARCH=m68000 ;; + 9000/[34]?? ) HP_ARCH=m68k ;; + 9000/[678][0-9][0-9]) + if [ -x /usr/bin/getconf ]; then + sc_cpu_version=`/usr/bin/getconf SC_CPU_VERSION 2>/dev/null` + sc_kernel_bits=`/usr/bin/getconf SC_KERNEL_BITS 2>/dev/null` + case "${sc_cpu_version}" in + 523) HP_ARCH="hppa1.0" ;; # CPU_PA_RISC1_0 + 528) HP_ARCH="hppa1.1" ;; # CPU_PA_RISC1_1 + 532) # CPU_PA_RISC2_0 + case "${sc_kernel_bits}" in + 32) HP_ARCH="hppa2.0n" ;; + 64) HP_ARCH="hppa2.0w" ;; + '') HP_ARCH="hppa2.0" ;; # HP-UX 10.20 + esac ;; + esac + fi + if [ "${HP_ARCH}" = "" ]; then + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + + #define _HPUX_SOURCE + #include + #include + + int main () + { + #if defined(_SC_KERNEL_BITS) + long bits = sysconf(_SC_KERNEL_BITS); + #endif + long cpu = sysconf (_SC_CPU_VERSION); + + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1"); break; + case CPU_PA_RISC2_0: + #if defined(_SC_KERNEL_BITS) + switch (bits) + { + case 64: puts ("hppa2.0w"); break; + case 32: puts ("hppa2.0n"); break; + default: puts ("hppa2.0"); break; + } break; + #else /* !defined(_SC_KERNEL_BITS) */ + puts ("hppa2.0"); break; + #endif + default: puts ("hppa1.0"); break; + } + exit (0); + } +EOF + (CCOPTS= $CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null) && HP_ARCH=`$dummy` + test -z "$HP_ARCH" && HP_ARCH=hppa + fi ;; + esac + if [ ${HP_ARCH} = "hppa2.0w" ] + then + eval $set_cc_for_build + + # hppa2.0w-hp-hpux* has a 64-bit kernel and a compiler generating + # 32-bit code. hppa64-hp-hpux* has the same kernel and a compiler + # generating 64-bit code. GNU and HP use different nomenclature: + # + # $ CC_FOR_BUILD=cc ./config.guess + # => hppa2.0w-hp-hpux11.23 + # $ CC_FOR_BUILD="cc +DA2.0w" ./config.guess + # => hppa64-hp-hpux11.23 + + if echo __LP64__ | (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | + grep -q __LP64__ + then + HP_ARCH="hppa2.0w" + else + HP_ARCH="hppa64" + fi + fi + echo ${HP_ARCH}-hp-hpux${HPUX_REV} + exit ;; + ia64:HP-UX:*:*) + HPUX_REV=`echo ${UNAME_RELEASE}|sed -e 's/[^.]*.[0B]*//'` + echo ia64-hp-hpux${HPUX_REV} + exit ;; + 3050*:HI-UX:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #include + int + main () + { + long cpu = sysconf (_SC_CPU_VERSION); + /* The order matters, because CPU_IS_HP_MC68K erroneously returns + true for CPU_PA_RISC1_0. CPU_IS_PA_RISC returns correct + results, however. */ + if (CPU_IS_PA_RISC (cpu)) + { + switch (cpu) + { + case CPU_PA_RISC1_0: puts ("hppa1.0-hitachi-hiuxwe2"); break; + case CPU_PA_RISC1_1: puts ("hppa1.1-hitachi-hiuxwe2"); break; + case CPU_PA_RISC2_0: puts ("hppa2.0-hitachi-hiuxwe2"); break; + default: puts ("hppa-hitachi-hiuxwe2"); break; + } + } + else if (CPU_IS_HP_MC68K (cpu)) + puts ("m68k-hitachi-hiuxwe2"); + else puts ("unknown-hitachi-hiuxwe2"); + exit (0); + } +EOF + $CC_FOR_BUILD -o $dummy $dummy.c && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + echo unknown-hitachi-hiuxwe2 + exit ;; + 9000/7??:4.3bsd:*:* | 9000/8?[79]:4.3bsd:*:* ) + echo hppa1.1-hp-bsd + exit ;; + 9000/8??:4.3bsd:*:*) + echo hppa1.0-hp-bsd + exit ;; + *9??*:MPE/iX:*:* | *3000*:MPE/iX:*:*) + echo hppa1.0-hp-mpeix + exit ;; + hp7??:OSF1:*:* | hp8?[79]:OSF1:*:* ) + echo hppa1.1-hp-osf + exit ;; + hp8??:OSF1:*:*) + echo hppa1.0-hp-osf + exit ;; + i*86:OSF1:*:*) + if [ -x /usr/sbin/sysversion ] ; then + echo ${UNAME_MACHINE}-unknown-osf1mk + else + echo ${UNAME_MACHINE}-unknown-osf1 + fi + exit ;; + parisc*:Lites*:*:*) + echo hppa1.1-hp-lites + exit ;; + C1*:ConvexOS:*:* | convex:ConvexOS:C1*:*) + echo c1-convex-bsd + exit ;; + C2*:ConvexOS:*:* | convex:ConvexOS:C2*:*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + C34*:ConvexOS:*:* | convex:ConvexOS:C34*:*) + echo c34-convex-bsd + exit ;; + C38*:ConvexOS:*:* | convex:ConvexOS:C38*:*) + echo c38-convex-bsd + exit ;; + C4*:ConvexOS:*:* | convex:ConvexOS:C4*:*) + echo c4-convex-bsd + exit ;; + CRAY*Y-MP:*:*:*) + echo ymp-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*[A-Z]90:*:*:*) + echo ${UNAME_MACHINE}-cray-unicos${UNAME_RELEASE} \ + | sed -e 's/CRAY.*\([A-Z]90\)/\1/' \ + -e y/ABCDEFGHIJKLMNOPQRSTUVWXYZ/abcdefghijklmnopqrstuvwxyz/ \ + -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*TS:*:*:*) + echo t90-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*T3E:*:*:*) + echo alphaev5-cray-unicosmk${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + CRAY*SV1:*:*:*) + echo sv1-cray-unicos${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + *:UNICOS/mp:*:*) + echo craynv-cray-unicosmp${UNAME_RELEASE} | sed -e 's/\.[^.]*$/.X/' + exit ;; + F30[01]:UNIX_System_V:*:* | F700:UNIX_System_V:*:*) + FUJITSU_PROC=`uname -m | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz'` + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | sed -e 's/ /_/'` + echo "${FUJITSU_PROC}-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + 5000:UNIX_System_V:4.*:*) + FUJITSU_SYS=`uname -p | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/\///'` + FUJITSU_REL=`echo ${UNAME_RELEASE} | tr 'ABCDEFGHIJKLMNOPQRSTUVWXYZ' 'abcdefghijklmnopqrstuvwxyz' | sed -e 's/ /_/'` + echo "sparc-fujitsu-${FUJITSU_SYS}${FUJITSU_REL}" + exit ;; + i*86:BSD/386:*:* | i*86:BSD/OS:*:* | *:Ascend\ Embedded/OS:*:*) + echo ${UNAME_MACHINE}-pc-bsdi${UNAME_RELEASE} + exit ;; + sparc*:BSD/OS:*:*) + echo sparc-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:BSD/OS:*:*) + echo ${UNAME_MACHINE}-unknown-bsdi${UNAME_RELEASE} + exit ;; + *:FreeBSD:*:*) + case ${UNAME_MACHINE} in + pc98) + echo i386-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + amd64) + echo x86_64-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + *) + echo ${UNAME_MACHINE}-unknown-freebsd`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` ;; + esac + exit ;; + i*:CYGWIN*:*) + echo ${UNAME_MACHINE}-pc-cygwin + exit ;; + *:MINGW*:*) + echo ${UNAME_MACHINE}-pc-mingw32 + exit ;; + i*:windows32*:*) + # uname -m includes "-pc" on this system. + echo ${UNAME_MACHINE}-mingw32 + exit ;; + i*:PW*:*) + echo ${UNAME_MACHINE}-pc-pw32 + exit ;; + *:Interix*:*) + case ${UNAME_MACHINE} in + x86) + echo i586-pc-interix${UNAME_RELEASE} + exit ;; + authenticamd | genuineintel | EM64T) + echo x86_64-unknown-interix${UNAME_RELEASE} + exit ;; + IA64) + echo ia64-unknown-interix${UNAME_RELEASE} + exit ;; + esac ;; + [345]86:Windows_95:* | [345]86:Windows_98:* | [345]86:Windows_NT:*) + echo i${UNAME_MACHINE}-pc-mks + exit ;; + 8664:Windows_NT:*) + echo x86_64-pc-mks + exit ;; + i*:Windows_NT*:* | Pentium*:Windows_NT*:*) + # How do we know it's Interix rather than the generic POSIX subsystem? + # It also conflicts with pre-2.0 versions of AT&T UWIN. Should we + # UNAME_MACHINE based on the output of uname instead of i386? + echo i586-pc-interix + exit ;; + i*:UWIN*:*) + echo ${UNAME_MACHINE}-pc-uwin + exit ;; + amd64:CYGWIN*:*:* | x86_64:CYGWIN*:*:*) + echo x86_64-unknown-cygwin + exit ;; + p*:CYGWIN*:*) + echo powerpcle-unknown-cygwin + exit ;; + prep*:SunOS:5.*:*) + echo powerpcle-unknown-solaris2`echo ${UNAME_RELEASE}|sed -e 's/[^.]*//'` + exit ;; + *:GNU:*:*) + # the GNU system + echo `echo ${UNAME_MACHINE}|sed -e 's,[-/].*$,,'`-unknown-gnu`echo ${UNAME_RELEASE}|sed -e 's,/.*$,,'` + exit ;; + *:GNU/*:*:*) + # other systems with GNU libc and userland + echo ${UNAME_MACHINE}-unknown-`echo ${UNAME_SYSTEM} | sed 's,^[^/]*/,,' | tr '[A-Z]' '[a-z]'``echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'`-gnu + exit ;; + i*86:Minix:*:*) + echo ${UNAME_MACHINE}-pc-minix + exit ;; + alpha:Linux:*:*) + case `sed -n '/^cpu model/s/^.*: \(.*\)/\1/p' < /proc/cpuinfo` in + EV5) UNAME_MACHINE=alphaev5 ;; + EV56) UNAME_MACHINE=alphaev56 ;; + PCA56) UNAME_MACHINE=alphapca56 ;; + PCA57) UNAME_MACHINE=alphapca56 ;; + EV6) UNAME_MACHINE=alphaev6 ;; + EV67) UNAME_MACHINE=alphaev67 ;; + EV68*) UNAME_MACHINE=alphaev68 ;; + esac + objdump --private-headers /bin/sh | grep -q ld.so.1 + if test "$?" = 0 ; then LIBC="libc1" ; else LIBC="" ; fi + echo ${UNAME_MACHINE}-unknown-linux-gnu${LIBC} + exit ;; + arm*:Linux:*:*) + eval $set_cc_for_build + if echo __ARM_EABI__ | $CC_FOR_BUILD -E - 2>/dev/null \ + | grep -q __ARM_EABI__ + then + echo ${UNAME_MACHINE}-unknown-linux-gnu + else + echo ${UNAME_MACHINE}-unknown-linux-gnueabi + fi + exit ;; + avr32*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + cris:Linux:*:*) + echo cris-axis-linux-gnu + exit ;; + crisv32:Linux:*:*) + echo crisv32-axis-linux-gnu + exit ;; + frv:Linux:*:*) + echo frv-unknown-linux-gnu + exit ;; + i*86:Linux:*:*) + LIBC=gnu + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #ifdef __dietlibc__ + LIBC=dietlibc + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^LIBC'` + echo "${UNAME_MACHINE}-pc-linux-${LIBC}" + exit ;; + ia64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + m32r*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + m68*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + mips:Linux:*:* | mips64:Linux:*:*) + eval $set_cc_for_build + sed 's/^ //' << EOF >$dummy.c + #undef CPU + #undef ${UNAME_MACHINE} + #undef ${UNAME_MACHINE}el + #if defined(__MIPSEL__) || defined(__MIPSEL) || defined(_MIPSEL) || defined(MIPSEL) + CPU=${UNAME_MACHINE}el + #else + #if defined(__MIPSEB__) || defined(__MIPSEB) || defined(_MIPSEB) || defined(MIPSEB) + CPU=${UNAME_MACHINE} + #else + CPU= + #endif + #endif +EOF + eval `$CC_FOR_BUILD -E $dummy.c 2>/dev/null | grep '^CPU'` + test x"${CPU}" != x && { echo "${CPU}-unknown-linux-gnu"; exit; } + ;; + or32:Linux:*:*) + echo or32-unknown-linux-gnu + exit ;; + padre:Linux:*:*) + echo sparc-unknown-linux-gnu + exit ;; + parisc64:Linux:*:* | hppa64:Linux:*:*) + echo hppa64-unknown-linux-gnu + exit ;; + parisc:Linux:*:* | hppa:Linux:*:*) + # Look for CPU level + case `grep '^cpu[^a-z]*:' /proc/cpuinfo 2>/dev/null | cut -d' ' -f2` in + PA7*) echo hppa1.1-unknown-linux-gnu ;; + PA8*) echo hppa2.0-unknown-linux-gnu ;; + *) echo hppa-unknown-linux-gnu ;; + esac + exit ;; + ppc64:Linux:*:*) + echo powerpc64-unknown-linux-gnu + exit ;; + ppc:Linux:*:*) + echo powerpc-unknown-linux-gnu + exit ;; + s390:Linux:*:* | s390x:Linux:*:*) + echo ${UNAME_MACHINE}-ibm-linux + exit ;; + sh64*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + sh*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + sparc:Linux:*:* | sparc64:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + vax:Linux:*:*) + echo ${UNAME_MACHINE}-dec-linux-gnu + exit ;; + x86_64:Linux:*:*) + echo x86_64-unknown-linux-gnu + exit ;; + xtensa*:Linux:*:*) + echo ${UNAME_MACHINE}-unknown-linux-gnu + exit ;; + i*86:DYNIX/ptx:4*:*) + # ptx 4.0 does uname -s correctly, with DYNIX/ptx in there. + # earlier versions are messed up and put the nodename in both + # sysname and nodename. + echo i386-sequent-sysv4 + exit ;; + i*86:UNIX_SV:4.2MP:2.*) + # Unixware is an offshoot of SVR4, but it has its own version + # number series starting with 2... + # I am not positive that other SVR4 systems won't match this, + # I just have to hope. -- rms. + # Use sysv4.2uw... so that sysv4* matches it. + echo ${UNAME_MACHINE}-pc-sysv4.2uw${UNAME_VERSION} + exit ;; + i*86:OS/2:*:*) + # If we were able to find `uname', then EMX Unix compatibility + # is probably installed. + echo ${UNAME_MACHINE}-pc-os2-emx + exit ;; + i*86:XTS-300:*:STOP) + echo ${UNAME_MACHINE}-unknown-stop + exit ;; + i*86:atheos:*:*) + echo ${UNAME_MACHINE}-unknown-atheos + exit ;; + i*86:syllable:*:*) + echo ${UNAME_MACHINE}-pc-syllable + exit ;; + i*86:LynxOS:2.*:* | i*86:LynxOS:3.[01]*:* | i*86:LynxOS:4.[02]*:*) + echo i386-unknown-lynxos${UNAME_RELEASE} + exit ;; + i*86:*DOS:*:*) + echo ${UNAME_MACHINE}-pc-msdosdjgpp + exit ;; + i*86:*:4.*:* | i*86:SYSTEM_V:4.*:*) + UNAME_REL=`echo ${UNAME_RELEASE} | sed 's/\/MP$//'` + if grep Novell /usr/include/link.h >/dev/null 2>/dev/null; then + echo ${UNAME_MACHINE}-univel-sysv${UNAME_REL} + else + echo ${UNAME_MACHINE}-pc-sysv${UNAME_REL} + fi + exit ;; + i*86:*:5:[678]*) + # UnixWare 7.x, OpenUNIX and OpenServer 6. + case `/bin/uname -X | grep "^Machine"` in + *486*) UNAME_MACHINE=i486 ;; + *Pentium) UNAME_MACHINE=i586 ;; + *Pent*|*Celeron) UNAME_MACHINE=i686 ;; + esac + echo ${UNAME_MACHINE}-unknown-sysv${UNAME_RELEASE}${UNAME_SYSTEM}${UNAME_VERSION} + exit ;; + i*86:*:3.2:*) + if test -f /usr/options/cb.name; then + UNAME_REL=`sed -n 's/.*Version //p' /dev/null >/dev/null ; then + UNAME_REL=`(/bin/uname -X|grep Release|sed -e 's/.*= //')` + (/bin/uname -X|grep i80486 >/dev/null) && UNAME_MACHINE=i486 + (/bin/uname -X|grep '^Machine.*Pentium' >/dev/null) \ + && UNAME_MACHINE=i586 + (/bin/uname -X|grep '^Machine.*Pent *II' >/dev/null) \ + && UNAME_MACHINE=i686 + (/bin/uname -X|grep '^Machine.*Pentium Pro' >/dev/null) \ + && UNAME_MACHINE=i686 + echo ${UNAME_MACHINE}-pc-sco$UNAME_REL + else + echo ${UNAME_MACHINE}-pc-sysv32 + fi + exit ;; + pc:*:*:*) + # Left here for compatibility: + # uname -m prints for DJGPP always 'pc', but it prints nothing about + # the processor, so we play safe by assuming i586. + # Note: whatever this is, it MUST be the same as what config.sub + # prints for the "djgpp" host, or else GDB configury will decide that + # this is a cross-build. + echo i586-pc-msdosdjgpp + exit ;; + Intel:Mach:3*:*) + echo i386-pc-mach3 + exit ;; + paragon:*:*:*) + echo i860-intel-osf1 + exit ;; + i860:*:4.*:*) # i860-SVR4 + if grep Stardent /usr/include/sys/uadmin.h >/dev/null 2>&1 ; then + echo i860-stardent-sysv${UNAME_RELEASE} # Stardent Vistra i860-SVR4 + else # Add other i860-SVR4 vendors below as they are discovered. + echo i860-unknown-sysv${UNAME_RELEASE} # Unknown i860-SVR4 + fi + exit ;; + mini*:CTIX:SYS*5:*) + # "miniframe" + echo m68010-convergent-sysv + exit ;; + mc68k:UNIX:SYSTEM5:3.51m) + echo m68k-convergent-sysv + exit ;; + M680?0:D-NIX:5.3:*) + echo m68k-diab-dnix + exit ;; + M68*:*:R3V[5678]*:*) + test -r /sysV68 && { echo 'm68k-motorola-sysv'; exit; } ;; + 3[345]??:*:4.0:3.0 | 3[34]??A:*:4.0:3.0 | 3[34]??,*:*:4.0:3.0 | 3[34]??/*:*:4.0:3.0 | 4400:*:4.0:3.0 | 4850:*:4.0:3.0 | SKA40:*:4.0:3.0 | SDS2:*:4.0:3.0 | SHG2:*:4.0:3.0 | S7501*:*:4.0:3.0) + OS_REL='' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + 3[34]??:*:4.0:* | 3[34]??,*:*:4.0:*) + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4; exit; } ;; + NCR*:*:4.2:* | MPRAS*:*:4.2:*) + OS_REL='.3' + test -r /etc/.relid \ + && OS_REL=.`sed -n 's/[^ ]* [^ ]* \([0-9][0-9]\).*/\1/p' < /etc/.relid` + /bin/uname -p 2>/dev/null | grep 86 >/dev/null \ + && { echo i486-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep entium >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } + /bin/uname -p 2>/dev/null | /bin/grep pteron >/dev/null \ + && { echo i586-ncr-sysv4.3${OS_REL}; exit; } ;; + m68*:LynxOS:2.*:* | m68*:LynxOS:3.0*:*) + echo m68k-unknown-lynxos${UNAME_RELEASE} + exit ;; + mc68030:UNIX_System_V:4.*:*) + echo m68k-atari-sysv4 + exit ;; + TSUNAMI:LynxOS:2.*:*) + echo sparc-unknown-lynxos${UNAME_RELEASE} + exit ;; + rs6000:LynxOS:2.*:*) + echo rs6000-unknown-lynxos${UNAME_RELEASE} + exit ;; + PowerPC:LynxOS:2.*:* | PowerPC:LynxOS:3.[01]*:* | PowerPC:LynxOS:4.[02]*:*) + echo powerpc-unknown-lynxos${UNAME_RELEASE} + exit ;; + SM[BE]S:UNIX_SV:*:*) + echo mips-dde-sysv${UNAME_RELEASE} + exit ;; + RM*:ReliantUNIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + RM*:SINIX-*:*:*) + echo mips-sni-sysv4 + exit ;; + *:SINIX-*:*:*) + if uname -p 2>/dev/null >/dev/null ; then + UNAME_MACHINE=`(uname -p) 2>/dev/null` + echo ${UNAME_MACHINE}-sni-sysv4 + else + echo ns32k-sni-sysv + fi + exit ;; + PENTIUM:*:4.0*:*) # Unisys `ClearPath HMP IX 4000' SVR4/MP effort + # says + echo i586-unisys-sysv4 + exit ;; + *:UNIX_System_V:4*:FTX*) + # From Gerald Hewes . + # How about differentiating between stratus architectures? -djm + echo hppa1.1-stratus-sysv4 + exit ;; + *:*:*:FTX*) + # From seanf@swdc.stratus.com. + echo i860-stratus-sysv4 + exit ;; + i*86:VOS:*:*) + # From Paul.Green@stratus.com. + echo ${UNAME_MACHINE}-stratus-vos + exit ;; + *:VOS:*:*) + # From Paul.Green@stratus.com. + echo hppa1.1-stratus-vos + exit ;; + mc68*:A/UX:*:*) + echo m68k-apple-aux${UNAME_RELEASE} + exit ;; + news*:NEWS-OS:6*:*) + echo mips-sony-newsos6 + exit ;; + R[34]000:*System_V*:*:* | R4000:UNIX_SYSV:*:* | R*000:UNIX_SV:*:*) + if [ -d /usr/nec ]; then + echo mips-nec-sysv${UNAME_RELEASE} + else + echo mips-unknown-sysv${UNAME_RELEASE} + fi + exit ;; + BeBox:BeOS:*:*) # BeOS running on hardware made by Be, PPC only. + echo powerpc-be-beos + exit ;; + BeMac:BeOS:*:*) # BeOS running on Mac or Mac clone, PPC only. + echo powerpc-apple-beos + exit ;; + BePC:BeOS:*:*) # BeOS running on Intel PC compatible. + echo i586-pc-beos + exit ;; + BePC:Haiku:*:*) # Haiku running on Intel PC compatible. + echo i586-pc-haiku + exit ;; + SX-4:SUPER-UX:*:*) + echo sx4-nec-superux${UNAME_RELEASE} + exit ;; + SX-5:SUPER-UX:*:*) + echo sx5-nec-superux${UNAME_RELEASE} + exit ;; + SX-6:SUPER-UX:*:*) + echo sx6-nec-superux${UNAME_RELEASE} + exit ;; + SX-7:SUPER-UX:*:*) + echo sx7-nec-superux${UNAME_RELEASE} + exit ;; + SX-8:SUPER-UX:*:*) + echo sx8-nec-superux${UNAME_RELEASE} + exit ;; + SX-8R:SUPER-UX:*:*) + echo sx8r-nec-superux${UNAME_RELEASE} + exit ;; + Power*:Rhapsody:*:*) + echo powerpc-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Rhapsody:*:*) + echo ${UNAME_MACHINE}-apple-rhapsody${UNAME_RELEASE} + exit ;; + *:Darwin:*:*) + UNAME_PROCESSOR=`uname -p` || UNAME_PROCESSOR=unknown + case $UNAME_PROCESSOR in + i386) + eval $set_cc_for_build + if [ "$CC_FOR_BUILD" != 'no_compiler_found' ]; then + if (echo '#ifdef __LP64__'; echo IS_64BIT_ARCH; echo '#endif') | \ + (CCOPTS= $CC_FOR_BUILD -E - 2>/dev/null) | \ + grep IS_64BIT_ARCH >/dev/null + then + UNAME_PROCESSOR="x86_64" + fi + fi ;; + unknown) UNAME_PROCESSOR=powerpc ;; + esac + echo ${UNAME_PROCESSOR}-apple-darwin${UNAME_RELEASE} + exit ;; + *:procnto*:*:* | *:QNX:[0123456789]*:*) + UNAME_PROCESSOR=`uname -p` + if test "$UNAME_PROCESSOR" = "x86"; then + UNAME_PROCESSOR=i386 + UNAME_MACHINE=pc + fi + echo ${UNAME_PROCESSOR}-${UNAME_MACHINE}-nto-qnx${UNAME_RELEASE} + exit ;; + *:QNX:*:4*) + echo i386-pc-qnx + exit ;; + NSE-?:NONSTOP_KERNEL:*:*) + echo nse-tandem-nsk${UNAME_RELEASE} + exit ;; + NSR-?:NONSTOP_KERNEL:*:*) + echo nsr-tandem-nsk${UNAME_RELEASE} + exit ;; + *:NonStop-UX:*:*) + echo mips-compaq-nonstopux + exit ;; + BS2000:POSIX*:*:*) + echo bs2000-siemens-sysv + exit ;; + DS/*:UNIX_System_V:*:*) + echo ${UNAME_MACHINE}-${UNAME_SYSTEM}-${UNAME_RELEASE} + exit ;; + *:Plan9:*:*) + # "uname -m" is not consistent, so use $cputype instead. 386 + # is converted to i386 for consistency with other x86 + # operating systems. + if test "$cputype" = "386"; then + UNAME_MACHINE=i386 + else + UNAME_MACHINE="$cputype" + fi + echo ${UNAME_MACHINE}-unknown-plan9 + exit ;; + *:TOPS-10:*:*) + echo pdp10-unknown-tops10 + exit ;; + *:TENEX:*:*) + echo pdp10-unknown-tenex + exit ;; + KS10:TOPS-20:*:* | KL10:TOPS-20:*:* | TYPE4:TOPS-20:*:*) + echo pdp10-dec-tops20 + exit ;; + XKL-1:TOPS-20:*:* | TYPE5:TOPS-20:*:*) + echo pdp10-xkl-tops20 + exit ;; + *:TOPS-20:*:*) + echo pdp10-unknown-tops20 + exit ;; + *:ITS:*:*) + echo pdp10-unknown-its + exit ;; + SEI:*:*:SEIUX) + echo mips-sei-seiux${UNAME_RELEASE} + exit ;; + *:DragonFly:*:*) + echo ${UNAME_MACHINE}-unknown-dragonfly`echo ${UNAME_RELEASE}|sed -e 's/[-(].*//'` + exit ;; + *:*VMS:*:*) + UNAME_MACHINE=`(uname -p) 2>/dev/null` + case "${UNAME_MACHINE}" in + A*) echo alpha-dec-vms ; exit ;; + I*) echo ia64-dec-vms ; exit ;; + V*) echo vax-dec-vms ; exit ;; + esac ;; + *:XENIX:*:SysV) + echo i386-pc-xenix + exit ;; + i*86:skyos:*:*) + echo ${UNAME_MACHINE}-pc-skyos`echo ${UNAME_RELEASE}` | sed -e 's/ .*$//' + exit ;; + i*86:rdos:*:*) + echo ${UNAME_MACHINE}-pc-rdos + exit ;; + i*86:AROS:*:*) + echo ${UNAME_MACHINE}-pc-aros + exit ;; +esac + +#echo '(No uname command or uname output not recognized.)' 1>&2 +#echo "${UNAME_MACHINE}:${UNAME_SYSTEM}:${UNAME_RELEASE}:${UNAME_VERSION}" 1>&2 + +eval $set_cc_for_build +cat >$dummy.c < +# include +#endif +main () +{ +#if defined (sony) +#if defined (MIPSEB) + /* BFD wants "bsd" instead of "newsos". Perhaps BFD should be changed, + I don't know.... */ + printf ("mips-sony-bsd\n"); exit (0); +#else +#include + printf ("m68k-sony-newsos%s\n", +#ifdef NEWSOS4 + "4" +#else + "" +#endif + ); exit (0); +#endif +#endif + +#if defined (__arm) && defined (__acorn) && defined (__unix) + printf ("arm-acorn-riscix\n"); exit (0); +#endif + +#if defined (hp300) && !defined (hpux) + printf ("m68k-hp-bsd\n"); exit (0); +#endif + +#if defined (NeXT) +#if !defined (__ARCHITECTURE__) +#define __ARCHITECTURE__ "m68k" +#endif + int version; + version=`(hostinfo | sed -n 's/.*NeXT Mach \([0-9]*\).*/\1/p') 2>/dev/null`; + if (version < 4) + printf ("%s-next-nextstep%d\n", __ARCHITECTURE__, version); + else + printf ("%s-next-openstep%d\n", __ARCHITECTURE__, version); + exit (0); +#endif + +#if defined (MULTIMAX) || defined (n16) +#if defined (UMAXV) + printf ("ns32k-encore-sysv\n"); exit (0); +#else +#if defined (CMU) + printf ("ns32k-encore-mach\n"); exit (0); +#else + printf ("ns32k-encore-bsd\n"); exit (0); +#endif +#endif +#endif + +#if defined (__386BSD__) + printf ("i386-pc-bsd\n"); exit (0); +#endif + +#if defined (sequent) +#if defined (i386) + printf ("i386-sequent-dynix\n"); exit (0); +#endif +#if defined (ns32000) + printf ("ns32k-sequent-dynix\n"); exit (0); +#endif +#endif + +#if defined (_SEQUENT_) + struct utsname un; + + uname(&un); + + if (strncmp(un.version, "V2", 2) == 0) { + printf ("i386-sequent-ptx2\n"); exit (0); + } + if (strncmp(un.version, "V1", 2) == 0) { /* XXX is V1 correct? */ + printf ("i386-sequent-ptx1\n"); exit (0); + } + printf ("i386-sequent-ptx\n"); exit (0); + +#endif + +#if defined (vax) +# if !defined (ultrix) +# include +# if defined (BSD) +# if BSD == 43 + printf ("vax-dec-bsd4.3\n"); exit (0); +# else +# if BSD == 199006 + printf ("vax-dec-bsd4.3reno\n"); exit (0); +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# endif +# else + printf ("vax-dec-bsd\n"); exit (0); +# endif +# else + printf ("vax-dec-ultrix\n"); exit (0); +# endif +#endif + +#if defined (alliant) && defined (i860) + printf ("i860-alliant-bsd\n"); exit (0); +#endif + + exit (1); +} +EOF + +$CC_FOR_BUILD -o $dummy $dummy.c 2>/dev/null && SYSTEM_NAME=`$dummy` && + { echo "$SYSTEM_NAME"; exit; } + +# Apollos put the system type in the environment. + +test -d /usr/apollo && { echo ${ISP}-apollo-${SYSTYPE}; exit; } + +# Convex versions that predate uname can use getsysinfo(1) + +if [ -x /usr/convex/getsysinfo ] +then + case `getsysinfo -f cpu_type` in + c1*) + echo c1-convex-bsd + exit ;; + c2*) + if getsysinfo -f scalar_acc + then echo c32-convex-bsd + else echo c2-convex-bsd + fi + exit ;; + c34*) + echo c34-convex-bsd + exit ;; + c38*) + echo c38-convex-bsd + exit ;; + c4*) + echo c4-convex-bsd + exit ;; + esac +fi + +cat >&2 < in order to provide the needed +information to handle your system. + +config.guess timestamp = $timestamp + +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null` + +hostinfo = `(hostinfo) 2>/dev/null` +/bin/universe = `(/bin/universe) 2>/dev/null` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null` +/bin/arch = `(/bin/arch) 2>/dev/null` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null` + +UNAME_MACHINE = ${UNAME_MACHINE} +UNAME_RELEASE = ${UNAME_RELEASE} +UNAME_SYSTEM = ${UNAME_SYSTEM} +UNAME_VERSION = ${UNAME_VERSION} +EOF + +exit 1 + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/config.h.in b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/config.h.in new file mode 100644 index 00000000..89a65b7c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/config.h.in @@ -0,0 +1,1242 @@ +/* config.h.in. Generated from configure.ac by autoheader. */ + +/***** begin user configuration section *****/ + +/* Define this to be the location of your password file */ +#define PASSWD_FILE "/etc/passwd" + +/* Define this to be the name of your NIS/YP password * + * map (if applicable) */ +#define PASSWD_MAP "passwd.byname" + +/* Define to 1 if you want user names to be cached */ +#define CACHE_USERNAMES 1 + +/* Define to 1 if system supports job control */ +#define JOB_CONTROL 1 + +/* Define this if you use "suspended" instead of "stopped" */ +#define USE_SUSPENDED 1 + +/* The default history buffer size in lines */ +#define DEFAULT_HISTSIZE 30 + +/* The default editor for the fc builtin */ +#define DEFAULT_FCEDIT "vi" + +/* The default prefix for temporary files */ +#define DEFAULT_TMPPREFIX "/tmp/zsh" + +/***** end of user configuration section *****/ +/***** shouldn't have to change anything below here *****/ + + + +/* Define to 1 if you want to use dynamically loaded modules on AIX. */ +#undef AIXDYNAMIC + +/* Define to 1 if the isprint() function is broken under UTF-8 locale. */ +#undef BROKEN_ISPRINT + +/* Define to 1 if kill(pid, 0) doesn't return ESRCH, ie BeOS R4.51. */ +#undef BROKEN_KILL_ESRCH + +/* Define to 1 if sigsuspend() is broken */ +#undef BROKEN_POSIX_SIGSUSPEND + +/* Define to 1 if compiler incorrectly cast signed to unsigned. */ +#undef BROKEN_SIGNED_TO_UNSIGNED_CASTING + +/* Define to 1 if tcsetpgrp() doesn't work, ie BeOS R4.51. */ +#undef BROKEN_TCSETPGRP + +/* Define to 1 if you use BSD style signal handling (and can block signals). + */ +#undef BSD_SIGNALS + +/* Undefine if you don't want local features. By default this is defined. */ +#undef CONFIG_LOCALE + +/* Define to one of `_getb67', `GETB67', `getb67' for Cray-2 and Cray-YMP + systems. This function is required for `alloca.c' support on those systems. + */ +#undef CRAY_STACKSEG_END + +/* Define to a custom value for the ZSH_PATCHLEVEL parameter */ +#undef CUSTOM_PATCHLEVEL + +/* Define to 1 if using `alloca.c'. */ +#undef C_ALLOCA + +/* Define to 1 if you want to debug zsh. */ +#undef DEBUG + +/* The default path; used when running commands with command -p */ +#undef DEFAULT_PATH + +/* Define default pager used by readnullcmd */ +#undef DEFAULT_READNULLCMD + +/* Define to 1 if you want to avoid calling functions that will require + dynamic NSS modules. */ +#undef DISABLE_DYNAMIC_NSS + +/* Define to 1 if an underscore has to be prepended to dlsym() argument. */ +#undef DLSYM_NEEDS_UNDERSCORE + +/* The extension used for dynamically loaded modules. */ +#undef DL_EXT + +/* Define to 1 if you want to use dynamically loaded modules. */ +#undef DYNAMIC + +/* Define to 1 if multiple modules defining the same symbol are OK. */ +#undef DYNAMIC_NAME_CLASH_OK + +/* Define to 1 if you want use unicode9 character widths. */ +#undef ENABLE_UNICODE9 + +/* Define to 1 if getcwd() calls malloc to allocate memory. */ +#undef GETCWD_CALLS_MALLOC + +/* Define to 1 if the `getpgrp' function requires zero arguments. */ +#undef GETPGRP_VOID + +/* Define to 1 if getpwnam() is faked, ie BeOS R4.51. */ +#undef GETPWNAM_FAKED + +/* The global file to source whenever zsh is run as a login shell; if + undefined, don't source anything */ +#undef GLOBAL_ZLOGIN + +/* The global file to source whenever zsh was run as a login shell. This is + sourced right before exiting. If undefined, don't source anything. */ +#undef GLOBAL_ZLOGOUT + +/* The global file to source whenever zsh is run as a login shell, before + zshrc is read; if undefined, don't source anything. */ +#undef GLOBAL_ZPROFILE + +/* The global file to source absolutely first whenever zsh is run; if + undefined, don't source anything. */ +#undef GLOBAL_ZSHENV + +/* The global file to source whenever zsh is run; if undefined, don't source + anything */ +#undef GLOBAL_ZSHRC + +/* Define if TIOCGWINSZ is defined in sys/ioctl.h but not in termios.h. */ +#undef GWINSZ_IN_SYS_IOCTL + +/* Define to 1 if you have `alloca', as a function or macro. */ +#undef HAVE_ALLOCA + +/* Define to 1 if you have and it should be used (not on Ultrix). + */ +#undef HAVE_ALLOCA_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_BIND_NETDB_H + +/* Define if you have the termcap boolcodes symbol. */ +#undef HAVE_BOOLCODES + +/* Define if you have the terminfo boolnames symbol. */ +#undef HAVE_BOOLNAMES + +/* Define to 1 if you have the `brk' function. */ +#undef HAVE_BRK + +/* Define to 1 if there is a prototype defined for brk() on your system. */ +#undef HAVE_BRK_PROTO + +/* Define to 1 if you have the `canonicalize_file_name' function. */ +#undef HAVE_CANONICALIZE_FILE_NAME + +/* Define to 1 if you have the `cap_get_proc' function. */ +#undef HAVE_CAP_GET_PROC + +/* Define to 1 if you have the `clock_gettime' function. */ +#undef HAVE_CLOCK_GETTIME + +/* Define to 1 if you have the header file. */ +#undef HAVE_CURSES_H + +/* Define to 1 if you have the `cygwin_conv_path' function. */ +#undef HAVE_CYGWIN_CONV_PATH + +/* Define to 1 if you have the `difftime' function. */ +#undef HAVE_DIFFTIME + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +#undef HAVE_DIRENT_H + +/* Define to 1 if you have the `dlclose' function. */ +#undef HAVE_DLCLOSE + +/* Define to 1 if you have the `dlerror' function. */ +#undef HAVE_DLERROR + +/* Define to 1 if you have the header file. */ +#undef HAVE_DLFCN_H + +/* Define to 1 if you have the `dlopen' function. */ +#undef HAVE_DLOPEN + +/* Define to 1 if you have the `dlsym' function. */ +#undef HAVE_DLSYM + +/* Define to 1 if you have the header file. */ +#undef HAVE_DL_H + +/* Define to 1 if you have the `endutxent' function. */ +#undef HAVE_ENDUTXENT + +/* Define to 1 if you have the `erand48' function. */ +#undef HAVE_ERAND48 + +/* Define to 1 if you have the header file. */ +#undef HAVE_ERRNO_H + +/* Define to 1 if you have the `faccessx' function. */ +#undef HAVE_FACCESSX + +/* Define to 1 if you have the `fchdir' function. */ +#undef HAVE_FCHDIR + +/* Define to 1 if you have the `fchmod' function. */ +#undef HAVE_FCHMOD + +/* Define to 1 if you have the `fchown' function. */ +#undef HAVE_FCHOWN + +/* Define to 1 if you have the header file. */ +#undef HAVE_FCNTL_H + +/* Define to 1 if system has working FIFOs. */ +#undef HAVE_FIFOS + +/* Define to 1 if you have the `fseeko' function. */ +#undef HAVE_FSEEKO + +/* Define to 1 if you have the `fstat' function. */ +#undef HAVE_FSTAT + +/* Define to 1 if you have the `ftello' function. */ +#undef HAVE_FTELLO + +/* Define to 1 if you have the `ftruncate' function. */ +#undef HAVE_FTRUNCATE + +/* Define to 1 if you have the header file. */ +#undef HAVE_GDBM_H + +/* Define to 1 if you have the `gdbm_open' function. */ +#undef HAVE_GDBM_OPEN + +/* Define to 1 if you have the `getcchar' function. */ +#undef HAVE_GETCCHAR + +/* Define to 1 if you have the `getcwd' function. */ +#undef HAVE_GETCWD + +/* Define to 1 if you have the `getenv' function. */ +#undef HAVE_GETENV + +/* Define to 1 if you have the `getgrgid' function. */ +#undef HAVE_GETGRGID + +/* Define to 1 if you have the `getgrnam' function. */ +#undef HAVE_GETGRNAM + +/* Define to 1 if you have the `gethostbyname2' function. */ +#undef HAVE_GETHOSTBYNAME2 + +/* Define to 1 if you have the `gethostname' function. */ +#undef HAVE_GETHOSTNAME + +/* Define to 1 if you have the `getipnodebyname' function. */ +#undef HAVE_GETIPNODEBYNAME + +/* Define to 1 if you have the `getline' function. */ +#undef HAVE_GETLINE + +/* Define to 1 if you have the `getlogin' function. */ +#undef HAVE_GETLOGIN + +/* Define to 1 if you have the `getpagesize' function. */ +#undef HAVE_GETPAGESIZE + +/* Define to 1 if you have the `getpwent' function. */ +#undef HAVE_GETPWENT + +/* Define to 1 if you have the `getpwnam' function. */ +#undef HAVE_GETPWNAM + +/* Define to 1 if you have the `getpwuid' function. */ +#undef HAVE_GETPWUID + +/* Define to 1 if you have the `getrlimit' function. */ +#undef HAVE_GETRLIMIT + +/* Define to 1 if you have the `getrusage' function. */ +#undef HAVE_GETRUSAGE + +/* Define to 1 if you have the `gettimeofday' function. */ +#undef HAVE_GETTIMEOFDAY + +/* Define to 1 if you have the `getutent' function. */ +#undef HAVE_GETUTENT + +/* Define to 1 if you have the `getutxent' function. */ +#undef HAVE_GETUTXENT + +/* Define to 1 if you have the `getxattr' function. */ +#undef HAVE_GETXATTR + +/* Define to 1 if you have the `grantpt' function. */ +#undef HAVE_GRANTPT + +/* Define to 1 if you have the header file. */ +#undef HAVE_GRP_H + +/* Define to 1 if you have the `htons' function. */ +#undef HAVE_HTONS + +/* Define to 1 if you have the `iconv' function. */ +#undef HAVE_ICONV + +/* Define to 1 if you have the header file. */ +#undef HAVE_ICONV_H + +/* Define to 1 if you have the `inet_aton' function. */ +#undef HAVE_INET_ATON + +/* Define to 1 if you have the `inet_ntop' function. */ +#undef HAVE_INET_NTOP + +/* Define to 1 if you have the `inet_pton' function. */ +#undef HAVE_INET_PTON + +/* Define to 1 if you have the `initgroups' function. */ +#undef HAVE_INITGROUPS + +/* Define to 1 if you have the `initscr' function. */ +#undef HAVE_INITSCR + +/* Define to 1 if you have the header file. */ +#undef HAVE_INTTYPES_H + +/* Define to 1 if there is a prototype defined for ioctl() on your system. */ +#undef HAVE_IOCTL_PROTO + +/* Define to 1 if you have the `isblank' function. */ +#undef HAVE_ISBLANK + +/* Define to 1 if you have the `isinf' function. */ +#undef HAVE_ISINF + +/* Define to 1 if you have the `isnan' function. */ +#undef HAVE_ISNAN + +/* Define to 1 if you have the `iswblank' function. */ +#undef HAVE_ISWBLANK + +/* Define to 1 if you have the `killpg' function. */ +#undef HAVE_KILLPG + +/* Define to 1 if you have the header file. */ +#undef HAVE_LANGINFO_H + +/* Define to 1 if you have the `lchown' function. */ +#undef HAVE_LCHOWN + +/* Define to 1 if you have the `cap' library (-lcap). */ +#undef HAVE_LIBCAP + +/* Define to 1 if you have the header file. */ +#undef HAVE_LIBC_H + +/* Define to 1 if you have the `dl' library (-ldl). */ +#undef HAVE_LIBDL + +/* Define to 1 if you have the `gdbm' library (-lgdbm). */ +#undef HAVE_LIBGDBM + +/* Define to 1 if you have the `m' library (-lm). */ +#undef HAVE_LIBM + +/* Define to 1 if you have the `rt' library (-lrt). */ +#undef HAVE_LIBRT + +/* Define to 1 if you have the `socket' library (-lsocket). */ +#undef HAVE_LIBSOCKET + +/* Define to 1 if you have the header file. */ +#undef HAVE_LIMITS_H + +/* Define to 1 if system has working link(). */ +#undef HAVE_LINK + +/* Define to 1 if you have the `load' function. */ +#undef HAVE_LOAD + +/* Define to 1 if you have the `loadbind' function. */ +#undef HAVE_LOADBIND + +/* Define to 1 if you have the `loadquery' function. */ +#undef HAVE_LOADQUERY + +/* Define to 1 if you have the header file. */ +#undef HAVE_LOCALE_H + +/* Define to 1 if you have the `log2' function. */ +#undef HAVE_LOG2 + +/* Define to 1 if you have the `lstat' function. */ +#undef HAVE_LSTAT + +/* Define to 1 if you have the `memcpy' function. */ +#undef HAVE_MEMCPY + +/* Define to 1 if you have the `memmove' function. */ +#undef HAVE_MEMMOVE + +/* Define to 1 if you have the header file. */ +#undef HAVE_MEMORY_H + +/* Define to 1 if you have the `mkfifo' function. */ +#undef HAVE_MKFIFO + +/* Define to 1 if there is a prototype defined for mknod() on your system. */ +#undef HAVE_MKNOD_PROTO + +/* Define to 1 if you have the `mkstemp' function. */ +#undef HAVE_MKSTEMP + +/* Define to 1 if you have the `mktime' function. */ +#undef HAVE_MKTIME + +/* Define to 1 if you have a working `mmap' system call. */ +#undef HAVE_MMAP + +/* Define to 1 if you have the `msync' function. */ +#undef HAVE_MSYNC + +/* Define to 1 if you have the `munmap' function. */ +#undef HAVE_MUNMAP + +/* Define to 1 if you have the `nanosleep' function. */ +#undef HAVE_NANOSLEEP + +/* Define to 1 if you have the header file. */ +#undef HAVE_NCURSESW_NCURSES_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NCURSESW_TERM_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NCURSES_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NCURSES_NCURSES_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NCURSES_TERM_H + +/* Define to 1 if you have the header file, and it defines `DIR'. */ +#undef HAVE_NDIR_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_NETINET_IN_SYSTM_H + +/* Define to 1 if you have the `nice' function. */ +#undef HAVE_NICE + +/* Define to 1 if you have NIS. */ +#undef HAVE_NIS + +/* Define to 1 if you have the `nis_list' function. */ +#undef HAVE_NIS_LIST + +/* Define to 1 if you have NISPLUS. */ +#undef HAVE_NIS_PLUS + +/* Define to 1 if you have the `nl_langinfo' function. */ +#undef HAVE_NL_LANGINFO + +/* Define to 1 if you have the `ntohs' function. */ +#undef HAVE_NTOHS + +/* Define if you have the termcap numcodes symbol. */ +#undef HAVE_NUMCODES + +/* Define if you have the terminfo numnames symbol. */ +#undef HAVE_NUMNAMES + +/* Define to 1 if you have the `open_memstream' function. */ +#undef HAVE_OPEN_MEMSTREAM + +/* Define to 1 if your termcap library has the ospeed variable */ +#undef HAVE_OSPEED + +/* Define to 1 if you have the `pathconf' function. */ +#undef HAVE_PATHCONF + +/* Define to 1 if you have the `poll' function. */ +#undef HAVE_POLL + +/* Define to 1 if you have the header file. */ +#undef HAVE_POLL_H + +/* Define to 1 if you have the `posix_openpt' function. */ +#undef HAVE_POSIX_OPENPT + +/* Define to 1 if you have the `ptsname' function. */ +#undef HAVE_PTSNAME + +/* Define to 1 if you have the `putenv' function. */ +#undef HAVE_PUTENV + +/* Define to 1 if you have the header file. */ +#undef HAVE_PWD_H + +/* Define to 1 if you have the `readlink' function. */ +#undef HAVE_READLINK + +/* Define to 1 if you have the `realpath' function. */ +#undef HAVE_REALPATH + +/* Define to 1 if you have the `regcomp' function. */ +#undef HAVE_REGCOMP + +/* Define to 1 if you have the `regerror' function. */ +#undef HAVE_REGERROR + +/* Define to 1 if you have the `regexec' function. */ +#undef HAVE_REGEXEC + +/* Define to 1 if you have the `regfree' function. */ +#undef HAVE_REGFREE + +/* Define to 1 if you have the `resize_term' function. */ +#undef HAVE_RESIZE_TERM + +/* Define to 1 if RLIMIT_AIO_MEM is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_AIO_MEM + +/* Define to 1 if RLIMIT_AIO_OPS is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_AIO_OPS + +/* Define to 1 if RLIMIT_AS is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_AS + +/* Define to 1 if RLIMIT_KQUEUES is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_KQUEUES + +/* Define to 1 if RLIMIT_LOCKS is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_LOCKS + +/* Define to 1 if RLIMIT_MEMLOCK is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_MEMLOCK + +/* Define to 1 if RLIMIT_MSGQUEUE is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_MSGQUEUE + +/* Define to 1 if RLIMIT_NICE is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_NICE + +/* Define to 1 if RLIMIT_NOFILE is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_NOFILE + +/* Define to 1 if RLIMIT_NPROC is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_NPROC + +/* Define to 1 if RLIMIT_NPTS is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_NPTS + +/* Define to 1 if RLIMIT_NTHR is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_NTHR + +/* Define to 1 if RLIMIT_POSIXLOCKS is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_POSIXLOCKS + +/* Define to 1 if RLIMIT_PTHREAD is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_PTHREAD + +/* Define to 1 if RLIMIT_RSS is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_RSS + +/* Define to 1 if RLIMIT_RTPRIO is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_RTPRIO + +/* Define to 1 if RLIMIT_SBSIZE is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_SBSIZE + +/* Define to 1 if RLIMIT_SIGPENDING is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_SIGPENDING + +/* Define to 1 if RLIMIT_SWAP is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_SWAP + +/* Define to 1 if RLIMIT_TCACHE is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_TCACHE + +/* Define to 1 if RLIMIT_VMEM is present (whether or not as a macro). */ +#undef HAVE_RLIMIT_VMEM + +/* Define to 1 if you have the `sbrk' function. */ +#undef HAVE_SBRK + +/* Define to 1 if there is a prototype defined for sbrk() on your system. */ +#undef HAVE_SBRK_PROTO + +/* Define to 1 if you have the `scalbn' function. */ +#undef HAVE_SCALBN + +/* Define to 1 if you have the `select' function. */ +#undef HAVE_SELECT + +/* Define to 1 if you have the `setcchar' function. */ +#undef HAVE_SETCCHAR + +/* Define to 1 if you have the `setenv' function. */ +#undef HAVE_SETENV + +/* Define to 1 if you have the `seteuid' function. */ +#undef HAVE_SETEUID + +/* Define to 1 if you have the `setlocale' function. */ +#undef HAVE_SETLOCALE + +/* Define to 1 if you have the `setpgid' function. */ +#undef HAVE_SETPGID + +/* Define to 1 if you have the `setpgrp' function. */ +#undef HAVE_SETPGRP + +/* Define to 1 if the system supports `setproctitle' to change process name */ +#undef HAVE_SETPROCTITLE + +/* Define to 1 if you have the `setresuid' function. */ +#undef HAVE_SETRESUID + +/* Define to 1 if you have the `setreuid' function. */ +#undef HAVE_SETREUID + +/* Define to 1 if you have the `setsid' function. */ +#undef HAVE_SETSID + +/* Define to 1 if you have the `setuid' function. */ +#undef HAVE_SETUID + +/* Define to 1 if you have the `setupterm' function. */ +#undef HAVE_SETUPTERM + +/* Define to 1 if you have the `setutxent' function. */ +#undef HAVE_SETUTXENT + +/* Define to 1 if you have the `shl_findsym' function. */ +#undef HAVE_SHL_FINDSYM + +/* Define to 1 if you have the `shl_load' function. */ +#undef HAVE_SHL_LOAD + +/* Define to 1 if you have the `shl_unload' function. */ +#undef HAVE_SHL_UNLOAD + +/* Define to 1 if you have the `sigaction' function. */ +#undef HAVE_SIGACTION + +/* Define to 1 if you have the `sigblock' function. */ +#undef HAVE_SIGBLOCK + +/* Define to 1 if you have the `sighold' function. */ +#undef HAVE_SIGHOLD + +/* Define to 1 if you have the `signgam' function. */ +#undef HAVE_SIGNGAM + +/* Define to 1 if you have the `sigprocmask' function. */ +#undef HAVE_SIGPROCMASK + +/* Define to 1 if you have the `sigrelse' function. */ +#undef HAVE_SIGRELSE + +/* Define to 1 if you have the `sigsetmask' function. */ +#undef HAVE_SIGSETMASK + +/* Define to 1 if you have the `srand_deterministic' function. */ +#undef HAVE_SRAND_DETERMINISTIC + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDARG_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDDEF_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDINT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDIO_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STDLIB_H + +/* Define if you have the termcap strcodes symbol. */ +#undef HAVE_STRCODES + +/* Define to 1 if you have the `strcoll' function and it is properly defined. + */ +#undef HAVE_STRCOLL + +/* Define to 1 if you have the `strerror' function. */ +#undef HAVE_STRERROR + +/* Define to 1 if you have the `strftime' function. */ +#undef HAVE_STRFTIME + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRINGS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_STRING_H + +/* Define if you have the terminfo strnames symbol. */ +#undef HAVE_STRNAMES + +/* Define to 1 if you have the `strptime' function. */ +#undef HAVE_STRPTIME + +/* Define to 1 if you have the `strstr' function. */ +#undef HAVE_STRSTR + +/* Define to 1 if you have the `strtoul' function. */ +#undef HAVE_STRTOUL + +/* Define if your system's struct direct has a member named d_ino. */ +#undef HAVE_STRUCT_DIRECT_D_INO + +/* Define if your system's struct direct has a member named d_stat. */ +#undef HAVE_STRUCT_DIRECT_D_STAT + +/* Define if your system's struct dirent has a member named d_ino. */ +#undef HAVE_STRUCT_DIRENT_D_INO + +/* Define if your system's struct dirent has a member named d_stat. */ +#undef HAVE_STRUCT_DIRENT_D_STAT + +/* Define to 1 if `ru_idrss' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_IDRSS + +/* Define to 1 if `ru_inblock' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_INBLOCK + +/* Define to 1 if `ru_isrss' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_ISRSS + +/* Define to 1 if `ru_ixrss' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_IXRSS + +/* Define to 1 if `ru_majflt' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_MAJFLT + +/* Define to 1 if `ru_maxrss' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_MAXRSS + +/* Define to 1 if `ru_minflt' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_MINFLT + +/* Define to 1 if `ru_msgrcv' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_MSGRCV + +/* Define to 1 if `ru_msgsnd' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_MSGSND + +/* Define to 1 if `ru_nivcsw' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_NIVCSW + +/* Define to 1 if `ru_nsignals' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_NSIGNALS + +/* Define to 1 if `ru_nswap' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_NSWAP + +/* Define to 1 if `ru_nvcsw' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_NVCSW + +/* Define to 1 if `ru_oublock' is a member of `struct rusage'. */ +#undef HAVE_STRUCT_RUSAGE_RU_OUBLOCK + +/* Define if your system's struct sockaddr_in6 has a member named + sin6_scope_id. */ +#undef HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID + +/* Define to 1 if `st_atimensec' is a member of `struct stat'. */ +#undef HAVE_STRUCT_STAT_ST_ATIMENSEC + +/* Define to 1 if `st_atimespec.tv_nsec' is a member of `struct stat'. */ +#undef HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC + +/* Define to 1 if `st_atim.tv_nsec' is a member of `struct stat'. */ +#undef HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC + +/* Define to 1 if `st_ctimensec' is a member of `struct stat'. */ +#undef HAVE_STRUCT_STAT_ST_CTIMENSEC + +/* Define to 1 if `st_ctimespec.tv_nsec' is a member of `struct stat'. */ +#undef HAVE_STRUCT_STAT_ST_CTIMESPEC_TV_NSEC + +/* Define to 1 if `st_ctim.tv_nsec' is a member of `struct stat'. */ +#undef HAVE_STRUCT_STAT_ST_CTIM_TV_NSEC + +/* Define to 1 if `st_mtimensec' is a member of `struct stat'. */ +#undef HAVE_STRUCT_STAT_ST_MTIMENSEC + +/* Define to 1 if `st_mtimespec.tv_nsec' is a member of `struct stat'. */ +#undef HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC + +/* Define to 1 if `st_mtim.tv_nsec' is a member of `struct stat'. */ +#undef HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC + +/* Define to 1 if struct timespec is defined by a system header */ +#undef HAVE_STRUCT_TIMESPEC + +/* Define to 1 if struct timezone is defined by a system header */ +#undef HAVE_STRUCT_TIMEZONE + +/* Define to 1 if struct utmp is defined by a system header */ +#undef HAVE_STRUCT_UTMP + +/* Define to 1 if struct utmpx is defined by a system header */ +#undef HAVE_STRUCT_UTMPX + +/* Define if your system's struct utmpx has a member named ut_host. */ +#undef HAVE_STRUCT_UTMPX_UT_HOST + +/* Define if your system's struct utmpx has a member named ut_tv. */ +#undef HAVE_STRUCT_UTMPX_UT_TV + +/* Define if your system's struct utmpx has a member named ut_xtime. */ +#undef HAVE_STRUCT_UTMPX_UT_XTIME + +/* Define if your system's struct utmp has a member named ut_host. */ +#undef HAVE_STRUCT_UTMP_UT_HOST + +/* Define to 1 if you have RFS superroot directory. */ +#undef HAVE_SUPERROOT + +/* Define to 1 if you have the `symlink' function. */ +#undef HAVE_SYMLINK + +/* Define to 1 if you have the `sysconf' function. */ +#undef HAVE_SYSCONF + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_CAPABILITY_H + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +#undef HAVE_SYS_DIR_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_FILIO_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_MMAN_H + +/* Define to 1 if you have the header file, and it defines `DIR'. + */ +#undef HAVE_SYS_NDIR_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_PARAM_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_RESOURCE_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_SELECT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_STAT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_STROPTS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TIMES_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TIME_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_TYPES_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_UTSNAME_H + +/* Define to 1 if you have that is POSIX.1 compatible. */ +#undef HAVE_SYS_WAIT_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_SYS_XATTR_H + +/* Define to 1 if you have the `tcgetattr' function. */ +#undef HAVE_TCGETATTR + +/* Define to 1 if you have the `tcsetpgrp' function. */ +#undef HAVE_TCSETPGRP + +/* Define to 1 if you have the header file. */ +#undef HAVE_TERMCAP_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_TERMIOS_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_TERMIO_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_TERM_H + +/* Define to 1 if you have the `tgamma' function. */ +#undef HAVE_TGAMMA + +/* Define to 1 if you have the `tgetent' function. */ +#undef HAVE_TGETENT + +/* Define to 1 if you have the `tigetflag' function. */ +#undef HAVE_TIGETFLAG + +/* Define to 1 if you have the `tigetnum' function. */ +#undef HAVE_TIGETNUM + +/* Define to 1 if you have the `tigetstr' function. */ +#undef HAVE_TIGETSTR + +/* Define to 1 if you have the `timelocal' function. */ +#undef HAVE_TIMELOCAL + +/* Define to 1 if you have the `uname' function. */ +#undef HAVE_UNAME + +/* Define to 1 if the compiler can initialise a union. */ +#undef HAVE_UNION_INIT + +/* Define to 1 if you have the header file. */ +#undef HAVE_UNISTD_H + +/* Define to 1 if you have the `unload' function. */ +#undef HAVE_UNLOAD + +/* Define to 1 if you have the `unlockpt' function. */ +#undef HAVE_UNLOCKPT + +/* Define to 1 if you have the `unsetenv' function. */ +#undef HAVE_UNSETENV + +/* Define to 1 if you have the `use_default_colors' function. */ +#undef HAVE_USE_DEFAULT_COLORS + +/* Define to 1 if you have the header file. */ +#undef HAVE_UTMPX_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_UTMP_H + +/* Define to 1 if you have the header file. */ +#undef HAVE_VARARGS_H + +/* Define to 1 if compiler supports variable-length arrays */ +#undef HAVE_VARIABLE_LENGTH_ARRAYS + +/* Define to 1 if you have the `waddwstr' function. */ +#undef HAVE_WADDWSTR + +/* Define to 1 if you have the `wait3' function. */ +#undef HAVE_WAIT3 + +/* Define to 1 if you have the `waitpid' function. */ +#undef HAVE_WAITPID + +/* Define to 1 if you have the header file. */ +#undef HAVE_WCHAR_H + +/* Define to 1 if you have the `wctomb' function. */ +#undef HAVE_WCTOMB + +/* Define to 1 if you have the `wget_wch' function. */ +#undef HAVE_WGET_WCH + +/* Define to 1 if you have the `win_wch' function. */ +#undef HAVE_WIN_WCH + +/* Define to 1 if you have the `xw' function. */ +#undef HAVE_XW + +/* Define to 1 if you have the `_mktemp' function. */ +#undef HAVE__MKTEMP + +/* Define to 1 if you want to use dynamically loaded modules on HPUX 10. */ +#undef HPUX10DYNAMIC + +/* Define as const if the declaration of iconv() needs const. */ +#undef ICONV_CONST + +/* Define to 1 if iconv() is linked from libiconv */ +#undef ICONV_FROM_LIBICONV + +/* Define to 1 if ino_t is 64 bit (for large file support). */ +#undef INO_T_IS_64_BIT + +/* Define to 1 if we must include to get a prototype for + ioctl(). */ +#undef IOCTL_IN_SYS_IOCTL + +/* Define to 1 if musl is being used as the C library */ +#undef LIBC_MUSL + +/* Definitions used when a long is less than eight byte, to try to provide + some support for eight byte operations. Note that ZSH_64_BIT_TYPE, + OFF_T_IS_64_BIT, INO_T_IS_64_BIT do *not* get defined if long is already 64 + bits, since in that case no special handling is required. Define to 1 if + long is 64 bits */ +#undef LONG_IS_64_BIT + +/* Define to be the machine type (microprocessor class or machine model). */ +#undef MACHTYPE + +/* Define for Maildir support */ +#undef MAILDIR_SUPPORT + +/* Define for function depth limits */ +#undef MAX_FUNCTION_DEPTH + +/* Define to 1 if you want support for multibyte character sets. */ +#undef MULTIBYTE_SUPPORT + +/* Define to 1 if you have ospeed, but it is not defined in termcap.h */ +#undef MUST_DEFINE_OSPEED + +/* Define to 1 if you have no signal blocking at all (bummer). */ +#undef NO_SIGNAL_BLOCKING + +/* Define to 1 if off_t is 64 bit (for large file support) */ +#undef OFF_T_IS_64_BIT + +/* Define to be the name of the operating system. */ +#undef OSTYPE + +/* Define to the address where bug reports for this package should be sent. */ +#undef PACKAGE_BUGREPORT + +/* Define to the full name of this package. */ +#undef PACKAGE_NAME + +/* Define to the full name and version of this package. */ +#undef PACKAGE_STRING + +/* Define to the one symbol short name of this package. */ +#undef PACKAGE_TARNAME + +/* Define to the home page for this package. */ +#undef PACKAGE_URL + +/* Define to the version of this package. */ +#undef PACKAGE_VERSION + +/* Define to the path of the /dev/fd filesystem. */ +#undef PATH_DEV_FD + +/* Define to be location of utmpx file. */ +#undef PATH_UTMPX_FILE + +/* Define to be location of utmp file. */ +#undef PATH_UTMP_FILE + +/* Define to be location of wtmpx file. */ +#undef PATH_WTMPX_FILE + +/* Define to be location of wtmp file. */ +#undef PATH_WTMP_FILE + +/* Define to 1 if you use POSIX style signal handling. */ +#undef POSIX_SIGNALS + +/* Define to 1 if printf and sprintf support %lld for long long. */ +#undef PRINTF_HAS_LLD + +/* Define to 1 if ANSI function prototypes are usable. */ +#undef PROTOTYPES + +/* Define if realpath() accepts NULL as its second argument. */ +#undef REALPATH_ACCEPTS_NULL + +/* Undefine this if you don't want to get a restricted shell when zsh is + exec'd with basename that starts with r. By default this is defined. */ +#undef RESTRICTED_R + +/* Define to 1 if RLIMIT_RSS and RLIMIT_AS both exist and are equal. */ +#undef RLIMIT_RSS_IS_AS + +/* Define to 1 if RLIMIT_VMEM and RLIMIT_AS both exist and are equal. */ +#undef RLIMIT_VMEM_IS_AS + +/* Define to 1 if RLIMIT_VMEM and RLIMIT_RSS both exist and are equal. */ +#undef RLIMIT_VMEM_IS_RSS + +/* Define to 1 if struct rlimit uses long long */ +#undef RLIM_T_IS_LONG_LONG + +/* Define to 1 if struct rlimit uses quad_t. */ +#undef RLIM_T_IS_QUAD_T + +/* Define to 1 if struct rlimit uses unsigned. */ +#undef RLIM_T_IS_UNSIGNED + +/* Define to 1 if select() is defined in , ie BeOS R4.51 */ +#undef SELECT_IN_SYS_SOCKET_H + +/* If using the C implementation of alloca, define if you know the + direction of stack growth for your system; otherwise it will be + automatically deduced at runtime. + STACK_DIRECTION > 0 => grows toward higher addresses + STACK_DIRECTION < 0 => grows toward lower addresses + STACK_DIRECTION = 0 => direction of growth unknown */ +#undef STACK_DIRECTION + +/* Define to 1 if the `S_IS*' macros in do not work properly. */ +#undef STAT_MACROS_BROKEN + +/* Define to 1 if you have the ANSI C header files. */ +#undef STDC_HEADERS + +/* Define to 1 if you use SYS style signal handling (and can block signals). + */ +#undef SYSV_SIGNALS + +/* Define to 1 if tgetent() accepts NULL as a buffer. */ +#undef TGETENT_ACCEPTS_NULL + +/* Define to what tgetent() returns on success (0 on HP-UX X/Open curses). */ +#undef TGETENT_SUCCESS + +/* Define if there is no prototype for the tgoto() terminal function. */ +#undef TGOTO_PROTO_MISSING + +/* Define if sys/time.h and sys/select.h cannot be both included. */ +#undef TIME_H_SELECT_H_CONFLICTS + +/* Define to 1 if you can safely include both and . */ +#undef TIME_WITH_SYS_TIME + +/* Define to 1 if all the kit for using /dev/ptmx for ptys is available. */ +#undef USE_DEV_PTMX + +/* Define to 1 if you need to use the native getcwd. */ +#undef USE_GETCWD + +/* Define to 1 if h_errno is not defined by the system. */ +#undef USE_LOCAL_H_ERRNO + +/* Define to 1 if you want to allocate stack memory e.g. with `alloca'. */ +#undef USE_STACK_ALLOCATION + +/* Define to be a string corresponding the vendor of the machine. */ +#undef VENDOR + +/* Define if your should include sys/stream.h and sys/ptem.h. */ +#undef WINSIZE_IN_PTEM + +/* Define if getxattr() etc. require additional MacOS-style arguments */ +#undef XATTR_EXTRA_ARGS + +/* Define to 1 if the zlong type uses 64-bit long int. */ +#undef ZLONG_IS_LONG_64 + +/* Define to 1 if the zlong type uses long long int. */ +#undef ZLONG_IS_LONG_LONG + +/* Define to a 64 bit integer type if there is one, but long is shorter. */ +#undef ZSH_64_BIT_TYPE + +/* Define to an unsigned variant of ZSH_64_BIT_TYPE if that is defined. */ +#undef ZSH_64_BIT_UTYPE + +/* Define to 1 if you want to get debugging information on internal hash + tables. This turns on the `hashinfo' builtin. */ +#undef ZSH_HASH_DEBUG + +/* Define to 1 if some variant of a curses header can be included */ +#undef ZSH_HAVE_CURSES_H + +/* Define to 1 if some variant of term.h can be included */ +#undef ZSH_HAVE_TERM_H + +/* Define to 1 if you want to turn on error checking for heap allocation. */ +#undef ZSH_HEAP_DEBUG + +/* Define to 1 if you want to use zsh's own memory allocation routines */ +#undef ZSH_MEM + +/* Define to 1 if you want to debug zsh memory allocation routines. */ +#undef ZSH_MEM_DEBUG + +/* Define to 1 if you want to turn on warnings of memory allocation errors */ +#undef ZSH_MEM_WARNING + +/* Define if _XOPEN_SOURCE_EXTENDED should not be defined to avoid clashes */ +#undef ZSH_NO_XOPEN + +/* Define to 1 if you want to turn on memory checking for free(). */ +#undef ZSH_SECURE_FREE + +/* Define to 1 if you want to add code for valgrind to debug heap memory. */ +#undef ZSH_VALGRIND + +/* Define to the base type of the third argument of accept */ +#undef ZSOCKLEN_T + +/* Enable large inode numbers on Mac OS X 10.5. */ +#ifndef _DARWIN_USE_64_BIT_INODE +# define _DARWIN_USE_64_BIT_INODE 1 +#endif + +/* Number of bits in a file offset, on hosts where this is settable. */ +#undef _FILE_OFFSET_BITS + +/* Define for large files, on AIX-style hosts. */ +#undef _LARGE_FILES + +/* Define to empty if `const' does not conform to ANSI C. */ +#undef const + +/* Define to `int' if doesn't define. */ +#undef gid_t + +/* Define to `unsigned long' if doesn't define. */ +#undef ino_t + +/* Define to `int' if does not define. */ +#undef mode_t + +/* Define to `long int' if does not define. */ +#undef off_t + +/* Define to `int' if does not define. */ +#undef pid_t + +/* Define to the type used in struct rlimit. */ +#undef rlim_t + +/* Define to `unsigned int' if or doesn't define */ +#undef sigset_t + +/* Define to `unsigned int' if does not define. */ +#undef size_t + +/* Define to `int' if doesn't define. */ +#undef uid_t diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/config.sub b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/config.sub new file mode 100755 index 00000000..2a55a507 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/config.sub @@ -0,0 +1,1705 @@ +#! /bin/sh +# Configuration validation subroutine script. +# Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, +# 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009 +# Free Software Foundation, Inc. + +timestamp='2009-11-20' + +# This file is (in principle) common to ALL GNU software. +# The presence of a machine in this file suggests that SOME GNU software +# can handle that machine. It does not imply ALL GNU software can. +# +# This file is free software; you can redistribute it and/or modify +# it under the terms of the GNU General Public License as published by +# the Free Software Foundation; either version 2 of the License, or +# (at your option) any later version. +# +# This program is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU General Public License for more details. +# +# You should have received a copy of the GNU General Public License +# along with this program; if not, write to the Free Software +# Foundation, Inc., 51 Franklin Street - Fifth Floor, Boston, MA +# 02110-1301, USA. +# +# As a special exception to the GNU General Public License, if you +# distribute this file as part of a program that contains a +# configuration script generated by Autoconf, you may include it under +# the same distribution terms that you use for the rest of that program. + + +# Please send patches to . Submit a context +# diff and a properly formatted GNU ChangeLog entry. +# +# Configuration subroutine to validate and canonicalize a configuration type. +# Supply the specified configuration type as an argument. +# If it is invalid, we print an error message on stderr and exit with code 1. +# Otherwise, we print the canonical config type on stdout and succeed. + +# You can get the latest version of this script from: +# http://git.savannah.gnu.org/gitweb/?p=config.git;a=blob_plain;f=config.sub;hb=HEAD + +# This file is supposed to be the same for all GNU packages +# and recognize all the CPU types, system types and aliases +# that are meaningful with *any* GNU software. +# Each package is responsible for reporting which valid configurations +# it does not support. The user should be able to distinguish +# a failure to support a valid configuration from a meaningless +# configuration. + +# The goal of this file is to map all the various variations of a given +# machine specification into a single specification in the form: +# CPU_TYPE-MANUFACTURER-OPERATING_SYSTEM +# or in some cases, the newer four-part form: +# CPU_TYPE-MANUFACTURER-KERNEL-OPERATING_SYSTEM +# It is wrong to echo any other type of specification. + +me=`echo "$0" | sed -e 's,.*/,,'` + +usage="\ +Usage: $0 [OPTION] CPU-MFR-OPSYS + $0 [OPTION] ALIAS + +Canonicalize a configuration name. + +Operation modes: + -h, --help print this help, then exit + -t, --time-stamp print date of last modification, then exit + -v, --version print version number, then exit + +Report bugs and patches to ." + +version="\ +GNU config.sub ($timestamp) + +Copyright (C) 1992, 1993, 1994, 1995, 1996, 1997, 1998, 1999, 2000, 2001, +2002, 2003, 2004, 2005, 2006, 2007, 2008 Free Software Foundation, Inc. + +This is free software; see the source for copying conditions. There is NO +warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE." + +help=" +Try \`$me --help' for more information." + +# Parse command line +while test $# -gt 0 ; do + case $1 in + --time-stamp | --time* | -t ) + echo "$timestamp" ; exit ;; + --version | -v ) + echo "$version" ; exit ;; + --help | --h* | -h ) + echo "$usage"; exit ;; + -- ) # Stop option processing + shift; break ;; + - ) # Use stdin as input. + break ;; + -* ) + echo "$me: invalid option $1$help" + exit 1 ;; + + *local*) + # First pass through any local machine types. + echo $1 + exit ;; + + * ) + break ;; + esac +done + +case $# in + 0) echo "$me: missing argument$help" >&2 + exit 1;; + 1) ;; + *) echo "$me: too many arguments$help" >&2 + exit 1;; +esac + +# Separate what the user gave into CPU-COMPANY and OS or KERNEL-OS (if any). +# Here we must recognize all the valid KERNEL-OS combinations. +maybe_os=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\2/'` +case $maybe_os in + nto-qnx* | linux-gnu* | linux-dietlibc | linux-newlib* | linux-uclibc* | \ + uclinux-uclibc* | uclinux-gnu* | kfreebsd*-gnu* | knetbsd*-gnu* | netbsd*-gnu* | \ + kopensolaris*-gnu* | \ + storm-chaos* | os2-emx* | rtmk-nova*) + os=-$maybe_os + basic_machine=`echo $1 | sed 's/^\(.*\)-\([^-]*-[^-]*\)$/\1/'` + ;; + *) + basic_machine=`echo $1 | sed 's/-[^-]*$//'` + if [ $basic_machine != $1 ] + then os=`echo $1 | sed 's/.*-/-/'` + else os=; fi + ;; +esac + +### Let's recognize common machines as not being operating systems so +### that things like config.sub decstation-3100 work. We also +### recognize some manufacturers as not being operating systems, so we +### can provide default operating systems below. +case $os in + -sun*os*) + # Prevent following clause from handling this invalid input. + ;; + -dec* | -mips* | -sequent* | -encore* | -pc532* | -sgi* | -sony* | \ + -att* | -7300* | -3300* | -delta* | -motorola* | -sun[234]* | \ + -unicom* | -ibm* | -next | -hp | -isi* | -apollo | -altos* | \ + -convergent* | -ncr* | -news | -32* | -3600* | -3100* | -hitachi* |\ + -c[123]* | -convex* | -sun | -crds | -omron* | -dg | -ultra | -tti* | \ + -harris | -dolphin | -highlevel | -gould | -cbm | -ns | -masscomp | \ + -apple | -axis | -knuth | -cray | -microblaze) + os= + basic_machine=$1 + ;; + -bluegene*) + os=-cnk + ;; + -sim | -cisco | -oki | -wec | -winbond) + os= + basic_machine=$1 + ;; + -scout) + ;; + -wrs) + os=-vxworks + basic_machine=$1 + ;; + -chorusos*) + os=-chorusos + basic_machine=$1 + ;; + -chorusrdb) + os=-chorusrdb + basic_machine=$1 + ;; + -hiux*) + os=-hiuxwe2 + ;; + -sco6) + os=-sco5v6 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco5) + os=-sco3.2v5 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco4) + os=-sco3.2v4 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2.[4-9]*) + os=`echo $os | sed -e 's/sco3.2./sco3.2v/'` + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco3.2v[4-9]*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco5v6*) + # Don't forget version if it is 3.2v4 or newer. + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -sco*) + os=-sco3.2v2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -udk*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -isc) + os=-isc2.2 + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -clix*) + basic_machine=clipper-intergraph + ;; + -isc*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-pc/'` + ;; + -lynx*) + os=-lynxos + ;; + -ptx*) + basic_machine=`echo $1 | sed -e 's/86-.*/86-sequent/'` + ;; + -windowsnt*) + os=`echo $os | sed -e 's/windowsnt/winnt/'` + ;; + -psos*) + os=-psos + ;; + -mint | -mint[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; +esac + +# Decode aliases for certain CPU-COMPANY combinations. +case $basic_machine in + # Recognize the basic CPU types without company name. + # Some are omitted here because they have special meanings below. + 1750a | 580 \ + | a29k \ + | alpha | alphaev[4-8] | alphaev56 | alphaev6[78] | alphapca5[67] \ + | alpha64 | alpha64ev[4-8] | alpha64ev56 | alpha64ev6[78] | alpha64pca5[67] \ + | am33_2.0 \ + | arc | arm | arm[bl]e | arme[lb] | armv[2345] | armv[345][lb] | avr | avr32 \ + | bfin \ + | c4x | clipper \ + | d10v | d30v | dlx | dsp16xx \ + | fido | fr30 | frv \ + | h8300 | h8500 | hppa | hppa1.[01] | hppa2.0 | hppa2.0[nw] | hppa64 \ + | i370 | i860 | i960 | ia64 \ + | ip2k | iq2000 \ + | lm32 \ + | m32c | m32r | m32rle | m68000 | m68k | m88k \ + | maxq | mb | microblaze | mcore | mep | metag \ + | mips | mipsbe | mipseb | mipsel | mipsle \ + | mips16 \ + | mips64 | mips64el \ + | mips64octeon | mips64octeonel \ + | mips64orion | mips64orionel \ + | mips64r5900 | mips64r5900el \ + | mips64vr | mips64vrel \ + | mips64vr4100 | mips64vr4100el \ + | mips64vr4300 | mips64vr4300el \ + | mips64vr5000 | mips64vr5000el \ + | mips64vr5900 | mips64vr5900el \ + | mipsisa32 | mipsisa32el \ + | mipsisa32r2 | mipsisa32r2el \ + | mipsisa64 | mipsisa64el \ + | mipsisa64r2 | mipsisa64r2el \ + | mipsisa64sb1 | mipsisa64sb1el \ + | mipsisa64sr71k | mipsisa64sr71kel \ + | mipstx39 | mipstx39el \ + | mn10200 | mn10300 \ + | moxie \ + | mt \ + | msp430 \ + | nios | nios2 \ + | ns16k | ns32k \ + | or32 \ + | pdp10 | pdp11 | pj | pjl \ + | powerpc | powerpc64 | powerpc64le | powerpcle | ppcbe \ + | pyramid \ + | rx \ + | score \ + | sh | sh[1234] | sh[24]a | sh[24]aeb | sh[23]e | sh[34]eb | sheb | shbe | shle | sh[1234]le | sh3ele \ + | sh64 | sh64le \ + | sparc | sparc64 | sparc64b | sparc64v | sparc86x | sparclet | sparclite \ + | sparcv8 | sparcv9 | sparcv9b | sparcv9v \ + | spu | strongarm \ + | tahoe | thumb | tic4x | tic80 | tron \ + | ubicom32 \ + | v850 | v850e \ + | we32k \ + | x86 | xc16x | xscale | xscalee[bl] | xstormy16 | xtensa \ + | z8k | z80) + basic_machine=$basic_machine-unknown + ;; + m6811 | m68hc11 | m6812 | m68hc12 | picochip) + # Motorola 68HC11/12. + basic_machine=$basic_machine-unknown + os=-none + ;; + m88110 | m680[12346]0 | m683?2 | m68360 | m5200 | v70 | w65 | z8k) + ;; + ms1) + basic_machine=mt-unknown + ;; + + # We use `pc' rather than `unknown' + # because (1) that's what they normally are, and + # (2) the word "unknown" tends to confuse beginning users. + i*86 | x86_64) + basic_machine=$basic_machine-pc + ;; + # Object if more than one company name word. + *-*-*) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; + # Recognize the basic CPU types with company name. + 580-* \ + | a29k-* \ + | alpha-* | alphaev[4-8]-* | alphaev56-* | alphaev6[78]-* \ + | alpha64-* | alpha64ev[4-8]-* | alpha64ev56-* | alpha64ev6[78]-* \ + | alphapca5[67]-* | alpha64pca5[67]-* | arc-* \ + | arm-* | armbe-* | armle-* | armeb-* | armv*-* \ + | avr-* | avr32-* \ + | bfin-* | bs2000-* \ + | c[123]* | c30-* | [cjt]90-* | c4x-* | c54x-* | c55x-* | c6x-* \ + | clipper-* | craynv-* | cydra-* \ + | d10v-* | d30v-* | dlx-* \ + | elxsi-* \ + | f30[01]-* | f700-* | fido-* | fr30-* | frv-* | fx80-* \ + | h8300-* | h8500-* \ + | hppa-* | hppa1.[01]-* | hppa2.0-* | hppa2.0[nw]-* | hppa64-* \ + | i*86-* | i860-* | i960-* | ia64-* \ + | ip2k-* | iq2000-* \ + | lm32-* \ + | m32c-* | m32r-* | m32rle-* \ + | m68000-* | m680[012346]0-* | m68360-* | m683?2-* | m68k-* \ + | m88110-* | m88k-* | maxq-* | mcore-* | metag-* | microblaze-* \ + | mips-* | mipsbe-* | mipseb-* | mipsel-* | mipsle-* \ + | mips16-* \ + | mips64-* | mips64el-* \ + | mips64octeon-* | mips64octeonel-* \ + | mips64orion-* | mips64orionel-* \ + | mips64r5900-* | mips64r5900el-* \ + | mips64vr-* | mips64vrel-* \ + | mips64vr4100-* | mips64vr4100el-* \ + | mips64vr4300-* | mips64vr4300el-* \ + | mips64vr5000-* | mips64vr5000el-* \ + | mips64vr5900-* | mips64vr5900el-* \ + | mipsisa32-* | mipsisa32el-* \ + | mipsisa32r2-* | mipsisa32r2el-* \ + | mipsisa64-* | mipsisa64el-* \ + | mipsisa64r2-* | mipsisa64r2el-* \ + | mipsisa64sb1-* | mipsisa64sb1el-* \ + | mipsisa64sr71k-* | mipsisa64sr71kel-* \ + | mipstx39-* | mipstx39el-* \ + | mmix-* \ + | mt-* \ + | msp430-* \ + | nios-* | nios2-* \ + | none-* | np1-* | ns16k-* | ns32k-* \ + | orion-* \ + | pdp10-* | pdp11-* | pj-* | pjl-* | pn-* | power-* \ + | powerpc-* | powerpc64-* | powerpc64le-* | powerpcle-* | ppcbe-* \ + | pyramid-* \ + | romp-* | rs6000-* | rx-* \ + | sh-* | sh[1234]-* | sh[24]a-* | sh[24]aeb-* | sh[23]e-* | sh[34]eb-* | sheb-* | shbe-* \ + | shle-* | sh[1234]le-* | sh3ele-* | sh64-* | sh64le-* \ + | sparc-* | sparc64-* | sparc64b-* | sparc64v-* | sparc86x-* | sparclet-* \ + | sparclite-* \ + | sparcv8-* | sparcv9-* | sparcv9b-* | sparcv9v-* | strongarm-* | sv1-* | sx?-* \ + | tahoe-* | thumb-* \ + | tic30-* | tic4x-* | tic54x-* | tic55x-* | tic6x-* | tic80-* | tile-* \ + | tron-* \ + | ubicom32-* \ + | v850-* | v850e-* | vax-* \ + | we32k-* \ + | x86-* | x86_64-* | xc16x-* | xps100-* | xscale-* | xscalee[bl]-* \ + | xstormy16-* | xtensa*-* \ + | ymp-* \ + | z8k-* | z80-*) + ;; + # Recognize the basic CPU types without company name, with glob match. + xtensa*) + basic_machine=$basic_machine-unknown + ;; + # Recognize the various machine names and aliases which stand + # for a CPU type and a company and sometimes even an OS. + 386bsd) + basic_machine=i386-unknown + os=-bsd + ;; + 3b1 | 7300 | 7300-att | att-7300 | pc7300 | safari | unixpc) + basic_machine=m68000-att + ;; + 3b*) + basic_machine=we32k-att + ;; + a29khif) + basic_machine=a29k-amd + os=-udi + ;; + abacus) + basic_machine=abacus-unknown + ;; + adobe68k) + basic_machine=m68010-adobe + os=-scout + ;; + alliant | fx80) + basic_machine=fx80-alliant + ;; + altos | altos3068) + basic_machine=m68k-altos + ;; + am29k) + basic_machine=a29k-none + os=-bsd + ;; + amd64) + basic_machine=x86_64-pc + ;; + amd64-*) + basic_machine=x86_64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + amdahl) + basic_machine=580-amdahl + os=-sysv + ;; + amiga | amiga-*) + basic_machine=m68k-unknown + ;; + amigaos | amigados) + basic_machine=m68k-unknown + os=-amigaos + ;; + amigaunix | amix) + basic_machine=m68k-unknown + os=-sysv4 + ;; + apollo68) + basic_machine=m68k-apollo + os=-sysv + ;; + apollo68bsd) + basic_machine=m68k-apollo + os=-bsd + ;; + aros) + basic_machine=i386-pc + os=-aros + ;; + aux) + basic_machine=m68k-apple + os=-aux + ;; + balance) + basic_machine=ns32k-sequent + os=-dynix + ;; + blackfin) + basic_machine=bfin-unknown + os=-linux + ;; + blackfin-*) + basic_machine=bfin-`echo $basic_machine | sed 's/^[^-]*-//'` + os=-linux + ;; + bluegene*) + basic_machine=powerpc-ibm + os=-cnk + ;; + c90) + basic_machine=c90-cray + os=-unicos + ;; + cegcc) + basic_machine=arm-unknown + os=-cegcc + ;; + convex-c1) + basic_machine=c1-convex + os=-bsd + ;; + convex-c2) + basic_machine=c2-convex + os=-bsd + ;; + convex-c32) + basic_machine=c32-convex + os=-bsd + ;; + convex-c34) + basic_machine=c34-convex + os=-bsd + ;; + convex-c38) + basic_machine=c38-convex + os=-bsd + ;; + cray | j90) + basic_machine=j90-cray + os=-unicos + ;; + craynv) + basic_machine=craynv-cray + os=-unicosmp + ;; + cr16) + basic_machine=cr16-unknown + os=-elf + ;; + crds | unos) + basic_machine=m68k-crds + ;; + crisv32 | crisv32-* | etraxfs*) + basic_machine=crisv32-axis + ;; + cris | cris-* | etrax*) + basic_machine=cris-axis + ;; + crx) + basic_machine=crx-unknown + os=-elf + ;; + da30 | da30-*) + basic_machine=m68k-da30 + ;; + decstation | decstation-3100 | pmax | pmax-* | pmin | dec3100 | decstatn) + basic_machine=mips-dec + ;; + decsystem10* | dec10*) + basic_machine=pdp10-dec + os=-tops10 + ;; + decsystem20* | dec20*) + basic_machine=pdp10-dec + os=-tops20 + ;; + delta | 3300 | motorola-3300 | motorola-delta \ + | 3300-motorola | delta-motorola) + basic_machine=m68k-motorola + ;; + delta88) + basic_machine=m88k-motorola + os=-sysv3 + ;; + dicos) + basic_machine=i686-pc + os=-dicos + ;; + djgpp) + basic_machine=i586-pc + os=-msdosdjgpp + ;; + dpx20 | dpx20-*) + basic_machine=rs6000-bull + os=-bosx + ;; + dpx2* | dpx2*-bull) + basic_machine=m68k-bull + os=-sysv3 + ;; + ebmon29k) + basic_machine=a29k-amd + os=-ebmon + ;; + elxsi) + basic_machine=elxsi-elxsi + os=-bsd + ;; + encore | umax | mmax) + basic_machine=ns32k-encore + ;; + es1800 | OSE68k | ose68k | ose | OSE) + basic_machine=m68k-ericsson + os=-ose + ;; + fx2800) + basic_machine=i860-alliant + ;; + genix) + basic_machine=ns32k-ns + ;; + gmicro) + basic_machine=tron-gmicro + os=-sysv + ;; + go32) + basic_machine=i386-pc + os=-go32 + ;; + h3050r* | hiux*) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + h8300hms) + basic_machine=h8300-hitachi + os=-hms + ;; + h8300xray) + basic_machine=h8300-hitachi + os=-xray + ;; + h8500hms) + basic_machine=h8500-hitachi + os=-hms + ;; + harris) + basic_machine=m88k-harris + os=-sysv3 + ;; + hp300-*) + basic_machine=m68k-hp + ;; + hp300bsd) + basic_machine=m68k-hp + os=-bsd + ;; + hp300hpux) + basic_machine=m68k-hp + os=-hpux + ;; + hp3k9[0-9][0-9] | hp9[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k2[0-9][0-9] | hp9k31[0-9]) + basic_machine=m68000-hp + ;; + hp9k3[2-9][0-9]) + basic_machine=m68k-hp + ;; + hp9k6[0-9][0-9] | hp6[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hp9k7[0-79][0-9] | hp7[0-79][0-9]) + basic_machine=hppa1.1-hp + ;; + hp9k78[0-9] | hp78[0-9]) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[67]1 | hp8[67]1 | hp9k80[24] | hp80[24] | hp9k8[78]9 | hp8[78]9 | hp9k893 | hp893) + # FIXME: really hppa2.0-hp + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][13679] | hp8[0-9][13679]) + basic_machine=hppa1.1-hp + ;; + hp9k8[0-9][0-9] | hp8[0-9][0-9]) + basic_machine=hppa1.0-hp + ;; + hppa-next) + os=-nextstep3 + ;; + hppaosf) + basic_machine=hppa1.1-hp + os=-osf + ;; + hppro) + basic_machine=hppa1.1-hp + os=-proelf + ;; + i370-ibm* | ibm*) + basic_machine=i370-ibm + ;; +# I'm not sure what "Sysv32" means. Should this be sysv3.2? + i*86v32) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv32 + ;; + i*86v4*) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv4 + ;; + i*86v) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-sysv + ;; + i*86sol2) + basic_machine=`echo $1 | sed -e 's/86.*/86-pc/'` + os=-solaris2 + ;; + i386mach) + basic_machine=i386-mach + os=-mach + ;; + i386-vsta | vsta) + basic_machine=i386-unknown + os=-vsta + ;; + iris | iris4d) + basic_machine=mips-sgi + case $os in + -irix*) + ;; + *) + os=-irix4 + ;; + esac + ;; + isi68 | isi) + basic_machine=m68k-isi + os=-sysv + ;; + m68knommu) + basic_machine=m68k-unknown + os=-linux + ;; + m68knommu-*) + basic_machine=m68k-`echo $basic_machine | sed 's/^[^-]*-//'` + os=-linux + ;; + m88k-omron*) + basic_machine=m88k-omron + ;; + magnum | m3230) + basic_machine=mips-mips + os=-sysv + ;; + merlin) + basic_machine=ns32k-utek + os=-sysv + ;; + microblaze) + basic_machine=microblaze-xilinx + ;; + mingw32) + basic_machine=i386-pc + os=-mingw32 + ;; + mingw32ce) + basic_machine=arm-unknown + os=-mingw32ce + ;; + miniframe) + basic_machine=m68000-convergent + ;; + *mint | -mint[0-9]* | *MiNT | *MiNT[0-9]*) + basic_machine=m68k-atari + os=-mint + ;; + mips3*-*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'` + ;; + mips3*) + basic_machine=`echo $basic_machine | sed -e 's/mips3/mips64/'`-unknown + ;; + monitor) + basic_machine=m68k-rom68k + os=-coff + ;; + morphos) + basic_machine=powerpc-unknown + os=-morphos + ;; + msdos) + basic_machine=i386-pc + os=-msdos + ;; + ms1-*) + basic_machine=`echo $basic_machine | sed -e 's/ms1-/mt-/'` + ;; + mvs) + basic_machine=i370-ibm + os=-mvs + ;; + ncr3000) + basic_machine=i486-ncr + os=-sysv4 + ;; + netbsd386) + basic_machine=i386-unknown + os=-netbsd + ;; + netwinder) + basic_machine=armv4l-rebel + os=-linux + ;; + news | news700 | news800 | news900) + basic_machine=m68k-sony + os=-newsos + ;; + news1000) + basic_machine=m68030-sony + os=-newsos + ;; + news-3600 | risc-news) + basic_machine=mips-sony + os=-newsos + ;; + necv70) + basic_machine=v70-nec + os=-sysv + ;; + next | m*-next ) + basic_machine=m68k-next + case $os in + -nextstep* ) + ;; + -ns2*) + os=-nextstep2 + ;; + *) + os=-nextstep3 + ;; + esac + ;; + nh3000) + basic_machine=m68k-harris + os=-cxux + ;; + nh[45]000) + basic_machine=m88k-harris + os=-cxux + ;; + nindy960) + basic_machine=i960-intel + os=-nindy + ;; + mon960) + basic_machine=i960-intel + os=-mon960 + ;; + nonstopux) + basic_machine=mips-compaq + os=-nonstopux + ;; + np1) + basic_machine=np1-gould + ;; + nsr-tandem) + basic_machine=nsr-tandem + ;; + op50n-* | op60c-*) + basic_machine=hppa1.1-oki + os=-proelf + ;; + openrisc | openrisc-*) + basic_machine=or32-unknown + ;; + os400) + basic_machine=powerpc-ibm + os=-os400 + ;; + OSE68000 | ose68000) + basic_machine=m68000-ericsson + os=-ose + ;; + os68k) + basic_machine=m68k-none + os=-os68k + ;; + pa-hitachi) + basic_machine=hppa1.1-hitachi + os=-hiuxwe2 + ;; + paragon) + basic_machine=i860-intel + os=-osf + ;; + parisc) + basic_machine=hppa-unknown + os=-linux + ;; + parisc-*) + basic_machine=hppa-`echo $basic_machine | sed 's/^[^-]*-//'` + os=-linux + ;; + pbd) + basic_machine=sparc-tti + ;; + pbb) + basic_machine=m68k-tti + ;; + pc532 | pc532-*) + basic_machine=ns32k-pc532 + ;; + pc98) + basic_machine=i386-pc + ;; + pc98-*) + basic_machine=i386-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium | p5 | k5 | k6 | nexgen | viac3) + basic_machine=i586-pc + ;; + pentiumpro | p6 | 6x86 | athlon | athlon_*) + basic_machine=i686-pc + ;; + pentiumii | pentium2 | pentiumiii | pentium3) + basic_machine=i686-pc + ;; + pentium4) + basic_machine=i786-pc + ;; + pentium-* | p5-* | k5-* | k6-* | nexgen-* | viac3-*) + basic_machine=i586-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumpro-* | p6-* | 6x86-* | athlon-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentiumii-* | pentium2-* | pentiumiii-* | pentium3-*) + basic_machine=i686-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pentium4-*) + basic_machine=i786-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + pn) + basic_machine=pn-gould + ;; + power) basic_machine=power-ibm + ;; + ppc) basic_machine=powerpc-unknown + ;; + ppc-*) basic_machine=powerpc-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppcle | powerpclittle | ppc-le | powerpc-little) + basic_machine=powerpcle-unknown + ;; + ppcle-* | powerpclittle-*) + basic_machine=powerpcle-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64) basic_machine=powerpc64-unknown + ;; + ppc64-*) basic_machine=powerpc64-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ppc64le | powerpc64little | ppc64-le | powerpc64-little) + basic_machine=powerpc64le-unknown + ;; + ppc64le-* | powerpc64little-*) + basic_machine=powerpc64le-`echo $basic_machine | sed 's/^[^-]*-//'` + ;; + ps2) + basic_machine=i386-ibm + ;; + pw32) + basic_machine=i586-unknown + os=-pw32 + ;; + rdos) + basic_machine=i386-pc + os=-rdos + ;; + rom68k) + basic_machine=m68k-rom68k + os=-coff + ;; + rm[46]00) + basic_machine=mips-siemens + ;; + rtpc | rtpc-*) + basic_machine=romp-ibm + ;; + s390 | s390-*) + basic_machine=s390-ibm + ;; + s390x | s390x-*) + basic_machine=s390x-ibm + ;; + sa29200) + basic_machine=a29k-amd + os=-udi + ;; + sb1) + basic_machine=mipsisa64sb1-unknown + ;; + sb1el) + basic_machine=mipsisa64sb1el-unknown + ;; + sde) + basic_machine=mipsisa32-sde + os=-elf + ;; + sei) + basic_machine=mips-sei + os=-seiux + ;; + sequent) + basic_machine=i386-sequent + ;; + sh) + basic_machine=sh-hitachi + os=-hms + ;; + sh5el) + basic_machine=sh5le-unknown + ;; + sh64) + basic_machine=sh64-unknown + ;; + sparclite-wrs | simso-wrs) + basic_machine=sparclite-wrs + os=-vxworks + ;; + sps7) + basic_machine=m68k-bull + os=-sysv2 + ;; + spur) + basic_machine=spur-unknown + ;; + st2000) + basic_machine=m68k-tandem + ;; + stratus) + basic_machine=i860-stratus + os=-sysv4 + ;; + sun2) + basic_machine=m68000-sun + ;; + sun2os3) + basic_machine=m68000-sun + os=-sunos3 + ;; + sun2os4) + basic_machine=m68000-sun + os=-sunos4 + ;; + sun3os3) + basic_machine=m68k-sun + os=-sunos3 + ;; + sun3os4) + basic_machine=m68k-sun + os=-sunos4 + ;; + sun4os3) + basic_machine=sparc-sun + os=-sunos3 + ;; + sun4os4) + basic_machine=sparc-sun + os=-sunos4 + ;; + sun4sol2) + basic_machine=sparc-sun + os=-solaris2 + ;; + sun3 | sun3-*) + basic_machine=m68k-sun + ;; + sun4) + basic_machine=sparc-sun + ;; + sun386 | sun386i | roadrunner) + basic_machine=i386-sun + ;; + sv1) + basic_machine=sv1-cray + os=-unicos + ;; + symmetry) + basic_machine=i386-sequent + os=-dynix + ;; + t3e) + basic_machine=alphaev5-cray + os=-unicos + ;; + t90) + basic_machine=t90-cray + os=-unicos + ;; + tic54x | c54x*) + basic_machine=tic54x-unknown + os=-coff + ;; + tic55x | c55x*) + basic_machine=tic55x-unknown + os=-coff + ;; + tic6x | c6x*) + basic_machine=tic6x-unknown + os=-coff + ;; + tile*) + basic_machine=tile-unknown + os=-linux-gnu + ;; + tx39) + basic_machine=mipstx39-unknown + ;; + tx39el) + basic_machine=mipstx39el-unknown + ;; + toad1) + basic_machine=pdp10-xkl + os=-tops20 + ;; + tower | tower-32) + basic_machine=m68k-ncr + ;; + tpf) + basic_machine=s390x-ibm + os=-tpf + ;; + udi29k) + basic_machine=a29k-amd + os=-udi + ;; + ultra3) + basic_machine=a29k-nyu + os=-sym1 + ;; + v810 | necv810) + basic_machine=v810-nec + os=-none + ;; + vaxv) + basic_machine=vax-dec + os=-sysv + ;; + vms) + basic_machine=vax-dec + os=-vms + ;; + vpp*|vx|vx-*) + basic_machine=f301-fujitsu + ;; + vxworks960) + basic_machine=i960-wrs + os=-vxworks + ;; + vxworks68) + basic_machine=m68k-wrs + os=-vxworks + ;; + vxworks29k) + basic_machine=a29k-wrs + os=-vxworks + ;; + w65*) + basic_machine=w65-wdc + os=-none + ;; + w89k-*) + basic_machine=hppa1.1-winbond + os=-proelf + ;; + xbox) + basic_machine=i686-pc + os=-mingw32 + ;; + xps | xps100) + basic_machine=xps100-honeywell + ;; + ymp) + basic_machine=ymp-cray + os=-unicos + ;; + z8k-*-coff) + basic_machine=z8k-unknown + os=-sim + ;; + z80-*-coff) + basic_machine=z80-unknown + os=-sim + ;; + none) + basic_machine=none-none + os=-none + ;; + +# Here we handle the default manufacturer of certain CPU types. It is in +# some cases the only manufacturer, in others, it is the most popular. + w89k) + basic_machine=hppa1.1-winbond + ;; + op50n) + basic_machine=hppa1.1-oki + ;; + op60c) + basic_machine=hppa1.1-oki + ;; + romp) + basic_machine=romp-ibm + ;; + mmix) + basic_machine=mmix-knuth + ;; + rs6000) + basic_machine=rs6000-ibm + ;; + vax) + basic_machine=vax-dec + ;; + pdp10) + # there are many clones, so DEC is not a safe bet + basic_machine=pdp10-unknown + ;; + pdp11) + basic_machine=pdp11-dec + ;; + we32k) + basic_machine=we32k-att + ;; + sh[1234] | sh[24]a | sh[24]aeb | sh[34]eb | sh[1234]le | sh[23]ele) + basic_machine=sh-unknown + ;; + sparc | sparcv8 | sparcv9 | sparcv9b | sparcv9v) + basic_machine=sparc-sun + ;; + cydra) + basic_machine=cydra-cydrome + ;; + orion) + basic_machine=orion-highlevel + ;; + orion105) + basic_machine=clipper-highlevel + ;; + mac | mpw | mac-mpw) + basic_machine=m68k-apple + ;; + pmac | pmac-mpw) + basic_machine=powerpc-apple + ;; + *-unknown) + # Make sure to match an already-canonicalized machine name. + ;; + *) + echo Invalid configuration \`$1\': machine \`$basic_machine\' not recognized 1>&2 + exit 1 + ;; +esac + +# Here we canonicalize certain aliases for manufacturers. +case $basic_machine in + *-digital*) + basic_machine=`echo $basic_machine | sed 's/digital.*/dec/'` + ;; + *-commodore*) + basic_machine=`echo $basic_machine | sed 's/commodore.*/cbm/'` + ;; + *) + ;; +esac + +# Decode manufacturer-specific aliases for certain operating systems. + +if [ x"$os" != x"" ] +then +case $os in + # First match some system type aliases + # that might get confused with valid system types. + # -solaris* is a basic system type, with this one exception. + -auroraux) + os=-auroraux + ;; + -solaris1 | -solaris1.*) + os=`echo $os | sed -e 's|solaris1|sunos4|'` + ;; + -solaris) + os=-solaris2 + ;; + -svr4*) + os=-sysv4 + ;; + -unixware*) + os=-sysv4.2uw + ;; + -gnu/linux*) + os=`echo $os | sed -e 's|gnu/linux|linux-gnu|'` + ;; + # First accept the basic system types. + # The portable systems comes first. + # Each alternative MUST END IN A *, to match a version number. + # -sysv* is not here because it comes later, after sysvr4. + -gnu* | -bsd* | -mach* | -minix* | -genix* | -ultrix* | -irix* \ + | -*vms* | -sco* | -esix* | -isc* | -aix* | -cnk* | -sunos | -sunos[34]*\ + | -hpux* | -unos* | -osf* | -luna* | -dgux* | -auroraux* | -solaris* \ + | -sym* | -kopensolaris* \ + | -amigaos* | -amigados* | -msdos* | -newsos* | -unicos* | -aof* \ + | -aos* | -aros* \ + | -nindy* | -vxsim* | -vxworks* | -ebmon* | -hms* | -mvs* \ + | -clix* | -riscos* | -uniplus* | -iris* | -rtu* | -xenix* \ + | -hiux* | -386bsd* | -knetbsd* | -mirbsd* | -netbsd* \ + | -openbsd* | -solidbsd* \ + | -ekkobsd* | -kfreebsd* | -freebsd* | -riscix* | -lynxos* \ + | -bosx* | -nextstep* | -cxux* | -aout* | -elf* | -oabi* \ + | -ptx* | -coff* | -ecoff* | -winnt* | -domain* | -vsta* \ + | -udi* | -eabi* | -lites* | -ieee* | -go32* | -aux* \ + | -chorusos* | -chorusrdb* | -cegcc* \ + | -cygwin* | -pe* | -psos* | -moss* | -proelf* | -rtems* \ + | -mingw32* | -linux-gnu* | -linux-newlib* | -linux-uclibc* \ + | -uxpv* | -beos* | -mpeix* | -udk* \ + | -interix* | -uwin* | -mks* | -rhapsody* | -darwin* | -opened* \ + | -openstep* | -oskit* | -conix* | -pw32* | -nonstopux* \ + | -storm-chaos* | -tops10* | -tenex* | -tops20* | -its* \ + | -os2* | -vos* | -palmos* | -uclinux* | -nucleus* \ + | -morphos* | -superux* | -rtmk* | -rtmk-nova* | -windiss* \ + | -powermax* | -dnix* | -nx6 | -nx7 | -sei* | -dragonfly* \ + | -skyos* | -haiku* | -rdos* | -toppers* | -drops* | -es*) + # Remember, each alternative MUST END IN *, to match a version number. + ;; + -qnx*) + case $basic_machine in + x86-* | i*86-*) + ;; + *) + os=-nto$os + ;; + esac + ;; + -nto-qnx*) + ;; + -nto*) + os=`echo $os | sed -e 's|nto|nto-qnx|'` + ;; + -sim | -es1800* | -hms* | -xray | -os68k* | -none* | -v88r* \ + | -windows* | -osx | -abug | -netware* | -os9* | -beos* | -haiku* \ + | -macos* | -mpw* | -magic* | -mmixware* | -mon960* | -lnews*) + ;; + -mac*) + os=`echo $os | sed -e 's|mac|macos|'` + ;; + -linux-dietlibc) + os=-linux-dietlibc + ;; + -linux*) + os=`echo $os | sed -e 's|linux|linux-gnu|'` + ;; + -sunos5*) + os=`echo $os | sed -e 's|sunos5|solaris2|'` + ;; + -sunos6*) + os=`echo $os | sed -e 's|sunos6|solaris3|'` + ;; + -opened*) + os=-openedition + ;; + -os400*) + os=-os400 + ;; + -wince*) + os=-wince + ;; + -osfrose*) + os=-osfrose + ;; + -osf*) + os=-osf + ;; + -utek*) + os=-bsd + ;; + -dynix*) + os=-bsd + ;; + -acis*) + os=-aos + ;; + -atheos*) + os=-atheos + ;; + -syllable*) + os=-syllable + ;; + -386bsd) + os=-bsd + ;; + -ctix* | -uts*) + os=-sysv + ;; + -nova*) + os=-rtmk-nova + ;; + -ns2 ) + os=-nextstep2 + ;; + -nsk*) + os=-nsk + ;; + # Preserve the version number of sinix5. + -sinix5.*) + os=`echo $os | sed -e 's|sinix|sysv|'` + ;; + -sinix*) + os=-sysv4 + ;; + -tpf*) + os=-tpf + ;; + -triton*) + os=-sysv3 + ;; + -oss*) + os=-sysv3 + ;; + -svr4) + os=-sysv4 + ;; + -svr3) + os=-sysv3 + ;; + -sysvr4) + os=-sysv4 + ;; + # This must come after -sysvr4. + -sysv*) + ;; + -ose*) + os=-ose + ;; + -es1800*) + os=-ose + ;; + -xenix) + os=-xenix + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + os=-mint + ;; + -aros*) + os=-aros + ;; + -kaos*) + os=-kaos + ;; + -zvmoe) + os=-zvmoe + ;; + -dicos*) + os=-dicos + ;; + -none) + ;; + *) + # Get rid of the `-' at the beginning of $os. + os=`echo $os | sed 's/[^-]*-//'` + echo Invalid configuration \`$1\': system \`$os\' not recognized 1>&2 + exit 1 + ;; +esac +else + +# Here we handle the default operating systems that come with various machines. +# The value should be what the vendor currently ships out the door with their +# machine or put another way, the most popular os provided with the machine. + +# Note that if you're going to try to match "-MANUFACTURER" here (say, +# "-sun"), then you have to tell the case statement up towards the top +# that MANUFACTURER isn't an operating system. Otherwise, code above +# will signal an error saying that MANUFACTURER isn't an operating +# system, and we'll never get to this point. + +case $basic_machine in + score-*) + os=-elf + ;; + spu-*) + os=-elf + ;; + *-acorn) + os=-riscix1.2 + ;; + arm*-rebel) + os=-linux + ;; + arm*-semi) + os=-aout + ;; + c4x-* | tic4x-*) + os=-coff + ;; + # This must come before the *-dec entry. + pdp10-*) + os=-tops20 + ;; + pdp11-*) + os=-none + ;; + *-dec | vax-*) + os=-ultrix4.2 + ;; + m68*-apollo) + os=-domain + ;; + i386-sun) + os=-sunos4.0.2 + ;; + m68000-sun) + os=-sunos3 + # This also exists in the configure program, but was not the + # default. + # os=-sunos4 + ;; + m68*-cisco) + os=-aout + ;; + mep-*) + os=-elf + ;; + mips*-cisco) + os=-elf + ;; + mips*-*) + os=-elf + ;; + or32-*) + os=-coff + ;; + *-tti) # must be before sparc entry or we get the wrong os. + os=-sysv3 + ;; + sparc-* | *-sun) + os=-sunos4.1.1 + ;; + *-be) + os=-beos + ;; + *-haiku) + os=-haiku + ;; + *-ibm) + os=-aix + ;; + *-knuth) + os=-mmixware + ;; + *-wec) + os=-proelf + ;; + *-winbond) + os=-proelf + ;; + *-oki) + os=-proelf + ;; + *-hp) + os=-hpux + ;; + *-hitachi) + os=-hiux + ;; + i860-* | *-att | *-ncr | *-altos | *-motorola | *-convergent) + os=-sysv + ;; + *-cbm) + os=-amigaos + ;; + *-dg) + os=-dgux + ;; + *-dolphin) + os=-sysv3 + ;; + m68k-ccur) + os=-rtu + ;; + m88k-omron*) + os=-luna + ;; + *-next ) + os=-nextstep + ;; + *-sequent) + os=-ptx + ;; + *-crds) + os=-unos + ;; + *-ns) + os=-genix + ;; + i370-*) + os=-mvs + ;; + *-next) + os=-nextstep3 + ;; + *-gould) + os=-sysv + ;; + *-highlevel) + os=-bsd + ;; + *-encore) + os=-bsd + ;; + *-sgi) + os=-irix + ;; + *-siemens) + os=-sysv4 + ;; + *-masscomp) + os=-rtu + ;; + f30[01]-fujitsu | f700-fujitsu) + os=-uxpv + ;; + *-rom68k) + os=-coff + ;; + *-*bug) + os=-coff + ;; + *-apple) + os=-macos + ;; + *-atari*) + os=-mint + ;; + *) + os=-none + ;; +esac +fi + +# Here we handle the case where we know the os, and the CPU type, but not the +# manufacturer. We pick the logical manufacturer. +vendor=unknown +case $basic_machine in + *-unknown) + case $os in + -riscix*) + vendor=acorn + ;; + -sunos*) + vendor=sun + ;; + -cnk*|-aix*) + vendor=ibm + ;; + -beos*) + vendor=be + ;; + -hpux*) + vendor=hp + ;; + -mpeix*) + vendor=hp + ;; + -hiux*) + vendor=hitachi + ;; + -unos*) + vendor=crds + ;; + -dgux*) + vendor=dg + ;; + -luna*) + vendor=omron + ;; + -genix*) + vendor=ns + ;; + -mvs* | -opened*) + vendor=ibm + ;; + -os400*) + vendor=ibm + ;; + -ptx*) + vendor=sequent + ;; + -tpf*) + vendor=ibm + ;; + -vxsim* | -vxworks* | -windiss*) + vendor=wrs + ;; + -aux*) + vendor=apple + ;; + -hms*) + vendor=hitachi + ;; + -mpw* | -macos*) + vendor=apple + ;; + -*mint | -mint[0-9]* | -*MiNT | -MiNT[0-9]*) + vendor=atari + ;; + -vos*) + vendor=stratus + ;; + esac + basic_machine=`echo $basic_machine | sed "s/unknown/$vendor/"` + ;; +esac + +echo $basic_machine$os +exit + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "timestamp='" +# time-stamp-format: "%:y-%02m-%02d" +# time-stamp-end: "'" +# End: diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/configure b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/configure new file mode 100755 index 00000000..2b2a912e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/configure @@ -0,0 +1,14547 @@ +#! /bin/sh +# Guess values for system-dependent variables and create Makefiles. +# Generated by GNU Autoconf 2.69. +# +# +# Copyright (C) 1992-1996, 1998-2012 Free Software Foundation, Inc. +# +# +# This configure script is free software; the Free Software Foundation +# gives unlimited permission to copy, distribute and modify it. +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + +# Use a proper internal environment variable to ensure we don't fall + # into an infinite loop, continuously re-executing ourselves. + if test x"${_as_can_reexec}" != xno && test "x$CONFIG_SHELL" != x; then + _as_can_reexec=no; export _as_can_reexec; + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 +as_fn_exit 255 + fi + # We don't want this to propagate to other subprocesses. + { _as_can_reexec=; unset _as_can_reexec;} +if test "x$CONFIG_SHELL" = x; then + as_bourne_compatible="if test -n \"\${ZSH_VERSION+set}\" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on \${1+\"\$@\"}, which + # is contrary to our usage. Disable this feature. + alias -g '\${1+\"\$@\"}'='\"\$@\"' + setopt NO_GLOB_SUBST +else + case \`(set -o) 2>/dev/null\` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi +" + as_required="as_fn_return () { (exit \$1); } +as_fn_success () { as_fn_return 0; } +as_fn_failure () { as_fn_return 1; } +as_fn_ret_success () { return 0; } +as_fn_ret_failure () { return 1; } + +exitcode=0 +as_fn_success || { exitcode=1; echo as_fn_success failed.; } +as_fn_failure && { exitcode=1; echo as_fn_failure succeeded.; } +as_fn_ret_success || { exitcode=1; echo as_fn_ret_success failed.; } +as_fn_ret_failure && { exitcode=1; echo as_fn_ret_failure succeeded.; } +if ( set x; as_fn_ret_success y && test x = \"\$1\" ); then : + +else + exitcode=1; echo positional parameters were not saved. +fi +test x\$exitcode = x0 || exit 1 +test -x / || exit 1" + as_suggested=" as_lineno_1=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_1a=\$LINENO + as_lineno_2=";as_suggested=$as_suggested$LINENO;as_suggested=$as_suggested" as_lineno_2a=\$LINENO + eval 'test \"x\$as_lineno_1'\$as_run'\" != \"x\$as_lineno_2'\$as_run'\" && + test \"x\`expr \$as_lineno_1'\$as_run' + 1\`\" = \"x\$as_lineno_2'\$as_run'\"' || exit 1 +test \$(( 1 + 1 )) = 2 || exit 1" + if (eval "$as_required") 2>/dev/null; then : + as_have_required=yes +else + as_have_required=no +fi + if test x$as_have_required = xyes && (eval "$as_suggested") 2>/dev/null; then : + +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +as_found=false +for as_dir in /bin$PATH_SEPARATOR/usr/bin$PATH_SEPARATOR$PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + as_found=: + case $as_dir in #( + /*) + for as_base in sh bash ksh sh5; do + # Try only shells that exist, to save several forks. + as_shell=$as_dir/$as_base + if { test -f "$as_shell" || test -f "$as_shell.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$as_shell"; } 2>/dev/null; then : + CONFIG_SHELL=$as_shell as_have_required=yes + if { $as_echo "$as_bourne_compatible""$as_suggested" | as_run=a "$as_shell"; } 2>/dev/null; then : + break 2 +fi +fi + done;; + esac + as_found=false +done +$as_found || { if { test -f "$SHELL" || test -f "$SHELL.exe"; } && + { $as_echo "$as_bourne_compatible""$as_required" | as_run=a "$SHELL"; } 2>/dev/null; then : + CONFIG_SHELL=$SHELL as_have_required=yes +fi; } +IFS=$as_save_IFS + + + if test "x$CONFIG_SHELL" != x; then : + export CONFIG_SHELL + # We cannot yet assume a decent shell, so we have to provide a +# neutralization value for shells without unset; and this also +# works around shells that cannot unset nonexistent variables. +# Preserve -v and -x to the replacement shell. +BASH_ENV=/dev/null +ENV=/dev/null +(unset BASH_ENV) >/dev/null 2>&1 && unset BASH_ENV ENV +case $- in # (((( + *v*x* | *x*v* ) as_opts=-vx ;; + *v* ) as_opts=-v ;; + *x* ) as_opts=-x ;; + * ) as_opts= ;; +esac +exec $CONFIG_SHELL $as_opts "$as_myself" ${1+"$@"} +# Admittedly, this is quite paranoid, since all the known shells bail +# out after a failed `exec'. +$as_echo "$0: could not re-execute with $CONFIG_SHELL" >&2 +exit 255 +fi + + if test x$as_have_required = xno; then : + $as_echo "$0: This script requires a shell more modern than all" + $as_echo "$0: the shells that I found on your system." + if test x${ZSH_VERSION+set} = xset ; then + $as_echo "$0: In particular, zsh $ZSH_VERSION has bugs and should" + $as_echo "$0: be upgraded to zsh 4.3.4 or later." + else + $as_echo "$0: Please tell bug-autoconf@gnu.org about your system, +$0: including any error possibly output before this +$0: message. Then install a modern shell, or manually run +$0: the script under such a shell if you do have one." + fi + exit 1 +fi +fi +fi +SHELL=${CONFIG_SHELL-/bin/sh} +export SHELL +# Unset more variables known to interfere with behavior of common tools. +CLICOLOR_FORCE= GREP_OPTIONS= +unset CLICOLOR_FORCE GREP_OPTIONS + +## --------------------- ## +## M4sh Shell Functions. ## +## --------------------- ## +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + + + as_lineno_1=$LINENO as_lineno_1a=$LINENO + as_lineno_2=$LINENO as_lineno_2a=$LINENO + eval 'test "x$as_lineno_1'$as_run'" != "x$as_lineno_2'$as_run'" && + test "x`expr $as_lineno_1'$as_run' + 1`" = "x$as_lineno_2'$as_run'"' || { + # Blame Lee E. McMahon (1931-1989) for sed's syntax. :-) + sed -n ' + p + /[$]LINENO/= + ' <$as_myself | + sed ' + s/[$]LINENO.*/&-/ + t lineno + b + :lineno + N + :loop + s/[$]LINENO\([^'$as_cr_alnum'_].*\n\)\(.*\)/\2\1\2/ + t loop + s/-\n.*// + ' >$as_me.lineno && + chmod +x "$as_me.lineno" || + { $as_echo "$as_me: error: cannot create $as_me.lineno; rerun with a POSIX shell" >&2; as_fn_exit 1; } + + # If we had to re-execute with $CONFIG_SHELL, we're ensured to have + # already done that, so ensure we don't try to do so again and fall + # in an infinite loop. This has already happened in practice. + _as_can_reexec=no; export _as_can_reexec + # Don't try to exec as it changes $[0], causing all sort of problems + # (the dirname of $[0] is not the place where we might find the + # original and so on. Autoconf is especially sensitive to this). + . "./$as_me.lineno" + # Exit status is that of the last command. + exit +} + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +test -n "$DJDIR" || exec 7<&0 &1 + +# Name of the host. +# hostname on some systems (SVR3.2, old GNU/Linux) returns a bogus exit status, +# so uname gets run too. +ac_hostname=`(hostname || uname -n) 2>/dev/null | sed 1q` + +# +# Initializations. +# +ac_default_prefix=/usr/local +ac_clean_files= +ac_config_libobj_dir=. +LIBOBJS= +cross_compiling=no +subdirs= +MFLAGS= +MAKEFLAGS= + +# Identity of this package. +PACKAGE_NAME= +PACKAGE_TARNAME= +PACKAGE_VERSION= +PACKAGE_STRING= +PACKAGE_BUGREPORT= +PACKAGE_URL= + +ac_unique_file="Src/zsh.h" +# Factoring default headers for most tests. +ac_includes_default="\ +#include +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_STAT_H +# include +#endif +#ifdef STDC_HEADERS +# include +# include +#else +# ifdef HAVE_STDLIB_H +# include +# endif +#endif +#ifdef HAVE_STRING_H +# if !defined STDC_HEADERS && defined HAVE_MEMORY_H +# include +# endif +# include +#endif +#ifdef HAVE_STRINGS_H +# include +#endif +#ifdef HAVE_INTTYPES_H +# include +#endif +#ifdef HAVE_STDINT_H +# include +#endif +#ifdef HAVE_UNISTD_H +# include +#endif" + +ac_header_list= +ac_subst_vars='LTLIBOBJS +LIBOBJS +EXTRAZSHOBJS +MOD_IMPORT_FUNCTION +MOD_IMPORT_VARIABLE +MOD_EXPORT +LINKMODS +L +IMPOPT +EXPOPT +EXTRA_LDFLAGS +E +DLLDFLAGS +DLCFLAGS +DLLD +DL_EXT +D +UNINSTLIB +INSTLIB +SHORTBOOTNAMES +RLIMITS_INC_H +ZSH_TERM_H +CURSES_KEYS_H +ZSH_CURSES_H +ERRNO_H +SIGNAL_H +ANSI2KNR +PAPERSIZE +TEXI2HTML +TEXI2PDF +TEXI2DVI +YODL_OPTIONS +YODL +LN_S +LN +AWK +INSTALL_DATA +INSTALL_SCRIPT +INSTALL_PROGRAM +SET_MAKE +ALLOCA +EGREP +GREP +U +CPP +LIBLDFLAGS +EXELDFLAGS +OBJEXT +EXEEXT +ac_ct_CC +CPPFLAGS +LDFLAGS +CFLAGS +CC +sitescriptdir +scriptdir +FUNCTIONS_SUBDIRS +fixed_sitefndir +sitefndir +fndir +additionalfpath +runhelp +runhelpdir +zlogout +zlogin +zprofile +zshrc +zshenv +tzsh +host_os +host_vendor +host_cpu +host +build_os +build_vendor +build_cpu +build +target_alias +host_alias +build_alias +LIBS +ECHO_T +ECHO_N +ECHO_C +DEFS +mandir +localedir +libdir +psdir +pdfdir +dvidir +htmldir +infodir +docdir +oldincludedir +includedir +localstatedir +sharedstatedir +sysconfdir +datadir +datarootdir +libexecdir +sbindir +bindir +program_transform_name +prefix +exec_prefix +PACKAGE_URL +PACKAGE_BUGREPORT +PACKAGE_STRING +PACKAGE_VERSION +PACKAGE_TARNAME +PACKAGE_NAME +PATH_SEPARATOR +SHELL' +ac_subst_files='CLEAN_MK +CONFIG_MK +DEFS_MK +VERSION_MK' +ac_user_opts=' +enable_option_checking +enable_cppflags +enable_cflags +enable_ldflags +enable_libs +enable_zsh_debug +enable_zsh_mem +enable_zsh_mem_debug +enable_zsh_mem_warning +enable_zsh_secure_free +enable_zsh_heap_debug +enable_zsh_valgrind +enable_zsh_hash_debug +enable_stack_allocation +enable_etcdir +enable_zshenv +enable_zshrc +enable_zprofile +enable_zlogin +enable_zlogout +enable_dynamic +enable_restricted_r +enable_locale +enable_ansi2knr +enable_runhelpdir +enable_fndir +enable_site_fndir +enable_function_subdirs +enable_additional_fpath +enable_scriptdir +enable_site_scriptdir +enable_custom_patchlevel +enable_maildir_support +enable_max_function_depth +enable_readnullcmd +enable_cap +enable_gdbm +enable_largefile +with_term_lib +with_tcsetpgrp +enable_multibyte +enable_unicode9 +enable_libc_musl +enable_dynamic_nss +' + ac_precious_vars='build_alias +host_alias +target_alias +CC +CFLAGS +LDFLAGS +LIBS +CPPFLAGS +CPP' + + +# Initialize some variables set by options. +ac_init_help= +ac_init_version=false +ac_unrecognized_opts= +ac_unrecognized_sep= +# The variables have the same names as the options, with +# dashes changed to underlines. +cache_file=/dev/null +exec_prefix=NONE +no_create= +no_recursion= +prefix=NONE +program_prefix=NONE +program_suffix=NONE +program_transform_name=s,x,x, +silent= +site= +srcdir= +verbose= +x_includes=NONE +x_libraries=NONE + +# Installation directory options. +# These are left unexpanded so users can "make install exec_prefix=/foo" +# and all the variables that are supposed to be based on exec_prefix +# by default will actually change. +# Use braces instead of parens because sh, perl, etc. also accept them. +# (The list follows the same order as the GNU Coding Standards.) +bindir='${exec_prefix}/bin' +sbindir='${exec_prefix}/sbin' +libexecdir='${exec_prefix}/libexec' +datarootdir='${prefix}/share' +datadir='${datarootdir}' +sysconfdir='${prefix}/etc' +sharedstatedir='${prefix}/com' +localstatedir='${prefix}/var' +includedir='${prefix}/include' +oldincludedir='/usr/include' +docdir='${datarootdir}/doc/${PACKAGE}' +infodir='${datarootdir}/info' +htmldir='${docdir}' +dvidir='${docdir}' +pdfdir='${docdir}' +psdir='${docdir}' +libdir='${exec_prefix}/lib' +localedir='${datarootdir}/locale' +mandir='${datarootdir}/man' + +ac_prev= +ac_dashdash= +for ac_option +do + # If the previous option needs an argument, assign it. + if test -n "$ac_prev"; then + eval $ac_prev=\$ac_option + ac_prev= + continue + fi + + case $ac_option in + *=?*) ac_optarg=`expr "X$ac_option" : '[^=]*=\(.*\)'` ;; + *=) ac_optarg= ;; + *) ac_optarg=yes ;; + esac + + # Accept the important Cygnus configure options, so we can diagnose typos. + + case $ac_dashdash$ac_option in + --) + ac_dashdash=yes ;; + + -bindir | --bindir | --bindi | --bind | --bin | --bi) + ac_prev=bindir ;; + -bindir=* | --bindir=* | --bindi=* | --bind=* | --bin=* | --bi=*) + bindir=$ac_optarg ;; + + -build | --build | --buil | --bui | --bu) + ac_prev=build_alias ;; + -build=* | --build=* | --buil=* | --bui=* | --bu=*) + build_alias=$ac_optarg ;; + + -cache-file | --cache-file | --cache-fil | --cache-fi \ + | --cache-f | --cache- | --cache | --cach | --cac | --ca | --c) + ac_prev=cache_file ;; + -cache-file=* | --cache-file=* | --cache-fil=* | --cache-fi=* \ + | --cache-f=* | --cache-=* | --cache=* | --cach=* | --cac=* | --ca=* | --c=*) + cache_file=$ac_optarg ;; + + --config-cache | -C) + cache_file=config.cache ;; + + -datadir | --datadir | --datadi | --datad) + ac_prev=datadir ;; + -datadir=* | --datadir=* | --datadi=* | --datad=*) + datadir=$ac_optarg ;; + + -datarootdir | --datarootdir | --datarootdi | --datarootd | --dataroot \ + | --dataroo | --dataro | --datar) + ac_prev=datarootdir ;; + -datarootdir=* | --datarootdir=* | --datarootdi=* | --datarootd=* \ + | --dataroot=* | --dataroo=* | --dataro=* | --datar=*) + datarootdir=$ac_optarg ;; + + -disable-* | --disable-*) + ac_useropt=`expr "x$ac_option" : 'x-*disable-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--disable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=no ;; + + -docdir | --docdir | --docdi | --doc | --do) + ac_prev=docdir ;; + -docdir=* | --docdir=* | --docdi=* | --doc=* | --do=*) + docdir=$ac_optarg ;; + + -dvidir | --dvidir | --dvidi | --dvid | --dvi | --dv) + ac_prev=dvidir ;; + -dvidir=* | --dvidir=* | --dvidi=* | --dvid=* | --dvi=* | --dv=*) + dvidir=$ac_optarg ;; + + -enable-* | --enable-*) + ac_useropt=`expr "x$ac_option" : 'x-*enable-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid feature name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"enable_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--enable-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval enable_$ac_useropt=\$ac_optarg ;; + + -exec-prefix | --exec_prefix | --exec-prefix | --exec-prefi \ + | --exec-pref | --exec-pre | --exec-pr | --exec-p | --exec- \ + | --exec | --exe | --ex) + ac_prev=exec_prefix ;; + -exec-prefix=* | --exec_prefix=* | --exec-prefix=* | --exec-prefi=* \ + | --exec-pref=* | --exec-pre=* | --exec-pr=* | --exec-p=* | --exec-=* \ + | --exec=* | --exe=* | --ex=*) + exec_prefix=$ac_optarg ;; + + -gas | --gas | --ga | --g) + # Obsolete; use --with-gas. + with_gas=yes ;; + + -help | --help | --hel | --he | -h) + ac_init_help=long ;; + -help=r* | --help=r* | --hel=r* | --he=r* | -hr*) + ac_init_help=recursive ;; + -help=s* | --help=s* | --hel=s* | --he=s* | -hs*) + ac_init_help=short ;; + + -host | --host | --hos | --ho) + ac_prev=host_alias ;; + -host=* | --host=* | --hos=* | --ho=*) + host_alias=$ac_optarg ;; + + -htmldir | --htmldir | --htmldi | --htmld | --html | --htm | --ht) + ac_prev=htmldir ;; + -htmldir=* | --htmldir=* | --htmldi=* | --htmld=* | --html=* | --htm=* \ + | --ht=*) + htmldir=$ac_optarg ;; + + -includedir | --includedir | --includedi | --included | --include \ + | --includ | --inclu | --incl | --inc) + ac_prev=includedir ;; + -includedir=* | --includedir=* | --includedi=* | --included=* | --include=* \ + | --includ=* | --inclu=* | --incl=* | --inc=*) + includedir=$ac_optarg ;; + + -infodir | --infodir | --infodi | --infod | --info | --inf) + ac_prev=infodir ;; + -infodir=* | --infodir=* | --infodi=* | --infod=* | --info=* | --inf=*) + infodir=$ac_optarg ;; + + -libdir | --libdir | --libdi | --libd) + ac_prev=libdir ;; + -libdir=* | --libdir=* | --libdi=* | --libd=*) + libdir=$ac_optarg ;; + + -libexecdir | --libexecdir | --libexecdi | --libexecd | --libexec \ + | --libexe | --libex | --libe) + ac_prev=libexecdir ;; + -libexecdir=* | --libexecdir=* | --libexecdi=* | --libexecd=* | --libexec=* \ + | --libexe=* | --libex=* | --libe=*) + libexecdir=$ac_optarg ;; + + -localedir | --localedir | --localedi | --localed | --locale) + ac_prev=localedir ;; + -localedir=* | --localedir=* | --localedi=* | --localed=* | --locale=*) + localedir=$ac_optarg ;; + + -localstatedir | --localstatedir | --localstatedi | --localstated \ + | --localstate | --localstat | --localsta | --localst | --locals) + ac_prev=localstatedir ;; + -localstatedir=* | --localstatedir=* | --localstatedi=* | --localstated=* \ + | --localstate=* | --localstat=* | --localsta=* | --localst=* | --locals=*) + localstatedir=$ac_optarg ;; + + -mandir | --mandir | --mandi | --mand | --man | --ma | --m) + ac_prev=mandir ;; + -mandir=* | --mandir=* | --mandi=* | --mand=* | --man=* | --ma=* | --m=*) + mandir=$ac_optarg ;; + + -nfp | --nfp | --nf) + # Obsolete; use --without-fp. + with_fp=no ;; + + -no-create | --no-create | --no-creat | --no-crea | --no-cre \ + | --no-cr | --no-c | -n) + no_create=yes ;; + + -no-recursion | --no-recursion | --no-recursio | --no-recursi \ + | --no-recurs | --no-recur | --no-recu | --no-rec | --no-re | --no-r) + no_recursion=yes ;; + + -oldincludedir | --oldincludedir | --oldincludedi | --oldincluded \ + | --oldinclude | --oldinclud | --oldinclu | --oldincl | --oldinc \ + | --oldin | --oldi | --old | --ol | --o) + ac_prev=oldincludedir ;; + -oldincludedir=* | --oldincludedir=* | --oldincludedi=* | --oldincluded=* \ + | --oldinclude=* | --oldinclud=* | --oldinclu=* | --oldincl=* | --oldinc=* \ + | --oldin=* | --oldi=* | --old=* | --ol=* | --o=*) + oldincludedir=$ac_optarg ;; + + -prefix | --prefix | --prefi | --pref | --pre | --pr | --p) + ac_prev=prefix ;; + -prefix=* | --prefix=* | --prefi=* | --pref=* | --pre=* | --pr=* | --p=*) + prefix=$ac_optarg ;; + + -program-prefix | --program-prefix | --program-prefi | --program-pref \ + | --program-pre | --program-pr | --program-p) + ac_prev=program_prefix ;; + -program-prefix=* | --program-prefix=* | --program-prefi=* \ + | --program-pref=* | --program-pre=* | --program-pr=* | --program-p=*) + program_prefix=$ac_optarg ;; + + -program-suffix | --program-suffix | --program-suffi | --program-suff \ + | --program-suf | --program-su | --program-s) + ac_prev=program_suffix ;; + -program-suffix=* | --program-suffix=* | --program-suffi=* \ + | --program-suff=* | --program-suf=* | --program-su=* | --program-s=*) + program_suffix=$ac_optarg ;; + + -program-transform-name | --program-transform-name \ + | --program-transform-nam | --program-transform-na \ + | --program-transform-n | --program-transform- \ + | --program-transform | --program-transfor \ + | --program-transfo | --program-transf \ + | --program-trans | --program-tran \ + | --progr-tra | --program-tr | --program-t) + ac_prev=program_transform_name ;; + -program-transform-name=* | --program-transform-name=* \ + | --program-transform-nam=* | --program-transform-na=* \ + | --program-transform-n=* | --program-transform-=* \ + | --program-transform=* | --program-transfor=* \ + | --program-transfo=* | --program-transf=* \ + | --program-trans=* | --program-tran=* \ + | --progr-tra=* | --program-tr=* | --program-t=*) + program_transform_name=$ac_optarg ;; + + -pdfdir | --pdfdir | --pdfdi | --pdfd | --pdf | --pd) + ac_prev=pdfdir ;; + -pdfdir=* | --pdfdir=* | --pdfdi=* | --pdfd=* | --pdf=* | --pd=*) + pdfdir=$ac_optarg ;; + + -psdir | --psdir | --psdi | --psd | --ps) + ac_prev=psdir ;; + -psdir=* | --psdir=* | --psdi=* | --psd=* | --ps=*) + psdir=$ac_optarg ;; + + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + silent=yes ;; + + -sbindir | --sbindir | --sbindi | --sbind | --sbin | --sbi | --sb) + ac_prev=sbindir ;; + -sbindir=* | --sbindir=* | --sbindi=* | --sbind=* | --sbin=* \ + | --sbi=* | --sb=*) + sbindir=$ac_optarg ;; + + -sharedstatedir | --sharedstatedir | --sharedstatedi \ + | --sharedstated | --sharedstate | --sharedstat | --sharedsta \ + | --sharedst | --shareds | --shared | --share | --shar \ + | --sha | --sh) + ac_prev=sharedstatedir ;; + -sharedstatedir=* | --sharedstatedir=* | --sharedstatedi=* \ + | --sharedstated=* | --sharedstate=* | --sharedstat=* | --sharedsta=* \ + | --sharedst=* | --shareds=* | --shared=* | --share=* | --shar=* \ + | --sha=* | --sh=*) + sharedstatedir=$ac_optarg ;; + + -site | --site | --sit) + ac_prev=site ;; + -site=* | --site=* | --sit=*) + site=$ac_optarg ;; + + -srcdir | --srcdir | --srcdi | --srcd | --src | --sr) + ac_prev=srcdir ;; + -srcdir=* | --srcdir=* | --srcdi=* | --srcd=* | --src=* | --sr=*) + srcdir=$ac_optarg ;; + + -sysconfdir | --sysconfdir | --sysconfdi | --sysconfd | --sysconf \ + | --syscon | --sysco | --sysc | --sys | --sy) + ac_prev=sysconfdir ;; + -sysconfdir=* | --sysconfdir=* | --sysconfdi=* | --sysconfd=* | --sysconf=* \ + | --syscon=* | --sysco=* | --sysc=* | --sys=* | --sy=*) + sysconfdir=$ac_optarg ;; + + -target | --target | --targe | --targ | --tar | --ta | --t) + ac_prev=target_alias ;; + -target=* | --target=* | --targe=* | --targ=* | --tar=* | --ta=* | --t=*) + target_alias=$ac_optarg ;; + + -v | -verbose | --verbose | --verbos | --verbo | --verb) + verbose=yes ;; + + -version | --version | --versio | --versi | --vers | -V) + ac_init_version=: ;; + + -with-* | --with-*) + ac_useropt=`expr "x$ac_option" : 'x-*with-\([^=]*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--with-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=\$ac_optarg ;; + + -without-* | --without-*) + ac_useropt=`expr "x$ac_option" : 'x-*without-\(.*\)'` + # Reject names that are not valid shell variable names. + expr "x$ac_useropt" : ".*[^-+._$as_cr_alnum]" >/dev/null && + as_fn_error $? "invalid package name: $ac_useropt" + ac_useropt_orig=$ac_useropt + ac_useropt=`$as_echo "$ac_useropt" | sed 's/[-+.]/_/g'` + case $ac_user_opts in + *" +"with_$ac_useropt" +"*) ;; + *) ac_unrecognized_opts="$ac_unrecognized_opts$ac_unrecognized_sep--without-$ac_useropt_orig" + ac_unrecognized_sep=', ';; + esac + eval with_$ac_useropt=no ;; + + --x) + # Obsolete; use --with-x. + with_x=yes ;; + + -x-includes | --x-includes | --x-include | --x-includ | --x-inclu \ + | --x-incl | --x-inc | --x-in | --x-i) + ac_prev=x_includes ;; + -x-includes=* | --x-includes=* | --x-include=* | --x-includ=* | --x-inclu=* \ + | --x-incl=* | --x-inc=* | --x-in=* | --x-i=*) + x_includes=$ac_optarg ;; + + -x-libraries | --x-libraries | --x-librarie | --x-librari \ + | --x-librar | --x-libra | --x-libr | --x-lib | --x-li | --x-l) + ac_prev=x_libraries ;; + -x-libraries=* | --x-libraries=* | --x-librarie=* | --x-librari=* \ + | --x-librar=* | --x-libra=* | --x-libr=* | --x-lib=* | --x-li=* | --x-l=*) + x_libraries=$ac_optarg ;; + + -*) as_fn_error $? "unrecognized option: \`$ac_option' +Try \`$0 --help' for more information" + ;; + + *=*) + ac_envvar=`expr "x$ac_option" : 'x\([^=]*\)='` + # Reject names that are not valid shell variable names. + case $ac_envvar in #( + '' | [0-9]* | *[!_$as_cr_alnum]* ) + as_fn_error $? "invalid variable name: \`$ac_envvar'" ;; + esac + eval $ac_envvar=\$ac_optarg + export $ac_envvar ;; + + *) + # FIXME: should be removed in autoconf 3.0. + $as_echo "$as_me: WARNING: you should use --build, --host, --target" >&2 + expr "x$ac_option" : ".*[^-._$as_cr_alnum]" >/dev/null && + $as_echo "$as_me: WARNING: invalid host type: $ac_option" >&2 + : "${build_alias=$ac_option} ${host_alias=$ac_option} ${target_alias=$ac_option}" + ;; + + esac +done + +if test -n "$ac_prev"; then + ac_option=--`echo $ac_prev | sed 's/_/-/g'` + as_fn_error $? "missing argument to $ac_option" +fi + +if test -n "$ac_unrecognized_opts"; then + case $enable_option_checking in + no) ;; + fatal) as_fn_error $? "unrecognized options: $ac_unrecognized_opts" ;; + *) $as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2 ;; + esac +fi + +# Check all directory arguments for consistency. +for ac_var in exec_prefix prefix bindir sbindir libexecdir datarootdir \ + datadir sysconfdir sharedstatedir localstatedir includedir \ + oldincludedir docdir infodir htmldir dvidir pdfdir psdir \ + libdir localedir mandir +do + eval ac_val=\$$ac_var + # Remove trailing slashes. + case $ac_val in + */ ) + ac_val=`expr "X$ac_val" : 'X\(.*[^/]\)' \| "X$ac_val" : 'X\(.*\)'` + eval $ac_var=\$ac_val;; + esac + # Be sure to have absolute directory names. + case $ac_val in + [\\/$]* | ?:[\\/]* ) continue;; + NONE | '' ) case $ac_var in *prefix ) continue;; esac;; + esac + as_fn_error $? "expected an absolute directory name for --$ac_var: $ac_val" +done + +# There might be people who depend on the old broken behavior: `$host' +# used to hold the argument of --host etc. +# FIXME: To remove some day. +build=$build_alias +host=$host_alias +target=$target_alias + +# FIXME: To remove some day. +if test "x$host_alias" != x; then + if test "x$build_alias" = x; then + cross_compiling=maybe + elif test "x$build_alias" != "x$host_alias"; then + cross_compiling=yes + fi +fi + +ac_tool_prefix= +test -n "$host_alias" && ac_tool_prefix=$host_alias- + +test "$silent" = yes && exec 6>/dev/null + + +ac_pwd=`pwd` && test -n "$ac_pwd" && +ac_ls_di=`ls -di .` && +ac_pwd_ls_di=`cd "$ac_pwd" && ls -di .` || + as_fn_error $? "working directory cannot be determined" +test "X$ac_ls_di" = "X$ac_pwd_ls_di" || + as_fn_error $? "pwd does not report name of working directory" + + +# Find the source files, if location was not specified. +if test -z "$srcdir"; then + ac_srcdir_defaulted=yes + # Try the directory containing this script, then the parent directory. + ac_confdir=`$as_dirname -- "$as_myself" || +$as_expr X"$as_myself" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_myself" : 'X\(//\)[^/]' \| \ + X"$as_myself" : 'X\(//\)$' \| \ + X"$as_myself" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_myself" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + srcdir=$ac_confdir + if test ! -r "$srcdir/$ac_unique_file"; then + srcdir=.. + fi +else + ac_srcdir_defaulted=no +fi +if test ! -r "$srcdir/$ac_unique_file"; then + test "$ac_srcdir_defaulted" = yes && srcdir="$ac_confdir or .." + as_fn_error $? "cannot find sources ($ac_unique_file) in $srcdir" +fi +ac_msg="sources are in $srcdir, but \`cd $srcdir' does not work" +ac_abs_confdir=`( + cd "$srcdir" && test -r "./$ac_unique_file" || as_fn_error $? "$ac_msg" + pwd)` +# When building in place, set srcdir=. +if test "$ac_abs_confdir" = "$ac_pwd"; then + srcdir=. +fi +# Remove unnecessary trailing slashes from srcdir. +# Double slashes in file names in object file debugging info +# mess up M-x gdb in Emacs. +case $srcdir in +*/) srcdir=`expr "X$srcdir" : 'X\(.*[^/]\)' \| "X$srcdir" : 'X\(.*\)'`;; +esac +for ac_var in $ac_precious_vars; do + eval ac_env_${ac_var}_set=\${${ac_var}+set} + eval ac_env_${ac_var}_value=\$${ac_var} + eval ac_cv_env_${ac_var}_set=\${${ac_var}+set} + eval ac_cv_env_${ac_var}_value=\$${ac_var} +done + +# +# Report the --help message. +# +if test "$ac_init_help" = "long"; then + # Omit some internal or obsolete options to make the list less imposing. + # This message is too long to be a string in the A/UX 3.1 sh. + cat <<_ACEOF +\`configure' configures this package to adapt to many kinds of systems. + +Usage: $0 [OPTION]... [VAR=VALUE]... + +To assign environment variables (e.g., CC, CFLAGS...), specify them as +VAR=VALUE. See below for descriptions of some of the useful variables. + +Defaults for the options are specified in brackets. + +Configuration: + -h, --help display this help and exit + --help=short display options specific to this package + --help=recursive display the short help of all the included packages + -V, --version display version information and exit + -q, --quiet, --silent do not print \`checking ...' messages + --cache-file=FILE cache test results in FILE [disabled] + -C, --config-cache alias for \`--cache-file=config.cache' + -n, --no-create do not create output files + --srcdir=DIR find the sources in DIR [configure dir or \`..'] + +Installation directories: + --prefix=PREFIX install architecture-independent files in PREFIX + [$ac_default_prefix] + --exec-prefix=EPREFIX install architecture-dependent files in EPREFIX + [PREFIX] + +By default, \`make install' will install all the files in +\`$ac_default_prefix/bin', \`$ac_default_prefix/lib' etc. You can specify +an installation prefix other than \`$ac_default_prefix' using \`--prefix', +for instance \`--prefix=\$HOME'. + +For better control, use the options below. + +Fine tuning of the installation directories: + --bindir=DIR user executables [EPREFIX/bin] + --sbindir=DIR system admin executables [EPREFIX/sbin] + --libexecdir=DIR program executables [EPREFIX/libexec] + --sysconfdir=DIR read-only single-machine data [PREFIX/etc] + --sharedstatedir=DIR modifiable architecture-independent data [PREFIX/com] + --localstatedir=DIR modifiable single-machine data [PREFIX/var] + --libdir=DIR object code libraries [EPREFIX/lib] + --includedir=DIR C header files [PREFIX/include] + --oldincludedir=DIR C header files for non-gcc [/usr/include] + --datarootdir=DIR read-only arch.-independent data root [PREFIX/share] + --datadir=DIR read-only architecture-independent data [DATAROOTDIR] + --infodir=DIR info documentation [DATAROOTDIR/info] + --localedir=DIR locale-dependent data [DATAROOTDIR/locale] + --mandir=DIR man documentation [DATAROOTDIR/man] + --docdir=DIR documentation root [DATAROOTDIR/doc/PACKAGE] + --htmldir=DIR html documentation [DOCDIR] + --dvidir=DIR dvi documentation [DOCDIR] + --pdfdir=DIR pdf documentation [DOCDIR] + --psdir=DIR ps documentation [DOCDIR] +_ACEOF + + cat <<\_ACEOF + +Program names: + --program-prefix=PREFIX prepend PREFIX to installed program names + --program-suffix=SUFFIX append SUFFIX to installed program names + --program-transform-name=PROGRAM run sed PROGRAM on installed program names + +System types: + --build=BUILD configure for building on BUILD [guessed] + --host=HOST cross-compile to build programs to run on HOST [BUILD] +_ACEOF +fi + +if test -n "$ac_init_help"; then + + cat <<\_ACEOF + +Optional Features: + --disable-option-checking ignore unrecognized --enable/--with options + --disable-FEATURE do not include FEATURE (same as --enable-FEATURE=no) + --enable-FEATURE[=ARG] include FEATURE [ARG=yes] + --enable-cppflags=... specify C preprocessor flags + --enable-cflags=... specify C compiler flags + --enable-ldflags=... specify linker flags + --enable-libs=... specify link libraries + --enable-zsh-debug compile with debug code and debugger symbols + --enable-zsh-mem compile with zsh memory allocation routines + --enable-zsh-mem-debug debug zsh memory allocation routines + --enable-zsh-mem-warning + print warnings for errors in memory allocation + --enable-zsh-secure-free + turn on error checking for free() + --enable-zsh-heap-debug turn on error checking for heap allocation + --enable-zsh-valgrind turn on support for valgrind debugging of heap + memory + --enable-zsh-hash-debug turn on debugging of internal hash tables + --enable-stack-allocation + allocate stack memory e.g. with `alloca' + --enable-etcdir=DIR the default directory for global zsh scripts + --enable-zshenv=FILE the full pathname of the global zshenv script + --enable-zshrc=FILE the full pathname of the global zshrc script + --enable-zprofile=FILE the full pathname of the global zprofile script + --enable-zlogin=FILE the full pathname of the global zlogin script + --enable-zlogout=FILE the full pathname of the global zlogout script + --disable-dynamic turn off dynamically loaded binary modules + --disable-restricted-r turn off r* invocation for restricted shell + --disable-locale turn off locale features + --enable-ansi2knr translate source to K&R C before compiling + --enable-runhelpdir=DIR the directory in which to install run-help files + --enable-fndir=DIR the directory in which to install functions + --enable-site-fndir=DIR same for site functions (not version specific) + --enable-function-subdirs + install functions in subdirectories + --enable-additional-fpath=DIR + add directories to default function path + --enable-scriptdir=DIR the directory in which to install scripts + --enable-site-scriptdir=DIR + same for site scripts (not version specific) + --enable-custom-patchlevel + set a custom ZSH_PATCHLEVEL value + --enable-maildir-support + enable maildir support in MAIL and MAILPATH + --enable-max-function-depth=MAX + limit function depth to MAX, default 500 + --enable-readnullcmd=PAGER + pager used when READNULLCMD is not set + --enable-cap enable the search for POSIX capabilities (may + require additional headers to be added by hand) + --disable-gdbm turn off search for gdbm library + --disable-largefile omit support for large files + --enable-multibyte support multibyte characters + --enable-unicode9 compile with unicode9 character widths + --enable-libc-musl compile with musl as the C library + --disable-dynamic-nss do not call functions that will require dynamic NSS + modules + +Optional Packages: + --with-PACKAGE[=ARG] use PACKAGE [ARG=yes] + --without-PACKAGE do not use PACKAGE (same as --with-PACKAGE=no) + --with-term-lib=LIBS search space-separated LIBS for terminal handling + --with-tcsetpgrp assumes that tcsetpgrp() exists and works correctly + +Some influential environment variables: + CC C compiler command + CFLAGS C compiler flags + LDFLAGS linker flags, e.g. -L if you have libraries in a + nonstandard directory + LIBS libraries to pass to the linker, e.g. -l + CPPFLAGS (Objective) C/C++ preprocessor flags, e.g. -I if + you have headers in a nonstandard directory + CPP C preprocessor + +Use these variables to override the choices made by `configure' or to help +it to find libraries and programs with nonstandard names/locations. + +Report bugs to the package provider. +_ACEOF +ac_status=$? +fi + +if test "$ac_init_help" = "recursive"; then + # If there are subdirs, report their specific --help. + for ac_dir in : $ac_subdirs_all; do test "x$ac_dir" = x: && continue + test -d "$ac_dir" || + { cd "$srcdir" && ac_pwd=`pwd` && srcdir=. && test -d "$ac_dir"; } || + continue + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + cd "$ac_dir" || { ac_status=$?; continue; } + # Check for guested configure. + if test -f "$ac_srcdir/configure.gnu"; then + echo && + $SHELL "$ac_srcdir/configure.gnu" --help=recursive + elif test -f "$ac_srcdir/configure"; then + echo && + $SHELL "$ac_srcdir/configure" --help=recursive + else + $as_echo "$as_me: WARNING: no configuration information is in $ac_dir" >&2 + fi || ac_status=$? + cd "$ac_pwd" || { ac_status=$?; break; } + done +fi + +test -n "$ac_init_help" && exit $ac_status +if $ac_init_version; then + cat <<\_ACEOF +configure +generated by GNU Autoconf 2.69 + +Copyright (C) 2012 Free Software Foundation, Inc. +This configure script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it. +_ACEOF + exit +fi + +## ------------------------ ## +## Autoconf initialization. ## +## ------------------------ ## + +# ac_fn_c_try_compile LINENO +# -------------------------- +# Try to compile conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext + if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest.$ac_objext; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_compile + +# ac_fn_c_try_cpp LINENO +# ---------------------- +# Try to preprocess conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_cpp () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_cpp conftest.$ac_ext" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_cpp conftest.$ac_ext") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } > conftest.i && { + test -z "$ac_c_preproc_warn_flag$ac_c_werror_flag" || + test ! -s conftest.err + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_cpp + +# ac_fn_c_check_type LINENO TYPE VAR INCLUDES +# ------------------------------------------- +# Tests whether TYPE exists after having included INCLUDES, setting cache +# variable VAR accordingly. +ac_fn_c_check_type () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=no" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof ($2)) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +if (sizeof (($2))) + return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + eval "$3=yes" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_type + +# ac_fn_c_try_run LINENO +# ---------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. Assumes +# that executables *can* be run. +ac_fn_c_try_run () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { ac_try='./conftest$ac_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then : + ac_retval=0 +else + $as_echo "$as_me: program exited with status $ac_status" >&5 + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=$ac_status +fi + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_run + +# ac_fn_c_check_header_compile LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists and can be compiled using the include files in +# INCLUDES, setting the cache variable VAR accordingly. +ac_fn_c_check_header_compile () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_compile + +# ac_fn_c_try_link LINENO +# ----------------------- +# Try to link conftest.$ac_ext, and return whether this succeeded. +ac_fn_c_try_link () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + rm -f conftest.$ac_objext conftest$ac_exeext + if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + grep -v '^ *+' conftest.err >conftest.er1 + cat conftest.er1 >&5 + mv -f conftest.er1 conftest.err + fi + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } && { + test -z "$ac_c_werror_flag" || + test ! -s conftest.err + } && test -s conftest$ac_exeext && { + test "$cross_compiling" = yes || + test -x conftest$ac_exeext + }; then : + ac_retval=0 +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + + ac_retval=1 +fi + # Delete the IPA/IPO (Inter Procedural Analysis/Optimization) information + # created by the PGI compiler (conftest_ipa8_conftest.oo), as it would + # interfere with the next link command; also delete a directory that is + # left behind by Apple's compiler. We do this before executing the actions. + rm -rf conftest.dSYM conftest_ipa8_conftest.oo + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + as_fn_set_status $ac_retval + +} # ac_fn_c_try_link + +# ac_fn_c_check_func LINENO FUNC VAR +# ---------------------------------- +# Tests whether FUNC exists, setting the cache variable VAR accordingly +ac_fn_c_check_func () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Define $2 to an innocuous variant, in case declares $2. + For example, HP-UX 11i declares gettimeofday. */ +#define $2 innocuous_$2 + +/* System header to define __stub macros and hopefully few prototypes, + which can conflict with char $2 (); below. + Prefer to if __STDC__ is defined, since + exists even on freestanding compilers. */ + +#ifdef __STDC__ +# include +#else +# include +#endif + +#undef $2 + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char $2 (); +/* The GNU C library defines this for functions which it implements + to always fail with ENOSYS. Some functions are actually named + something starting with __ and the normal name is an alias. */ +#if defined __stub_$2 || defined __stub___$2 +choke me +#endif + +int +main () +{ +return $2 (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_func + +# ac_fn_c_check_header_mongrel LINENO HEADER VAR INCLUDES +# ------------------------------------------------------- +# Tests whether HEADER exists, giving a warning if it cannot be compiled using +# the include files in INCLUDES and setting the cache variable VAR +# accordingly. +ac_fn_c_check_header_mongrel () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + if eval \${$3+:} false; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +else + # Is the header compilable? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 usability" >&5 +$as_echo_n "checking $2 usability... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +#include <$2> +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_header_compiler=yes +else + ac_header_compiler=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_compiler" >&5 +$as_echo "$ac_header_compiler" >&6; } + +# Is the header present? +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking $2 presence" >&5 +$as_echo_n "checking $2 presence... " >&6; } +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include <$2> +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + ac_header_preproc=yes +else + ac_header_preproc=no +fi +rm -f conftest.err conftest.i conftest.$ac_ext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_header_preproc" >&5 +$as_echo "$ac_header_preproc" >&6; } + +# So? What about this header? +case $ac_header_compiler:$ac_header_preproc:$ac_c_preproc_warn_flag in #(( + yes:no: ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&5 +$as_echo "$as_me: WARNING: $2: accepted by the compiler, rejected by the preprocessor!" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; + no:yes:* ) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: present but cannot be compiled" >&5 +$as_echo "$as_me: WARNING: $2: present but cannot be compiled" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: check for missing prerequisite headers?" >&5 +$as_echo "$as_me: WARNING: $2: check for missing prerequisite headers?" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: see the Autoconf documentation" >&5 +$as_echo "$as_me: WARNING: $2: see the Autoconf documentation" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&5 +$as_echo "$as_me: WARNING: $2: section \"Present But Cannot Be Compiled\"" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $2: proceeding with the compiler's result" >&5 +$as_echo "$as_me: WARNING: $2: proceeding with the compiler's result" >&2;} + ;; +esac + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2" >&5 +$as_echo_n "checking for $2... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + eval "$3=\$ac_header_compiler" +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +fi + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_header_mongrel + +# ac_fn_c_check_decl LINENO SYMBOL VAR INCLUDES +# --------------------------------------------- +# Tests whether SYMBOL is declared in INCLUDES, setting cache variable VAR +# accordingly. +ac_fn_c_check_decl () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + as_decl_name=`echo $2|sed 's/ *(.*//'` + as_decl_use=`echo $2|sed -e 's/(/((/' -e 's/)/) 0&/' -e 's/,/) 0& (/g'` + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $as_decl_name is declared" >&5 +$as_echo_n "checking whether $as_decl_name is declared... " >&6; } +if eval \${$3+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$4 +int +main () +{ +#ifndef $as_decl_name +#ifdef __cplusplus + (void) $as_decl_use; +#else + (void) $as_decl_name; +#endif +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$3=yes" +else + eval "$3=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$3 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_decl + +# ac_fn_c_check_member LINENO AGGR MEMBER VAR INCLUDES +# ---------------------------------------------------- +# Tries to find if the field MEMBER exists in type AGGR, after including +# INCLUDES, setting cache variable VAR accordingly. +ac_fn_c_check_member () +{ + as_lineno=${as_lineno-"$1"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for $2.$3" >&5 +$as_echo_n "checking for $2.$3... " >&6; } +if eval \${$4+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main () +{ +static $2 ac_aggr; +if (ac_aggr.$3) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$4=yes" +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$5 +int +main () +{ +static $2 ac_aggr; +if (sizeof ac_aggr.$3) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$4=yes" +else + eval "$4=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$4 + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } + eval $as_lineno_stack; ${as_lineno_stack:+:} unset as_lineno + +} # ac_fn_c_check_member +cat >config.log <<_ACEOF +This file contains any messages produced by compilers while +running configure, to aid debugging if configure makes a mistake. + +It was created by $as_me, which was +generated by GNU Autoconf 2.69. Invocation command line was + + $ $0 $@ + +_ACEOF +exec 5>>config.log +{ +cat <<_ASUNAME +## --------- ## +## Platform. ## +## --------- ## + +hostname = `(hostname || uname -n) 2>/dev/null | sed 1q` +uname -m = `(uname -m) 2>/dev/null || echo unknown` +uname -r = `(uname -r) 2>/dev/null || echo unknown` +uname -s = `(uname -s) 2>/dev/null || echo unknown` +uname -v = `(uname -v) 2>/dev/null || echo unknown` + +/usr/bin/uname -p = `(/usr/bin/uname -p) 2>/dev/null || echo unknown` +/bin/uname -X = `(/bin/uname -X) 2>/dev/null || echo unknown` + +/bin/arch = `(/bin/arch) 2>/dev/null || echo unknown` +/usr/bin/arch -k = `(/usr/bin/arch -k) 2>/dev/null || echo unknown` +/usr/convex/getsysinfo = `(/usr/convex/getsysinfo) 2>/dev/null || echo unknown` +/usr/bin/hostinfo = `(/usr/bin/hostinfo) 2>/dev/null || echo unknown` +/bin/machine = `(/bin/machine) 2>/dev/null || echo unknown` +/usr/bin/oslevel = `(/usr/bin/oslevel) 2>/dev/null || echo unknown` +/bin/universe = `(/bin/universe) 2>/dev/null || echo unknown` + +_ASUNAME + +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + $as_echo "PATH: $as_dir" + done +IFS=$as_save_IFS + +} >&5 + +cat >&5 <<_ACEOF + + +## ----------- ## +## Core tests. ## +## ----------- ## + +_ACEOF + + +# Keep a trace of the command line. +# Strip out --no-create and --no-recursion so they do not pile up. +# Strip out --silent because we don't want to record it for future runs. +# Also quote any args containing shell meta-characters. +# Make two passes to allow for proper duplicate-argument suppression. +ac_configure_args= +ac_configure_args0= +ac_configure_args1= +ac_must_keep_next=false +for ac_pass in 1 2 +do + for ac_arg + do + case $ac_arg in + -no-create | --no-c* | -n | -no-recursion | --no-r*) continue ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil) + continue ;; + *\'*) + ac_arg=`$as_echo "$ac_arg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + case $ac_pass in + 1) as_fn_append ac_configure_args0 " '$ac_arg'" ;; + 2) + as_fn_append ac_configure_args1 " '$ac_arg'" + if test $ac_must_keep_next = true; then + ac_must_keep_next=false # Got value, back to normal. + else + case $ac_arg in + *=* | --config-cache | -C | -disable-* | --disable-* \ + | -enable-* | --enable-* | -gas | --g* | -nfp | --nf* \ + | -q | -quiet | --q* | -silent | --sil* | -v | -verb* \ + | -with-* | --with-* | -without-* | --without-* | --x) + case "$ac_configure_args0 " in + "$ac_configure_args1"*" '$ac_arg' "* ) continue ;; + esac + ;; + -* ) ac_must_keep_next=true ;; + esac + fi + as_fn_append ac_configure_args " '$ac_arg'" + ;; + esac + done +done +{ ac_configure_args0=; unset ac_configure_args0;} +{ ac_configure_args1=; unset ac_configure_args1;} + +# When interrupted or exit'd, cleanup temporary files, and complete +# config.log. We remove comments because anyway the quotes in there +# would cause problems or look ugly. +# WARNING: Use '\'' to represent an apostrophe within the trap. +# WARNING: Do not start the trap code with a newline, due to a FreeBSD 4.0 bug. +trap 'exit_status=$? + # Save into config.log some information that might help in debugging. + { + echo + + $as_echo "## ---------------- ## +## Cache variables. ## +## ---------------- ##" + echo + # The following way of writing the cache mishandles newlines in values, +( + for ac_var in `(set) 2>&1 | sed -n '\''s/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'\''`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + (set) 2>&1 | + case $as_nl`(ac_space='\'' '\''; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + sed -n \ + "s/'\''/'\''\\\\'\'''\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\''\\2'\''/p" + ;; #( + *) + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) + echo + + $as_echo "## ----------------- ## +## Output variables. ## +## ----------------- ##" + echo + for ac_var in $ac_subst_vars + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + + if test -n "$ac_subst_files"; then + $as_echo "## ------------------- ## +## File substitutions. ## +## ------------------- ##" + echo + for ac_var in $ac_subst_files + do + eval ac_val=\$$ac_var + case $ac_val in + *\'\''*) ac_val=`$as_echo "$ac_val" | sed "s/'\''/'\''\\\\\\\\'\'''\''/g"`;; + esac + $as_echo "$ac_var='\''$ac_val'\''" + done | sort + echo + fi + + if test -s confdefs.h; then + $as_echo "## ----------- ## +## confdefs.h. ## +## ----------- ##" + echo + cat confdefs.h + echo + fi + test "$ac_signal" != 0 && + $as_echo "$as_me: caught signal $ac_signal" + $as_echo "$as_me: exit $exit_status" + } >&5 + rm -f core *.core core.conftest.* && + rm -f -r conftest* confdefs* conf$$* $ac_clean_files && + exit $exit_status +' 0 +for ac_signal in 1 2 13 15; do + trap 'ac_signal='$ac_signal'; as_fn_exit 1' $ac_signal +done +ac_signal=0 + +# confdefs.h avoids OS command line length limits that DEFS can exceed. +rm -f -r conftest* confdefs.h + +$as_echo "/* confdefs.h */" > confdefs.h + +# Predefined preprocessor variables. + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_NAME "$PACKAGE_NAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_TARNAME "$PACKAGE_TARNAME" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_VERSION "$PACKAGE_VERSION" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_STRING "$PACKAGE_STRING" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_BUGREPORT "$PACKAGE_BUGREPORT" +_ACEOF + +cat >>confdefs.h <<_ACEOF +#define PACKAGE_URL "$PACKAGE_URL" +_ACEOF + + +# Let the site file select an alternate cache file if it wants to. +# Prefer an explicitly selected file to automatically selected ones. +ac_site_file1=NONE +ac_site_file2=NONE +if test -n "$CONFIG_SITE"; then + # We do not want a PATH search for config.site. + case $CONFIG_SITE in #(( + -*) ac_site_file1=./$CONFIG_SITE;; + */*) ac_site_file1=$CONFIG_SITE;; + *) ac_site_file1=./$CONFIG_SITE;; + esac +elif test "x$prefix" != xNONE; then + ac_site_file1=$prefix/share/config.site + ac_site_file2=$prefix/etc/config.site +else + ac_site_file1=$ac_default_prefix/share/config.site + ac_site_file2=$ac_default_prefix/etc/config.site +fi +for ac_site_file in "$ac_site_file1" "$ac_site_file2" +do + test "x$ac_site_file" = xNONE && continue + if test /dev/null != "$ac_site_file" && test -r "$ac_site_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading site script $ac_site_file" >&5 +$as_echo "$as_me: loading site script $ac_site_file" >&6;} + sed 's/^/| /' "$ac_site_file" >&5 + . "$ac_site_file" \ + || { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "failed to load site script $ac_site_file +See \`config.log' for more details" "$LINENO" 5; } + fi +done + +if test -r "$cache_file"; then + # Some versions of bash will fail to source /dev/null (special files + # actually), so we avoid doing that. DJGPP emulates it as a regular file. + if test /dev/null != "$cache_file" && test -f "$cache_file"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: loading cache $cache_file" >&5 +$as_echo "$as_me: loading cache $cache_file" >&6;} + case $cache_file in + [\\/]* | ?:[\\/]* ) . "$cache_file";; + *) . "./$cache_file";; + esac + fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: creating cache $cache_file" >&5 +$as_echo "$as_me: creating cache $cache_file" >&6;} + >$cache_file +fi + +as_fn_append ac_header_list " stdlib.h" +as_fn_append ac_header_list " unistd.h" +as_fn_append ac_header_list " sys/param.h" +# Check that the precious variables saved in the cache have kept the same +# value. +ac_cache_corrupted=false +for ac_var in $ac_precious_vars; do + eval ac_old_set=\$ac_cv_env_${ac_var}_set + eval ac_new_set=\$ac_env_${ac_var}_set + eval ac_old_val=\$ac_cv_env_${ac_var}_value + eval ac_new_val=\$ac_env_${ac_var}_value + case $ac_old_set,$ac_new_set in + set,) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was set to \`$ac_old_val' in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,set) + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' was not set in the previous run" >&5 +$as_echo "$as_me: error: \`$ac_var' was not set in the previous run" >&2;} + ac_cache_corrupted=: ;; + ,);; + *) + if test "x$ac_old_val" != "x$ac_new_val"; then + # differences in whitespace do not lead to failure. + ac_old_val_w=`echo x $ac_old_val` + ac_new_val_w=`echo x $ac_new_val` + if test "$ac_old_val_w" != "$ac_new_val_w"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: \`$ac_var' has changed since the previous run:" >&5 +$as_echo "$as_me: error: \`$ac_var' has changed since the previous run:" >&2;} + ac_cache_corrupted=: + else + { $as_echo "$as_me:${as_lineno-$LINENO}: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&5 +$as_echo "$as_me: warning: ignoring whitespace changes in \`$ac_var' since the previous run:" >&2;} + eval $ac_var=\$ac_old_val + fi + { $as_echo "$as_me:${as_lineno-$LINENO}: former value: \`$ac_old_val'" >&5 +$as_echo "$as_me: former value: \`$ac_old_val'" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: current value: \`$ac_new_val'" >&5 +$as_echo "$as_me: current value: \`$ac_new_val'" >&2;} + fi;; + esac + # Pass precious variables to config.status. + if test "$ac_new_set" = set; then + case $ac_new_val in + *\'*) ac_arg=$ac_var=`$as_echo "$ac_new_val" | sed "s/'/'\\\\\\\\''/g"` ;; + *) ac_arg=$ac_var=$ac_new_val ;; + esac + case " $ac_configure_args " in + *" '$ac_arg' "*) ;; # Avoid dups. Use of quotes ensures accuracy. + *) as_fn_append ac_configure_args " '$ac_arg'" ;; + esac + fi +done +if $ac_cache_corrupted; then + { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} + { $as_echo "$as_me:${as_lineno-$LINENO}: error: changes in the environment can compromise the build" >&5 +$as_echo "$as_me: error: changes in the environment can compromise the build" >&2;} + as_fn_error $? "run \`make distclean' and/or \`rm $cache_file' and start over" "$LINENO" 5 +fi +## -------------------- ## +## Main body of script. ## +## -------------------- ## + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + + +ac_config_headers="$ac_config_headers config.h" + + +. ${srcdir}/Config/version.mk +echo "configuring for zsh $VERSION" + +ac_aux_dir= +for ac_dir in "$srcdir" "$srcdir/.." "$srcdir/../.."; do + if test -f "$ac_dir/install-sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install-sh -c" + break + elif test -f "$ac_dir/install.sh"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/install.sh -c" + break + elif test -f "$ac_dir/shtool"; then + ac_aux_dir=$ac_dir + ac_install_sh="$ac_aux_dir/shtool install -c" + break + fi +done +if test -z "$ac_aux_dir"; then + as_fn_error $? "cannot find install-sh, install.sh, or shtool in \"$srcdir\" \"$srcdir/..\" \"$srcdir/../..\"" "$LINENO" 5 +fi + +# These three variables are undocumented and unsupported, +# and are intended to be withdrawn in a future Autoconf release. +# They can cause serious problems if a builder's source tree is in a directory +# whose full name contains unusual characters. +ac_config_guess="$SHELL $ac_aux_dir/config.guess" # Please don't use this var. +ac_config_sub="$SHELL $ac_aux_dir/config.sub" # Please don't use this var. +ac_configure="$SHELL $ac_aux_dir/configure" # Please don't use this var. + + +# Make sure we can run config.sub. +$SHELL "$ac_aux_dir/config.sub" sun4 >/dev/null 2>&1 || + as_fn_error $? "cannot run $SHELL $ac_aux_dir/config.sub" "$LINENO" 5 + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking build system type" >&5 +$as_echo_n "checking build system type... " >&6; } +if ${ac_cv_build+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_build_alias=$build_alias +test "x$ac_build_alias" = x && + ac_build_alias=`$SHELL "$ac_aux_dir/config.guess"` +test "x$ac_build_alias" = x && + as_fn_error $? "cannot guess build type; you must specify one" "$LINENO" 5 +ac_cv_build=`$SHELL "$ac_aux_dir/config.sub" $ac_build_alias` || + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $ac_build_alias failed" "$LINENO" 5 + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_build" >&5 +$as_echo "$ac_cv_build" >&6; } +case $ac_cv_build in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical build" "$LINENO" 5;; +esac +build=$ac_cv_build +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_build +shift +build_cpu=$1 +build_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +build_os=$* +IFS=$ac_save_IFS +case $build_os in *\ *) build_os=`echo "$build_os" | sed 's/ /-/g'`;; esac + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking host system type" >&5 +$as_echo_n "checking host system type... " >&6; } +if ${ac_cv_host+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "x$host_alias" = x; then + ac_cv_host=$ac_cv_build +else + ac_cv_host=`$SHELL "$ac_aux_dir/config.sub" $host_alias` || + as_fn_error $? "$SHELL $ac_aux_dir/config.sub $host_alias failed" "$LINENO" 5 +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_host" >&5 +$as_echo "$ac_cv_host" >&6; } +case $ac_cv_host in +*-*-*) ;; +*) as_fn_error $? "invalid value of canonical host" "$LINENO" 5;; +esac +host=$ac_cv_host +ac_save_IFS=$IFS; IFS='-' +set x $ac_cv_host +shift +host_cpu=$1 +host_vendor=$2 +shift; shift +# Remember, the first character of IFS is used to create $*, +# except with old shells: +host_os=$* +IFS=$ac_save_IFS +case $host_os in *\ *) host_os=`echo "$host_os" | sed 's/ /-/g'`;; esac + + + +cat >>confdefs.h <<_ACEOF +#define MACHTYPE "$host_cpu" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define VENDOR "$host_vendor" +_ACEOF + + +cat >>confdefs.h <<_ACEOF +#define OSTYPE "$host_os" +_ACEOF + + +test "$program_prefix" != NONE && + program_transform_name="s&^&$program_prefix&;$program_transform_name" +# Use a double $ so make ignores it. +test "$program_suffix" != NONE && + program_transform_name="s&\$&$program_suffix&;$program_transform_name" +# Double any \ or $. +# By default was `s,x,x', remove it if useless. +ac_script='s/[\\$]/&&/g;s/;s,x,x,$//' +program_transform_name=`$as_echo "$program_transform_name" | sed "$ac_script"` + + +# Un-double any \ or $ (doubled by AC_ARG_PROGRAM). +cat <<\EOF_SED > conftestsed +s,\\\\,\\,g; s,\$\$,$,g +EOF_SED +zsh_transform_name=`echo "${program_transform_name}" | sed -f conftestsed` +rm -f conftestsed +tzsh_name=`echo zsh | sed -e "${zsh_transform_name}"` +# Double any \ or $ in the transformed name that results. +cat <<\EOF_SED >> conftestsed +s,\\,\\\\,g; s,\$,$$,g +EOF_SED +tzsh=`echo ${tzsh_name} | sed -f conftestsed` +rm -f conftestsed + + +# Check whether --enable-cppflags was given. +if test "${enable_cppflags+set}" = set; then : + enableval=$enable_cppflags; if test "$enableval" = "yes" + then CPPFLAGS="$CPPFLAGS" + else CPPFLAGS="$enable_cppflags" + fi +fi + + # Check whether --enable-cflags was given. +if test "${enable_cflags+set}" = set; then : + enableval=$enable_cflags; if test "$enableval" = "yes" + then CFLAGS="$CFLAGS" + else CFLAGS="$enable_cflags" + fi +fi + + # Check whether --enable-ldflags was given. +if test "${enable_ldflags+set}" = set; then : + enableval=$enable_ldflags; if test "$enableval" = "yes" + then LDFLAGS="$LDFLAGS" + else LDFLAGS="$enable_ldflags" + fi +fi + + # Check whether --enable-libs was given. +if test "${enable_libs+set}" = set; then : + enableval=$enable_libs; if test "$enableval" = "yes" + then LIBS="$LIBS" + else LIBS="$enable_libs" + fi +fi + + + +# Check whether --enable-zsh-debug was given. +if test "${enable_zsh_debug+set}" = set; then : + enableval=$enable_zsh_debug; if test x$enableval = xyes; then + $as_echo "#define DEBUG 1" >>confdefs.h + +fi +fi + + + +# Check whether --enable-zsh-mem was given. +if test "${enable_zsh_mem+set}" = set; then : + enableval=$enable_zsh_mem; if test x$enableval = xyes; then + $as_echo "#define ZSH_MEM 1" >>confdefs.h + +fi +fi + + + +# Check whether --enable-zsh-mem-debug was given. +if test "${enable_zsh_mem_debug+set}" = set; then : + enableval=$enable_zsh_mem_debug; if test x$enableval = xyes; then + $as_echo "#define ZSH_MEM_DEBUG 1" >>confdefs.h + +fi +fi + + + +# Check whether --enable-zsh-mem-warning was given. +if test "${enable_zsh_mem_warning+set}" = set; then : + enableval=$enable_zsh_mem_warning; if test x$enableval = xyes; then + $as_echo "#define ZSH_MEM_WARNING 1" >>confdefs.h + +fi +fi + + + +# Check whether --enable-zsh-secure-free was given. +if test "${enable_zsh_secure_free+set}" = set; then : + enableval=$enable_zsh_secure_free; if test x$enableval = xyes; then + $as_echo "#define ZSH_SECURE_FREE 1" >>confdefs.h + +fi +fi + + + +# Check whether --enable-zsh-heap-debug was given. +if test "${enable_zsh_heap_debug+set}" = set; then : + enableval=$enable_zsh_heap_debug; if test x$enableval = xyes; then + $as_echo "#define ZSH_HEAP_DEBUG 1" >>confdefs.h + +fi +fi + + + +# Check whether --enable-zsh-valgrind was given. +if test "${enable_zsh_valgrind+set}" = set; then : + enableval=$enable_zsh_valgrind; if test x$enableval = xyes; then + $as_echo "#define ZSH_VALGRIND 1" >>confdefs.h + +fi +fi + + + +# Check whether --enable-zsh-hash-debug was given. +if test "${enable_zsh_hash_debug+set}" = set; then : + enableval=$enable_zsh_hash_debug; if test x$enableval = xyes; then + $as_echo "#define ZSH_HASH_DEBUG 1" >>confdefs.h + +fi +fi + + + +# Check whether --enable-stack-allocation was given. +if test "${enable_stack_allocation+set}" = set; then : + enableval=$enable_stack_allocation; if test x$enableval = xyes; then + $as_echo "#define USE_STACK_ALLOCATION 1" >>confdefs.h + +fi +fi + + +# Check whether --enable-etcdir was given. +if test "${enable_etcdir+set}" = set; then : + enableval=$enable_etcdir; etcdir="$enableval" +else + etcdir=/etc +fi + + +# Check whether --enable-zshenv was given. +if test "${enable_zshenv+set}" = set; then : + enableval=$enable_zshenv; zshenv="$enableval" +else + if test "x$etcdir" = xno; then + zshenv=no +else + zshenv="$etcdir/zshenv" +fi +fi + + +if test "x$zshenv" != xno; then + cat >>confdefs.h <<_ACEOF +#define GLOBAL_ZSHENV "$zshenv" +_ACEOF + +fi + +# Check whether --enable-zshrc was given. +if test "${enable_zshrc+set}" = set; then : + enableval=$enable_zshrc; zshrc="$enableval" +else + if test "x$etcdir" = xno; then + zshrc=no +else + zshrc="$etcdir/zshrc" +fi +fi + + +if test "x$zshrc" != xno; then + cat >>confdefs.h <<_ACEOF +#define GLOBAL_ZSHRC "$zshrc" +_ACEOF + +fi + +# Check whether --enable-zprofile was given. +if test "${enable_zprofile+set}" = set; then : + enableval=$enable_zprofile; zprofile="$enableval" +else + if test "x$etcdir" = xno; then + zprofile=no +else + zprofile="$etcdir/zprofile" +fi +fi + + +if test "x$zprofile" != xno; then + cat >>confdefs.h <<_ACEOF +#define GLOBAL_ZPROFILE "$zprofile" +_ACEOF + +fi + +# Check whether --enable-zlogin was given. +if test "${enable_zlogin+set}" = set; then : + enableval=$enable_zlogin; zlogin="$enableval" +else + if test "x$etcdir" = xno; then + zlogin=no +else + zlogin="$etcdir/zlogin" +fi +fi + + +if test "x$zlogin" != xno; then + cat >>confdefs.h <<_ACEOF +#define GLOBAL_ZLOGIN "$zlogin" +_ACEOF + +fi + +# Check whether --enable-zlogout was given. +if test "${enable_zlogout+set}" = set; then : + enableval=$enable_zlogout; zlogout="$enableval" +else + if test "x$etcdir" = xno; then + zlogout=no +else + zlogout="$etcdir/zlogout" +fi +fi + + +if test "x$zlogout" != xno; then + cat >>confdefs.h <<_ACEOF +#define GLOBAL_ZLOGOUT "$zlogout" +_ACEOF + +fi + + +# Check whether --enable-dynamic was given. +if test "${enable_dynamic+set}" = set; then : + enableval=$enable_dynamic; dynamic="$enableval" +else + dynamic=yes +fi + + + +# Check whether --enable-restricted-r was given. +if test "${enable_restricted_r+set}" = set; then : + enableval=$enable_restricted_r; if test x$enableval = xyes; then + $as_echo "#define RESTRICTED_R 1" >>confdefs.h + +fi +else + $as_echo "#define RESTRICTED_R 1" >>confdefs.h + + +fi + + + +# Check whether --enable-locale was given. +if test "${enable_locale+set}" = set; then : + enableval=$enable_locale; if test x$enableval = xyes; then + $as_echo "#define CONFIG_LOCALE 1" >>confdefs.h + +fi +else + $as_echo "#define CONFIG_LOCALE 1" >>confdefs.h + + +fi + + +# Check whether --enable-ansi2knr was given. +if test "${enable_ansi2knr+set}" = set; then : + enableval=$enable_ansi2knr; ansi2knr="$enableval" +else + ansi2knr=default +fi + + +# Check whether --enable-runhelpdir was given. +if test "${enable_runhelpdir+set}" = set; then : + enableval=$enable_runhelpdir; if test x"$enableval" = xno; then + runhelpdir= +else + runhelpdir="$enableval" +fi +else + runhelpdir=yes +fi + +if test x"$runhelpdir" = xyes; then + runhelpdir=${datadir}/${tzsh_name}/'${VERSION}'/help +fi +if test x"$runhelpdir" = x; then + runhelp= +else + runhelp=runhelp +fi + +# Check whether --enable-fndir was given. +if test "${enable_fndir+set}" = set; then : + enableval=$enable_fndir; if test x$enableval = xyes; then + fndir=${datadir}/${tzsh_name}/'${VERSION}'/functions +else + fndir="$enableval" +fi +else + fndir=${datadir}/${tzsh_name}/'${VERSION}'/functions +fi + + +# Check whether --enable-site-fndir was given. +if test "${enable_site_fndir+set}" = set; then : + enableval=$enable_site_fndir; if test x$enableval = xyes; then + sitefndir=${datadir}/${tzsh_name}/site-functions +else + sitefndir="$enableval" +fi +else + sitefndir=${datadir}/${tzsh_name}/site-functions +fi + + +if test X$sitefndir = X/usr/local/share/zsh/site-functions || \ + test X$sitefndir = Xno +then fixed_sitefndir='' +elif test X$prefix != X/usr/local; then + if test X$prefix = XNONE && test X$ac_default_prefix = X/usr/local; then + if test X$tzsh_name != Xzsh + then fixed_sitefndir=/usr/local/share/zsh/site-functions + else fixed_sitefndir='' + fi + else fixed_sitefndir=/usr/local/share/zsh/site-functions + fi +elif test X$tzsh_name != Xzsh +then fixed_sitefndir=/usr/local/share/zsh/site-functions +else fixed_sitefndir='' +fi + + +# Check whether --enable-function-subdirs was given. +if test "${enable_function_subdirs+set}" = set; then : + enableval=$enable_function_subdirs; +fi + + +if test "x${enable_function_subdirs}" != x && + test "x${enable_function_subdirs}" != xno; then + FUNCTIONS_SUBDIRS=yes +else + FUNCTIONS_SUBDIRS=no +fi + +# Check whether --enable-additional-fpath was given. +if test "${enable_additional_fpath+set}" = set; then : + enableval=$enable_additional_fpath; if test x$enableval = xyes; then + additionalfpath="" +else + additionalfpath="${enableval}" +fi +else + additionalfpath="" +fi + + + + +# Check whether --enable-scriptdir was given. +if test "${enable_scriptdir+set}" = set; then : + enableval=$enable_scriptdir; if test x$enableval = xyes; then + scriptdir=${datadir}/${tzsh_name}/'${VERSION}'/scripts +else + scriptdir="$enableval" +fi +else + scriptdir=${datadir}/${tzsh_name}/'${VERSION}'/scripts +fi + + +# Check whether --enable-site-scriptdir was given. +if test "${enable_site_scriptdir+set}" = set; then : + enableval=$enable_site_scriptdir; if test x$enableval = xyes; then + sitescriptdir=${datadir}/${tzsh_name}/scripts +else + sitescriptdir="$enableval" +fi +else + sitescriptdir=${datadir}/${tzsh_name}/scripts +fi + + + +if test x$htmldir = x'${docdir}' || test x$htmldir = x; then + htmldir='$(datadir)/$(tzsh)/htmldoc' +fi + + +# Check whether --enable-custom-patchlevel was given. +if test "${enable_custom_patchlevel+set}" = set; then : + enableval=$enable_custom_patchlevel; if test x$enableval != x && test x$enableval != xno; then + cat >>confdefs.h <<_ACEOF +#define CUSTOM_PATCHLEVEL "$enableval" +_ACEOF + +fi +fi + + + +# Check whether --enable-maildir-support was given. +if test "${enable_maildir_support+set}" = set; then : + enableval=$enable_maildir_support; if test x$enableval = xyes; then + $as_echo "#define MAILDIR_SUPPORT 1" >>confdefs.h + +fi +fi + + + +# Check whether --enable-max-function-depth was given. +if test "${enable_max_function_depth+set}" = set; then : + enableval=$enable_max_function_depth; if test x$enableval = xyes; then + $as_echo "#define MAX_FUNCTION_DEPTH 500" >>confdefs.h + +elif test x$enableval != xno; then + cat >>confdefs.h <<_ACEOF +#define MAX_FUNCTION_DEPTH $enableval +_ACEOF + +fi +else + $as_echo "#define MAX_FUNCTION_DEPTH 500" >>confdefs.h + + +fi + + + +# Check whether --enable-readnullcmd was given. +if test "${enable_readnullcmd+set}" = set; then : + enableval=$enable_readnullcmd; if test x$enableval = xyes; then + $as_echo "#define DEFAULT_READNULLCMD \"more\"" >>confdefs.h + +elif test x$enableval != xno; then + cat >>confdefs.h <<_ACEOF +#define DEFAULT_READNULLCMD "$enableval" +_ACEOF + +fi +else + $as_echo "#define DEFAULT_READNULLCMD \"more\"" >>confdefs.h + + +fi + + +# Check whether --enable-cap was given. +if test "${enable_cap+set}" = set; then : + enableval=$enable_cap; +fi + + +# Check whether --enable-gdbm was given. +if test "${enable_gdbm+set}" = set; then : + enableval=$enable_gdbm; gdbm="$enableval" +else + gdbm=yes +fi + + +test -z "${CFLAGS+set}" && CFLAGS= auto_cflags=1 +test -z "${LDFLAGS+set}" && LDFLAGS= auto_ldflags=1 + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}gcc", so it can be a program name with args. +set dummy ${ac_tool_prefix}gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$ac_cv_prog_CC"; then + ac_ct_CC=$CC + # Extract the first word of "gcc", so it can be a program name with args. +set dummy gcc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="gcc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +else + CC="$ac_cv_prog_CC" +fi + +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + # Extract the first word of "${ac_tool_prefix}cc", so it can be a program name with args. +set dummy ${ac_tool_prefix}cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="${ac_tool_prefix}cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + fi +fi +if test -z "$CC"; then + # Extract the first word of "cc", so it can be a program name with args. +set dummy cc; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else + ac_prog_rejected=no +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + if test "$as_dir/$ac_word$ac_exec_ext" = "/usr/ucb/cc"; then + ac_prog_rejected=yes + continue + fi + ac_cv_prog_CC="cc" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +if test $ac_prog_rejected = yes; then + # We found a bogon in the path, so make sure we never use it. + set dummy $ac_cv_prog_CC + shift + if test $# != 0; then + # We chose a different compiler from the bogus one. + # However, it has the same basename, so the bogon will be chosen + # first if we set CC to just the basename; use the full file name. + shift + ac_cv_prog_CC="$as_dir/$ac_word${1+' '}$@" + fi +fi +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + +fi +if test -z "$CC"; then + if test -n "$ac_tool_prefix"; then + for ac_prog in cl.exe + do + # Extract the first word of "$ac_tool_prefix$ac_prog", so it can be a program name with args. +set dummy $ac_tool_prefix$ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$CC"; then + ac_cv_prog_CC="$CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_CC="$ac_tool_prefix$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +CC=$ac_cv_prog_CC +if test -n "$CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $CC" >&5 +$as_echo "$CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$CC" && break + done +fi +if test -z "$CC"; then + ac_ct_CC=$CC + for ac_prog in cl.exe +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ac_ct_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ac_ct_CC"; then + ac_cv_prog_ac_ct_CC="$ac_ct_CC" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ac_ct_CC="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ac_ct_CC=$ac_cv_prog_ac_ct_CC +if test -n "$ac_ct_CC"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_ct_CC" >&5 +$as_echo "$ac_ct_CC" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ac_ct_CC" && break +done + + if test "x$ac_ct_CC" = x; then + CC="" + else + case $cross_compiling:$ac_tool_warned in +yes:) +{ $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: using cross tools not prefixed with host triplet" >&5 +$as_echo "$as_me: WARNING: using cross tools not prefixed with host triplet" >&2;} +ac_tool_warned=yes ;; +esac + CC=$ac_ct_CC + fi +fi + +fi + + +test -z "$CC" && { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "no acceptable C compiler found in \$PATH +See \`config.log' for more details" "$LINENO" 5; } + +# Provide some information about the compiler. +$as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler version" >&5 +set X $ac_compile +ac_compiler=$2 +for ac_option in --version -v -V -qversion; do + { { ac_try="$ac_compiler $ac_option >&5" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compiler $ac_option >&5") 2>conftest.err + ac_status=$? + if test -s conftest.err; then + sed '10a\ +... rest of stderr output deleted ... + 10q' conftest.err >conftest.er1 + cat conftest.er1 >&5 + fi + rm -f conftest.er1 conftest.err + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } +done + +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files a.out a.out.dSYM a.exe b.out" +# Try to create an executable without -o first, disregard a.out. +# It will help us diagnose broken compilers, and finding out an intuition +# of exeext. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether the C compiler works" >&5 +$as_echo_n "checking whether the C compiler works... " >&6; } +ac_link_default=`$as_echo "$ac_link" | sed 's/ -o *conftest[^ ]*//'` + +# The possible output files: +ac_files="a.out conftest.exe conftest a.exe a_out.exe b.out conftest.*" + +ac_rmfiles= +for ac_file in $ac_files +do + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + * ) ac_rmfiles="$ac_rmfiles $ac_file";; + esac +done +rm -f $ac_rmfiles + +if { { ac_try="$ac_link_default" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link_default") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # Autoconf-2.13 could set the ac_cv_exeext variable to `no'. +# So ignore a value of `no', otherwise this would lead to `EXEEXT = no' +# in a Makefile. We should not override ac_cv_exeext if it was cached, +# so that the user can short-circuit this test for compilers unknown to +# Autoconf. +for ac_file in $ac_files '' +do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) + ;; + [ab].out ) + # We found the default executable, but exeext='' is most + # certainly right. + break;; + *.* ) + if test "${ac_cv_exeext+set}" = set && test "$ac_cv_exeext" != no; + then :; else + ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + fi + # We set ac_cv_exeext here because the later test for it is not + # safe: cross compilers may not add the suffix if given an `-o' + # argument, so we may need to know it at that point already. + # Even if this section looks crufty: it has the advantage of + # actually working. + break;; + * ) + break;; + esac +done +test "$ac_cv_exeext" = no && ac_cv_exeext= + +else + ac_file='' +fi +if test -z "$ac_file"; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +$as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 77 "C compiler cannot create executables +See \`config.log' for more details" "$LINENO" 5; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for C compiler default output file name" >&5 +$as_echo_n "checking for C compiler default output file name... " >&6; } +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_file" >&5 +$as_echo "$ac_file" >&6; } +ac_exeext=$ac_cv_exeext + +rm -f -r a.out a.out.dSYM a.exe conftest$ac_cv_exeext b.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of executables" >&5 +$as_echo_n "checking for suffix of executables... " >&6; } +if { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + # If both `conftest.exe' and `conftest' are `present' (well, observable) +# catch `conftest.exe'. For instance with Cygwin, `ls conftest' will +# work properly (i.e., refer to `conftest.exe'), while it won't with +# `rm'. +for ac_file in conftest.exe conftest conftest.*; do + test -f "$ac_file" || continue + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM | *.o | *.obj ) ;; + *.* ) ac_cv_exeext=`expr "$ac_file" : '[^.]*\(\..*\)'` + break;; + * ) break;; + esac +done +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of executables: cannot compile and link +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest conftest$ac_cv_exeext +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_exeext" >&5 +$as_echo "$ac_cv_exeext" >&6; } + +rm -f conftest.$ac_ext +EXEEXT=$ac_cv_exeext +ac_exeext=$EXEEXT +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +FILE *f = fopen ("conftest.out", "w"); + return ferror (f) || fclose (f) != 0; + + ; + return 0; +} +_ACEOF +ac_clean_files="$ac_clean_files conftest.out" +# Check that the compiler produces executables we can run. If not, either +# the compiler is broken, or we cross compile. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are cross compiling" >&5 +$as_echo_n "checking whether we are cross compiling... " >&6; } +if test "$cross_compiling" != yes; then + { { ac_try="$ac_link" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_link") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; } + if { ac_try='./conftest$ac_cv_exeext' + { { case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_try") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + cross_compiling=no + else + if test "$cross_compiling" = maybe; then + cross_compiling=yes + else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot run C compiled programs. +If you meant to cross compile, use \`--host'. +See \`config.log' for more details" "$LINENO" 5; } + fi + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $cross_compiling" >&5 +$as_echo "$cross_compiling" >&6; } + +rm -f conftest.$ac_ext conftest$ac_cv_exeext conftest.out +ac_clean_files=$ac_clean_files_save +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for suffix of object files" >&5 +$as_echo_n "checking for suffix of object files... " >&6; } +if ${ac_cv_objext+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +rm -f conftest.o conftest.obj +if { { ac_try="$ac_compile" +case "(($ac_try" in + *\"* | *\`* | *\\*) ac_try_echo=\$ac_try;; + *) ac_try_echo=$ac_try;; +esac +eval ac_try_echo="\"\$as_me:${as_lineno-$LINENO}: $ac_try_echo\"" +$as_echo "$ac_try_echo"; } >&5 + (eval "$ac_compile") 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; then : + for ac_file in conftest.o conftest.obj conftest.*; do + test -f "$ac_file" || continue; + case $ac_file in + *.$ac_ext | *.xcoff | *.tds | *.d | *.pdb | *.xSYM | *.bb | *.bbg | *.map | *.inf | *.dSYM ) ;; + *) ac_cv_objext=`expr "$ac_file" : '.*\.\(.*\)'` + break;; + esac +done +else + $as_echo "$as_me: failed program was:" >&5 +sed 's/^/| /' conftest.$ac_ext >&5 + +{ { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "cannot compute suffix of object files: cannot compile +See \`config.log' for more details" "$LINENO" 5; } +fi +rm -f conftest.$ac_cv_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_objext" >&5 +$as_echo "$ac_cv_objext" >&6; } +OBJEXT=$ac_cv_objext +ac_objext=$OBJEXT +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we are using the GNU C compiler" >&5 +$as_echo_n "checking whether we are using the GNU C compiler... " >&6; } +if ${ac_cv_c_compiler_gnu+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ +#ifndef __GNUC__ + choke me +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_compiler_gnu=yes +else + ac_compiler_gnu=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +ac_cv_c_compiler_gnu=$ac_compiler_gnu + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_compiler_gnu" >&5 +$as_echo "$ac_cv_c_compiler_gnu" >&6; } +if test $ac_compiler_gnu = yes; then + GCC=yes +else + GCC= +fi +ac_test_CFLAGS=${CFLAGS+set} +ac_save_CFLAGS=$CFLAGS +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether $CC accepts -g" >&5 +$as_echo_n "checking whether $CC accepts -g... " >&6; } +if ${ac_cv_prog_cc_g+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_save_c_werror_flag=$ac_c_werror_flag + ac_c_werror_flag=yes + ac_cv_prog_cc_g=no + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +else + CFLAGS="" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + +else + ac_c_werror_flag=$ac_save_c_werror_flag + CFLAGS="-g" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_g=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_c_werror_flag=$ac_save_c_werror_flag +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_g" >&5 +$as_echo "$ac_cv_prog_cc_g" >&6; } +if test "$ac_test_CFLAGS" = set; then + CFLAGS=$ac_save_CFLAGS +elif test $ac_cv_prog_cc_g = yes; then + if test "$GCC" = yes; then + CFLAGS="-g -O2" + else + CFLAGS="-g" + fi +else + if test "$GCC" = yes; then + CFLAGS="-O2" + else + CFLAGS= + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $CC option to accept ISO C89" >&5 +$as_echo_n "checking for $CC option to accept ISO C89... " >&6; } +if ${ac_cv_prog_cc_c89+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_prog_cc_c89=no +ac_save_CC=$CC +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +struct stat; +/* Most of the following tests are stolen from RCS 5.7's src/conf.sh. */ +struct buf { int x; }; +FILE * (*rcsopen) (struct buf *, struct stat *, int); +static char *e (p, i) + char **p; + int i; +{ + return p[i]; +} +static char *f (char * (*g) (char **, int), char **p, ...) +{ + char *s; + va_list v; + va_start (v,p); + s = g (p, va_arg (v,int)); + va_end (v); + return s; +} + +/* OSF 4.0 Compaq cc is some sort of almost-ANSI by default. It has + function prototypes and stuff, but not '\xHH' hex character constants. + These don't provoke an error unfortunately, instead are silently treated + as 'x'. The following induces an error, until -std is added to get + proper ANSI mode. Curiously '\x00'!='x' always comes out true, for an + array size at least. It's necessary to write '\x00'==0 to get something + that's true only with -std. */ +int osf4_cc_array ['\x00' == 0 ? 1 : -1]; + +/* IBM C 6 for AIX is almost-ANSI by default, but it replaces macro parameters + inside strings and character constants. */ +#define FOO(x) 'x' +int xlc6_cc_array[FOO(a) == 'x' ? 1 : -1]; + +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; +int pairnames (int, char **, FILE *(*)(struct buf *, struct stat *, int), int, int); +int argc; +char **argv; +int +main () +{ +return f (e, argv, 0) != argv[0] || f (e, argv, 1) != argv[1]; + ; + return 0; +} +_ACEOF +for ac_arg in '' -qlanglvl=extc89 -qlanglvl=ansi -std \ + -Ae "-Aa -D_HPUX_SOURCE" "-Xc -D__EXTENSIONS__" +do + CC="$ac_save_CC $ac_arg" + if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_prog_cc_c89=$ac_arg +fi +rm -f core conftest.err conftest.$ac_objext + test "x$ac_cv_prog_cc_c89" != "xno" && break +done +rm -f conftest.$ac_ext +CC=$ac_save_CC + +fi +# AC_CACHE_VAL +case "x$ac_cv_prog_cc_c89" in + x) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: none needed" >&5 +$as_echo "none needed" >&6; } ;; + xno) + { $as_echo "$as_me:${as_lineno-$LINENO}: result: unsupported" >&5 +$as_echo "unsupported" >&6; } ;; + *) + CC="$CC $ac_cv_prog_cc_c89" + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_prog_cc_c89" >&5 +$as_echo "$ac_cv_prog_cc_c89" >&6; } ;; +esac +if test "x$ac_cv_prog_cc_c89" != xno; then : + +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + + + +if test "$host" = mips-sni-sysv4 && test -n "$GCC"; then + : +else + +# Check whether --enable-largefile was given. +if test "${enable_largefile+set}" = set; then : + enableval=$enable_largefile; +fi + +if test "$enable_largefile" != no; then + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for special C compiler options needed for large files" >&5 +$as_echo_n "checking for special C compiler options needed for large files... " >&6; } +if ${ac_cv_sys_largefile_CC+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_cv_sys_largefile_CC=no + if test "$GCC" != yes; then + ac_save_CC=$CC + while :; do + # IRIX 6.2 and later do not support large files by default, + # so use the C compiler's -n32 option if that helps. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int +main () +{ + + ; + return 0; +} +_ACEOF + if ac_fn_c_try_compile "$LINENO"; then : + break +fi +rm -f core conftest.err conftest.$ac_objext + CC="$CC -n32" + if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_sys_largefile_CC=' -n32'; break +fi +rm -f core conftest.err conftest.$ac_objext + break + done + CC=$ac_save_CC + rm -f conftest.$ac_ext + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_largefile_CC" >&5 +$as_echo "$ac_cv_sys_largefile_CC" >&6; } + if test "$ac_cv_sys_largefile_CC" != no; then + CC=$CC$ac_cv_sys_largefile_CC + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _FILE_OFFSET_BITS value needed for large files" >&5 +$as_echo_n "checking for _FILE_OFFSET_BITS value needed for large files... " >&6; } +if ${ac_cv_sys_file_offset_bits+:} false; then : + $as_echo_n "(cached) " >&6 +else + while :; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_sys_file_offset_bits=no; break +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#define _FILE_OFFSET_BITS 64 +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_sys_file_offset_bits=64; break +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_cv_sys_file_offset_bits=unknown + break +done +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_file_offset_bits" >&5 +$as_echo "$ac_cv_sys_file_offset_bits" >&6; } +case $ac_cv_sys_file_offset_bits in #( + no | unknown) ;; + *) +cat >>confdefs.h <<_ACEOF +#define _FILE_OFFSET_BITS $ac_cv_sys_file_offset_bits +_ACEOF +;; +esac +rm -rf conftest* + if test $ac_cv_sys_file_offset_bits = unknown; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for _LARGE_FILES value needed for large files" >&5 +$as_echo_n "checking for _LARGE_FILES value needed for large files... " >&6; } +if ${ac_cv_sys_large_files+:} false; then : + $as_echo_n "(cached) " >&6 +else + while :; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_sys_large_files=no; break +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#define _LARGE_FILES 1 +#include + /* Check that off_t can represent 2**63 - 1 correctly. + We can't simply define LARGE_OFF_T to be 9223372036854775807, + since some C++ compilers masquerading as C compilers + incorrectly reject 9223372036854775807. */ +#define LARGE_OFF_T (((off_t) 1 << 62) - 1 + ((off_t) 1 << 62)) + int off_t_is_large[(LARGE_OFF_T % 2147483629 == 721 + && LARGE_OFF_T % 2147483647 == 1) + ? 1 : -1]; +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_sys_large_files=1; break +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + ac_cv_sys_large_files=unknown + break +done +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_sys_large_files" >&5 +$as_echo "$ac_cv_sys_large_files" >&6; } +case $ac_cv_sys_large_files in #( + no | unknown) ;; + *) +cat >>confdefs.h <<_ACEOF +#define _LARGE_FILES $ac_cv_sys_large_files +_ACEOF +;; +esac +rm -rf conftest* + fi + + +fi + +fi + +if test -n "$auto_cflags" && test ."$ansi2knr" != .yes; then + if test "${enable_zsh_debug}" = yes; then + if test -n "$GCC"; then + CFLAGS="$CFLAGS -Wall -Wmissing-prototypes -ggdb" + else + CFLAGS="$CFLAGS -g" + fi + else + if test -n "$GCC"; then + CFLAGS="$CFLAGS -Wall -Wmissing-prototypes -O2" + else + CFLAGS="$CFLAGS -O" + fi + fi +fi +if test -n "$auto_ldflags"; then + case "${enable_zsh_debug}$host_os" in + yesaix*|yeshpux*|yesnetbsd*|yesopenbsd*) ;; # "ld -g" is not valid on these systems + darwin*) LDFLAGS=-Wl,-x ;; + yes*) LDFLAGS=-g ;; + *) LDFLAGS=-s ;; + esac +fi + +case "$host_os" in + sco*) CFLAGS="-D__sco $CFLAGS" ;; +esac + +sed=':1 + s/ -s / /g + t1 + s/^ *// + s/ *$//' + +case " $LDFLAGS " in + *" -s "*) strip_exeldflags=true strip_libldflags=true + LDFLAGS=`echo " $LDFLAGS " | sed "$sed"` ;; + *) strip_exeldflags=false strip_libldflags=false ;; +esac + +case " ${EXELDFLAGS+$EXELDFLAGS }" in + " ") ;; + *" -s "*) strip_exeldflags=true + EXELDFLAGS=`echo " $EXELDFLAGS " | sed "$sed"` ;; + *) strip_exeldflags=false ;; +esac + +case " ${LIBLDFLAGS+$LIBLDFLAGS }" in + " ") ;; + *" -s "*) strip_libldflags=true + LIBLDFLAGS=`echo " $LIBLDFLAGS " | sed "$sed"` ;; + *) strip_libldflags=false ;; +esac + + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking how to run the C preprocessor" >&5 +$as_echo_n "checking how to run the C preprocessor... " >&6; } +# On Suns, sometimes $CPP names a directory. +if test -n "$CPP" && test -d "$CPP"; then + CPP= +fi +if test -z "$CPP"; then + if ${ac_cv_prog_CPP+:} false; then : + $as_echo_n "(cached) " >&6 +else + # Double quotes because CPP needs to be expanded + for CPP in "$CC -E" "$CC -E -traditional-cpp" "/lib/cpp" + do + ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + break +fi + + done + ac_cv_prog_CPP=$CPP + +fi + CPP=$ac_cv_prog_CPP +else + ac_cv_prog_CPP=$CPP +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $CPP" >&5 +$as_echo "$CPP" >&6; } +ac_preproc_ok=false +for ac_c_preproc_warn_flag in '' yes +do + # Use a header file that comes with gcc, so configuring glibc + # with a fresh cross-compiler works. + # Prefer to if __STDC__ is defined, since + # exists even on freestanding compilers. + # On the NeXT, cc -E runs the code through the compiler's parser, + # not just through cpp. "Syntax error" is here to catch this case. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __STDC__ +# include +#else +# include +#endif + Syntax error +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + +else + # Broken: fails on valid input. +continue +fi +rm -f conftest.err conftest.i conftest.$ac_ext + + # OK, works on sane cases. Now check whether nonexistent headers + # can be detected and how. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +_ACEOF +if ac_fn_c_try_cpp "$LINENO"; then : + # Broken: success on invalid input. +continue +else + # Passes both tests. +ac_preproc_ok=: +break +fi +rm -f conftest.err conftest.i conftest.$ac_ext + +done +# Because of `break', _AC_PREPROC_IFELSE's cleaning code was skipped. +rm -f conftest.i conftest.err conftest.$ac_ext +if $ac_preproc_ok; then : + +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error $? "C preprocessor \"$CPP\" fails sanity check +See \`config.log' for more details" "$LINENO" 5; } +fi + +ac_ext=c +ac_cpp='$CPP $CPPFLAGS' +ac_compile='$CC -c $CFLAGS $CPPFLAGS conftest.$ac_ext >&5' +ac_link='$CC -o conftest$ac_exeext $CFLAGS $CPPFLAGS $LDFLAGS conftest.$ac_ext $LIBS >&5' +ac_compiler_gnu=$ac_cv_c_compiler_gnu + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for an ANSI C-conforming const" >&5 +$as_echo_n "checking for an ANSI C-conforming const... " >&6; } +if ${ac_cv_c_const+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + +#ifndef __cplusplus + /* Ultrix mips cc rejects this sort of thing. */ + typedef int charset[2]; + const charset cs = { 0, 0 }; + /* SunOS 4.1.1 cc rejects this. */ + char const *const *pcpcc; + char **ppc; + /* NEC SVR4.0.2 mips cc rejects this. */ + struct point {int x, y;}; + static struct point const zero = {0,0}; + /* AIX XL C 1.02.0.0 rejects this. + It does not let you subtract one const X* pointer from another in + an arm of an if-expression whose if-part is not a constant + expression */ + const char *g = "string"; + pcpcc = &g + (g ? g-g : 0); + /* HPUX 7.0 cc rejects these. */ + ++pcpcc; + ppc = (char**) pcpcc; + pcpcc = (char const *const *) ppc; + { /* SCO 3.2v4 cc rejects this sort of thing. */ + char tx; + char *t = &tx; + char const *s = 0 ? (char *) 0 : (char const *) 0; + + *t++ = 0; + if (s) return 0; + } + { /* Someone thinks the Sun supposedly-ANSI compiler will reject this. */ + int x[] = {25, 17}; + const int *foo = &x[0]; + ++foo; + } + { /* Sun SC1.0 ANSI compiler rejects this -- but not the above. */ + typedef const int *iptr; + iptr p = 0; + ++p; + } + { /* AIX XL C 1.02.0.0 rejects this sort of thing, saying + "k.c", line 2.27: 1506-025 (S) Operand must be a modifiable lvalue. */ + struct s { int j; const int *ap[3]; } bx; + struct s *b = &bx; b->j = 5; + } + { /* ULTRIX-32 V3.1 (Rev 9) vcc rejects this */ + const int foo = 10; + if (!foo) return 0; + } + return !cs[0] && !zero.x; +#endif + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_c_const=yes +else + ac_cv_c_const=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_const" >&5 +$as_echo "$ac_cv_c_const" >&6; } +if test $ac_cv_c_const = no; then + +$as_echo "#define const /**/" >>confdefs.h + +fi + +case "$host_os" in + darwin[0-9].*) CPP="$CPP -traditional-cpp" ;; +esac + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ${CC-cc} option to accept ANSI C" >&5 +$as_echo_n "checking for ${CC-cc} option to accept ANSI C... " >&6; } +if ${fp_cv_prog_cc_stdc+:} false; then : + $as_echo_n "(cached) " >&6 +else + fp_cv_prog_cc_stdc=no +ac_save_CFLAGS="$CFLAGS" +# Don't try gcc -ansi; that turns off useful extensions and +# breaks some systems' header files. +# AIX -qlanglvl=ansi +# Ultrix and OSF/1 -std1 +# HP-UX -Ae or -Aa -D_HPUX_SOURCE +# SVR4 -Xc +# For HP-UX, we try -Ae first; this turns on ANSI but also extensions, +# as well as defining _HPUX_SOURCE, and we can then use long long. +# We keep the old version for backward compatibility. +for ac_arg in "" -qlanglvl=ansi -std1 -Ae "-Aa -D_HPUX_SOURCE" -Xc +do + CFLAGS="$ac_save_CFLAGS $ac_arg" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifndef __STDC__ +choke me +#endif + +int +main () +{ +int test (int i, double x); +struct s1 {int (*f) (int a);}; +struct s2 {int (*f) (double a);}; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + fp_cv_prog_cc_stdc="$ac_arg"; break +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +done +CFLAGS="$ac_save_CFLAGS" + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $fp_cv_prog_cc_stdc" >&5 +$as_echo "$fp_cv_prog_cc_stdc" >&6; } +case "x$fp_cv_prog_cc_stdc" in + x|xno) ;; + *) CC="$CC $fp_cv_prog_cc_stdc" ;; +esac + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether to use prototypes" >&5 +$as_echo_n "checking whether to use prototypes... " >&6; } +if test ."$ansi2knr" = .yes || test ."$ansi2knr" = .no; then + msg="(overridden) " +else + msg= + if test ."$fp_cv_prog_cc_stdc" = .no; then + ansi2knr=yes + else + ansi2knr=no + fi +fi + +if test "$ansi2knr" = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${msg}no" >&5 +$as_echo "${msg}no" >&6; } + U=_ +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: ${msg}yes" >&5 +$as_echo "${msg}yes" >&6; } + $as_echo "#define PROTOTYPES 1" >>confdefs.h + + U= +fi + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for grep that handles long lines and -e" >&5 +$as_echo_n "checking for grep that handles long lines and -e... " >&6; } +if ${ac_cv_path_GREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -z "$GREP"; then + ac_path_GREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in grep ggrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_GREP="$as_dir/$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_GREP" || continue +# Check for GNU ac_path_GREP and select it if it is found. + # Check for GNU $ac_path_GREP +case `"$ac_path_GREP" --version 2>&1` in +*GNU*) + ac_cv_path_GREP="$ac_path_GREP" ac_path_GREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'GREP' >> "conftest.nl" + "$ac_path_GREP" -e 'GREP$' -e '-(cannot match)-' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_GREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_GREP="$ac_path_GREP" + ac_path_GREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_GREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_GREP"; then + as_fn_error $? "no acceptable grep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_GREP=$GREP +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_GREP" >&5 +$as_echo "$ac_cv_path_GREP" >&6; } + GREP="$ac_cv_path_GREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if ${ac_cv_path_EGREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_EGREP" || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_EGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_EGREP=$EGREP +fi + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if ${ac_cv_header_stdc+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes +else + ac_cv_header_stdc=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +$as_echo "#define STDC_HEADERS 1" >>confdefs.h + +fi + +# On IRIX 5.3, sys/types and inttypes.h are conflicting. +for ac_header in sys/types.h sys/stat.h stdlib.h string.h memory.h strings.h \ + inttypes.h stdint.h unistd.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + +ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" +if test "x$ac_cv_type_size_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define size_t unsigned int +_ACEOF + +fi + +# The Ultrix 4.2 mips builtin alloca declared by alloca.h only works +# for constant arguments. Useless! +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working alloca.h" >&5 +$as_echo_n "checking for working alloca.h... " >&6; } +if ${ac_cv_working_alloca_h+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +char *p = (char *) alloca (2 * sizeof (int)); + if (p) return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_working_alloca_h=yes +else + ac_cv_working_alloca_h=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_working_alloca_h" >&5 +$as_echo "$ac_cv_working_alloca_h" >&6; } +if test $ac_cv_working_alloca_h = yes; then + +$as_echo "#define HAVE_ALLOCA_H 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for alloca" >&5 +$as_echo_n "checking for alloca... " >&6; } +if ${ac_cv_func_alloca_works+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __GNUC__ +# define alloca __builtin_alloca +#else +# ifdef _MSC_VER +# include +# define alloca _alloca +# else +# ifdef HAVE_ALLOCA_H +# include +# else +# ifdef _AIX + #pragma alloca +# else +# ifndef alloca /* predefined by HP cc +Olibcalls */ +void *alloca (size_t); +# endif +# endif +# endif +# endif +#endif + +int +main () +{ +char *p = (char *) alloca (1); + if (p) return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_func_alloca_works=yes +else + ac_cv_func_alloca_works=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_alloca_works" >&5 +$as_echo "$ac_cv_func_alloca_works" >&6; } + +if test $ac_cv_func_alloca_works = yes; then + +$as_echo "#define HAVE_ALLOCA 1" >>confdefs.h + +else + # The SVR3 libPW and SVR4 libucb both contain incompatible functions +# that cause trouble. Some versions do not even contain alloca or +# contain a buggy version. If you still want to use their alloca, +# use ar to extract alloca.o from them instead of compiling alloca.c. + +ALLOCA=\${LIBOBJDIR}alloca.$ac_objext + +$as_echo "#define C_ALLOCA 1" >>confdefs.h + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether \`alloca.c' needs Cray hooks" >&5 +$as_echo_n "checking whether \`alloca.c' needs Cray hooks... " >&6; } +if ${ac_cv_os_cray+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#if defined CRAY && ! defined CRAY2 +webecray +#else +wenotbecray +#endif + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "webecray" >/dev/null 2>&1; then : + ac_cv_os_cray=yes +else + ac_cv_os_cray=no +fi +rm -f conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_os_cray" >&5 +$as_echo "$ac_cv_os_cray" >&6; } +if test $ac_cv_os_cray = yes; then + for ac_func in _getb67 GETB67 getb67; do + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + +cat >>confdefs.h <<_ACEOF +#define CRAY_STACKSEG_END $ac_func +_ACEOF + + break +fi + + done +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking stack direction for C alloca" >&5 +$as_echo_n "checking stack direction for C alloca... " >&6; } +if ${ac_cv_c_stack_direction+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_c_stack_direction=0 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +find_stack_direction (int *addr, int depth) +{ + int dir, dummy = 0; + if (! addr) + addr = &dummy; + *addr = addr < &dummy ? 1 : addr == &dummy ? 0 : -1; + dir = depth ? find_stack_direction (addr, depth - 1) : 0; + return dir + dummy; +} + +int +main (int argc, char **argv) +{ + return find_stack_direction (0, argc + !argv + 20) < 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_c_stack_direction=1 +else + ac_cv_c_stack_direction=-1 +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_c_stack_direction" >&5 +$as_echo "$ac_cv_c_stack_direction" >&6; } +cat >>confdefs.h <<_ACEOF +#define STACK_DIRECTION $ac_cv_c_stack_direction +_ACEOF + + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if the compiler supports union initialisation" >&5 +$as_echo_n "checking if the compiler supports union initialisation... " >&6; } +if ${zsh_cv_c_have_union_init+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +union{void *p;long l;}u={0}; +int +main () +{ +u.l=1; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_c_have_union_init=yes +else + zsh_cv_c_have_union_init=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_c_have_union_init" >&5 +$as_echo "$zsh_cv_c_have_union_init" >&6; } + +if test x$zsh_cv_c_have_union_init = xyes; then + $as_echo "#define HAVE_UNION_INIT 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if signed to unsigned casting is broken" >&5 +$as_echo_n "checking if signed to unsigned casting is broken... " >&6; } +if ${zsh_cv_c_broken_signed_to_unsigned_casting+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_c_broken_signed_to_unsigned_casting=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +main(){return((int)(unsigned char)((char) -1) == 255);} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_c_broken_signed_to_unsigned_casting=yes +else + zsh_cv_c_broken_signed_to_unsigned_casting=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_c_broken_signed_to_unsigned_casting" >&5 +$as_echo "$zsh_cv_c_broken_signed_to_unsigned_casting" >&6; } + +if test x$zsh_cv_c_broken_signed_to_unsigned_casting = xyes; then + $as_echo "#define BROKEN_SIGNED_TO_UNSIGNED_CASTING 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if the compiler supports variable-length arrays" >&5 +$as_echo_n "checking if the compiler supports variable-length arrays... " >&6; } +if ${zsh_cv_c_variable_length_arrays+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int foo(), n; +int +main () +{ +int i[foo()], a[n+1]; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_c_variable_length_arrays=yes +else + zsh_cv_c_variable_length_arrays=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_c_variable_length_arrays" >&5 +$as_echo "$zsh_cv_c_variable_length_arrays" >&6; } + +if test x$zsh_cv_c_variable_length_arrays = xyes; then + $as_echo "#define HAVE_VARIABLE_LENGTH_ARRAYS 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ${MAKE-make} sets \$(MAKE)" >&5 +$as_echo_n "checking whether ${MAKE-make} sets \$(MAKE)... " >&6; } +set x ${MAKE-make} +ac_make=`$as_echo "$2" | sed 's/+/p/g; s/[^a-zA-Z0-9_]/_/g'` +if eval \${ac_cv_prog_make_${ac_make}_set+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat >conftest.make <<\_ACEOF +SHELL = /bin/sh +all: + @echo '@@@%%%=$(MAKE)=@@@%%%' +_ACEOF +# GNU make sometimes prints "make[1]: Entering ...", which would confuse us. +case `${MAKE-make} -f conftest.make 2>/dev/null` in + *@@@%%%=?*=@@@%%%*) + eval ac_cv_prog_make_${ac_make}_set=yes;; + *) + eval ac_cv_prog_make_${ac_make}_set=no;; +esac +rm -f conftest.make +fi +if eval test \$ac_cv_prog_make_${ac_make}_set = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } + SET_MAKE= +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } + SET_MAKE="MAKE=${MAKE-make}" +fi + # Find a good install program. We prefer a C program (faster), +# so one script is as good as another. But avoid the broken or +# incompatible versions: +# SysV /etc/install, /usr/sbin/install +# SunOS /usr/etc/install +# IRIX /sbin/install +# AIX /bin/install +# AmigaOS /C/install, which installs bootblocks on floppy discs +# AIX 4 /usr/bin/installbsd, which doesn't work without a -g flag +# AFS /usr/afsws/bin/install, which mishandles nonexistent args +# SVR4 /usr/ucb/install, which tries to use the nonexistent group "staff" +# OS/2's system install, which has a completely different semantic +# ./install, which can be erroneously created by make from ./install.sh. +# Reject install programs that cannot install multiple files. +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for a BSD-compatible install" >&5 +$as_echo_n "checking for a BSD-compatible install... " >&6; } +if test -z "$INSTALL"; then +if ${ac_cv_path_install+:} false; then : + $as_echo_n "(cached) " >&6 +else + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + # Account for people who put trailing slashes in PATH elements. +case $as_dir/ in #(( + ./ | .// | /[cC]/* | \ + /etc/* | /usr/sbin/* | /usr/etc/* | /sbin/* | /usr/afsws/bin/* | \ + ?:[\\/]os2[\\/]install[\\/]* | ?:[\\/]OS2[\\/]INSTALL[\\/]* | \ + /usr/ucb/* ) ;; + *) + # OSF1 and SCO ODT 3.0 have their own names for install. + # Don't use installbsd from OSF since it installs stuff as root + # by default. + for ac_prog in ginstall scoinst install; do + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_prog$ac_exec_ext"; then + if test $ac_prog = install && + grep dspmsg "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # AIX install. It has an incompatible calling convention. + : + elif test $ac_prog = install && + grep pwplus "$as_dir/$ac_prog$ac_exec_ext" >/dev/null 2>&1; then + # program-specific install script used by HP pwplus--don't use. + : + else + rm -rf conftest.one conftest.two conftest.dir + echo one > conftest.one + echo two > conftest.two + mkdir conftest.dir + if "$as_dir/$ac_prog$ac_exec_ext" -c conftest.one conftest.two "`pwd`/conftest.dir" && + test -s conftest.one && test -s conftest.two && + test -s conftest.dir/conftest.one && + test -s conftest.dir/conftest.two + then + ac_cv_path_install="$as_dir/$ac_prog$ac_exec_ext -c" + break 3 + fi + fi + fi + done + done + ;; +esac + + done +IFS=$as_save_IFS + +rm -rf conftest.one conftest.two conftest.dir + +fi + if test "${ac_cv_path_install+set}" = set; then + INSTALL=$ac_cv_path_install + else + # As a last resort, use the slow shell script. Don't cache a + # value for INSTALL within a source directory, because that will + # break other packages using the cache if that directory is + # removed, or if the value is a relative name. + INSTALL=$ac_install_sh + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $INSTALL" >&5 +$as_echo "$INSTALL" >&6; } + +# Use test -z because SunOS4 sh mishandles braces in ${var-val}. +# It thinks the first close brace ends the variable substitution. +test -z "$INSTALL_PROGRAM" && INSTALL_PROGRAM='${INSTALL}' + +test -z "$INSTALL_SCRIPT" && INSTALL_SCRIPT='${INSTALL}' + +test -z "$INSTALL_DATA" && INSTALL_DATA='${INSTALL} -m 644' + for ac_prog in gawk mawk nawk awk +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_AWK+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$AWK"; then + ac_cv_prog_AWK="$AWK" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_AWK="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +AWK=$ac_cv_prog_AWK +if test -n "$AWK"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $AWK" >&5 +$as_echo "$AWK" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$AWK" && break +done + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln works" >&5 +$as_echo_n "checking whether ln works... " >&6; } +if ${ac_cv_prog_LN+:} false; then : + $as_echo_n "(cached) " >&6 +else + rm -f conftestdata conftestlink +echo > conftestdata +if ln conftestdata conftestlink 2>/dev/null +then + rm -f conftestdata conftestlink + ac_cv_prog_LN="ln" +else + rm -f conftestdata + ac_cv_prog_LN="cp" +fi +fi +LN="$ac_cv_prog_LN" +if test "$ac_cv_prog_LN" = "ln"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether ln -s works" >&5 +$as_echo_n "checking whether ln -s works... " >&6; } +LN_S=$as_ln_s +if test "$LN_S" = "ln -s"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: yes" >&5 +$as_echo "yes" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no, using $LN_S" >&5 +$as_echo "no, using $LN_S" >&6; } +fi + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for egrep" >&5 +$as_echo_n "checking for egrep... " >&6; } +if ${ac_cv_path_EGREP+:} false; then : + $as_echo_n "(cached) " >&6 +else + if echo a | $GREP -E '(a|b)' >/dev/null 2>&1 + then ac_cv_path_EGREP="$GREP -E" + else + if test -z "$EGREP"; then + ac_path_EGREP_found=false + # Loop through the user's path and test for each of PROGNAME-LIST + as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH$PATH_SEPARATOR/usr/xpg4/bin +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_prog in egrep; do + for ac_exec_ext in '' $ac_executable_extensions; do + ac_path_EGREP="$as_dir/$ac_prog$ac_exec_ext" + as_fn_executable_p "$ac_path_EGREP" || continue +# Check for GNU ac_path_EGREP and select it if it is found. + # Check for GNU $ac_path_EGREP +case `"$ac_path_EGREP" --version 2>&1` in +*GNU*) + ac_cv_path_EGREP="$ac_path_EGREP" ac_path_EGREP_found=:;; +*) + ac_count=0 + $as_echo_n 0123456789 >"conftest.in" + while : + do + cat "conftest.in" "conftest.in" >"conftest.tmp" + mv "conftest.tmp" "conftest.in" + cp "conftest.in" "conftest.nl" + $as_echo 'EGREP' >> "conftest.nl" + "$ac_path_EGREP" 'EGREP$' < "conftest.nl" >"conftest.out" 2>/dev/null || break + diff "conftest.out" "conftest.nl" >/dev/null 2>&1 || break + as_fn_arith $ac_count + 1 && ac_count=$as_val + if test $ac_count -gt ${ac_path_EGREP_max-0}; then + # Best one so far, save it but keep looking for a better one + ac_cv_path_EGREP="$ac_path_EGREP" + ac_path_EGREP_max=$ac_count + fi + # 10*(2^10) chars as input seems more than enough + test $ac_count -gt 10 && break + done + rm -f conftest.in conftest.tmp conftest.nl conftest.out;; +esac + + $ac_path_EGREP_found && break 3 + done + done + done +IFS=$as_save_IFS + if test -z "$ac_cv_path_EGREP"; then + as_fn_error $? "no acceptable egrep could be found in $PATH$PATH_SEPARATOR/usr/xpg4/bin" "$LINENO" 5 + fi +else + ac_cv_path_EGREP=$EGREP +fi + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_path_EGREP" >&5 +$as_echo "$ac_cv_path_EGREP" >&6; } + EGREP="$ac_cv_path_EGREP" + + for ac_prog in yodl +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_YODL+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$YODL"; then + ac_cv_prog_YODL="$YODL" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_YODL="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +YODL=$ac_cv_prog_YODL +if test -n "$YODL"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $YODL" >&5 +$as_echo "$YODL" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$YODL" && break +done +test -n "$YODL" || YODL=": yodl" + + +YODL_OPTIONS='' +if test "x$ac_cv_prog_YODL" = xyodl; then + case `yodl --version` in + *"version 2."*) YODL_OPTIONS='-k' ;; + *"version 3."*) YODL_OPTIONS='-k -L' ;; + *"version 4."*) YODL_OPTIONS='-k -L' ;; + esac +fi + + +for ac_prog in texi2dvi +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_TEXI2DVI+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$TEXI2DVI"; then + ac_cv_prog_TEXI2DVI="$TEXI2DVI" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_TEXI2DVI="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +TEXI2DVI=$ac_cv_prog_TEXI2DVI +if test -n "$TEXI2DVI"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $TEXI2DVI" >&5 +$as_echo "$TEXI2DVI" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$TEXI2DVI" && break +done +test -n "$TEXI2DVI" || TEXI2DVI=": texi2dvi" + +for ac_prog in texi2pdf +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_TEXI2PDF+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$TEXI2PDF"; then + ac_cv_prog_TEXI2PDF="$TEXI2PDF" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_TEXI2PDF="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +TEXI2PDF=$ac_cv_prog_TEXI2PDF +if test -n "$TEXI2PDF"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $TEXI2PDF" >&5 +$as_echo "$TEXI2PDF" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$TEXI2PDF" && break +done +test -n "$TEXI2PDF" || TEXI2PDF=": texi2pdf" + +for ac_prog in texi2any texi2html +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_TEXI2HTML+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$TEXI2HTML"; then + ac_cv_prog_TEXI2HTML="$TEXI2HTML" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_TEXI2HTML="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +TEXI2HTML=$ac_cv_prog_TEXI2HTML +if test -n "$TEXI2HTML"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $TEXI2HTML" >&5 +$as_echo "$TEXI2HTML" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$TEXI2HTML" && break +done +test -n "$TEXI2HTML" || TEXI2HTML=": texi2html" + + +if test x"$TEXI2PDF" != xtexi2pdf && test x"$TEXI2DVI" = xtexi2dvi; then + TEXI2PDF='texi2dvi --pdf' +fi + +if test x"$TEXI2HTML" = xtexi2any; then + TEXI2HTML='texi2any -c TEXI2HTML=1' +fi + +case "$LC_PAPER" in + ??_US*) PAPERSIZE=us ;; + *) PAPERSIZE=a4 ;; +esac + + +for ac_prog in ansi2knr +do + # Extract the first word of "$ac_prog", so it can be a program name with args. +set dummy $ac_prog; ac_word=$2 +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_word" >&5 +$as_echo_n "checking for $ac_word... " >&6; } +if ${ac_cv_prog_ANSI2KNR+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -n "$ANSI2KNR"; then + ac_cv_prog_ANSI2KNR="$ANSI2KNR" # Let the user override the test. +else +as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + for ac_exec_ext in '' $ac_executable_extensions; do + if as_fn_executable_p "$as_dir/$ac_word$ac_exec_ext"; then + ac_cv_prog_ANSI2KNR="$ac_prog" + $as_echo "$as_me:${as_lineno-$LINENO}: found $as_dir/$ac_word$ac_exec_ext" >&5 + break 2 + fi +done + done +IFS=$as_save_IFS + +fi +fi +ANSI2KNR=$ac_cv_prog_ANSI2KNR +if test -n "$ANSI2KNR"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ANSI2KNR" >&5 +$as_echo "$ANSI2KNR" >&6; } +else + { $as_echo "$as_me:${as_lineno-$LINENO}: result: no" >&5 +$as_echo "no" >&6; } +fi + + + test -n "$ANSI2KNR" && break +done +test -n "$ANSI2KNR" || ANSI2KNR=": ansi2knr" + + +if test x"$ansi2knr" = xyes && test x"$ANSI2KNR" = x": ansi2knr"; then + echo "----------" + echo "configure fatal error:" + echo "ansi2knr was specified (--enable-ansi2knr) but the program could not be found." + echo "Either remove the configure option if it is not required or build the ansi2knr" + echo "program before reconfiguring Zsh. The source code for ansi2knr is also" + echo "available in the GPL directory on Zsh distribution sites." + exit 1 +fi + +ac_header_dirent=no +for ac_hdr in dirent.h sys/ndir.h sys/dir.h ndir.h; do + as_ac_Header=`$as_echo "ac_cv_header_dirent_$ac_hdr" | $as_tr_sh` +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for $ac_hdr that defines DIR" >&5 +$as_echo_n "checking for $ac_hdr that defines DIR... " >&6; } +if eval \${$as_ac_Header+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include <$ac_hdr> + +int +main () +{ +if ((DIR *) 0) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + eval "$as_ac_Header=yes" +else + eval "$as_ac_Header=no" +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +eval ac_res=\$$as_ac_Header + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_res" >&5 +$as_echo "$ac_res" >&6; } +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_hdr" | $as_tr_cpp` 1 +_ACEOF + +ac_header_dirent=$ac_hdr; break +fi + +done +# Two versions of opendir et al. are in -ldir and -lx on SCO Xenix. +if test $ac_header_dirent = dirent.h; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 +$as_echo_n "checking for library containing opendir... " >&6; } +if ${ac_cv_search_opendir+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char opendir (); +int +main () +{ +return opendir (); + ; + return 0; +} +_ACEOF +for ac_lib in '' dir; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_opendir=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_opendir+:} false; then : + break +fi +done +if ${ac_cv_search_opendir+:} false; then : + +else + ac_cv_search_opendir=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 +$as_echo "$ac_cv_search_opendir" >&6; } +ac_res=$ac_cv_search_opendir +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing opendir" >&5 +$as_echo_n "checking for library containing opendir... " >&6; } +if ${ac_cv_search_opendir+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char opendir (); +int +main () +{ +return opendir (); + ; + return 0; +} +_ACEOF +for ac_lib in '' x; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_opendir=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_opendir+:} false; then : + break +fi +done +if ${ac_cv_search_opendir+:} false; then : + +else + ac_cv_search_opendir=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_opendir" >&5 +$as_echo "$ac_cv_search_opendir" >&6; } +ac_res=$ac_cv_search_opendir +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ANSI C header files" >&5 +$as_echo_n "checking for ANSI C header files... " >&6; } +if ${ac_cv_header_stdc+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include +#include + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stdc=yes +else + ac_cv_header_stdc=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +if test $ac_cv_header_stdc = yes; then + # SunOS 4.x string.h does not declare mem*, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "memchr" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # ISC 2.0.2 stdlib.h does not declare free, contrary to ANSI. + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "free" >/dev/null 2>&1; then : + +else + ac_cv_header_stdc=no +fi +rm -f conftest* + +fi + +if test $ac_cv_header_stdc = yes; then + # /bin/cc in Irix-4.0.5 gets non-ANSI ctype macros unless using -ansi. + if test "$cross_compiling" = yes; then : + : +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#if ((' ' & 0x0FF) == 0x020) +# define ISLOWER(c) ('a' <= (c) && (c) <= 'z') +# define TOUPPER(c) (ISLOWER(c) ? 'A' + ((c) - 'a') : (c)) +#else +# define ISLOWER(c) \ + (('a' <= (c) && (c) <= 'i') \ + || ('j' <= (c) && (c) <= 'r') \ + || ('s' <= (c) && (c) <= 'z')) +# define TOUPPER(c) (ISLOWER(c) ? ((c) | 0x40) : (c)) +#endif + +#define XOR(e, f) (((e) && !(f)) || (!(e) && (f))) +int +main () +{ + int i; + for (i = 0; i < 256; i++) + if (XOR (islower (i), ISLOWER (i)) + || toupper (i) != TOUPPER (i)) + return 2; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + +else + ac_cv_header_stdc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stdc" >&5 +$as_echo "$ac_cv_header_stdc" >&6; } +if test $ac_cv_header_stdc = yes; then + +$as_echo "#define STDC_HEADERS 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether time.h and sys/time.h may both be included" >&5 +$as_echo_n "checking whether time.h and sys/time.h may both be included... " >&6; } +if ${ac_cv_header_time+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#include + +int +main () +{ +if ((struct tm *) 0) +return 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_time=yes +else + ac_cv_header_time=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_time" >&5 +$as_echo "$ac_cv_header_time" >&6; } +if test $ac_cv_header_time = yes; then + +$as_echo "#define TIME_WITH_SYS_TIME 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether stat file-mode macros are broken" >&5 +$as_echo_n "checking whether stat file-mode macros are broken... " >&6; } +if ${ac_cv_header_stat_broken+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include + +#if defined S_ISBLK && defined S_IFDIR +extern char c1[S_ISBLK (S_IFDIR) ? -1 : 1]; +#endif + +#if defined S_ISBLK && defined S_IFCHR +extern char c2[S_ISBLK (S_IFCHR) ? -1 : 1]; +#endif + +#if defined S_ISLNK && defined S_IFREG +extern char c3[S_ISLNK (S_IFREG) ? -1 : 1]; +#endif + +#if defined S_ISSOCK && defined S_IFREG +extern char c4[S_ISSOCK (S_IFREG) ? -1 : 1]; +#endif + +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_stat_broken=no +else + ac_cv_header_stat_broken=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_stat_broken" >&5 +$as_echo "$ac_cv_header_stat_broken" >&6; } +if test $ac_cv_header_stat_broken = yes; then + +$as_echo "#define STAT_MACROS_BROKEN 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sys/wait.h that is POSIX.1 compatible" >&5 +$as_echo_n "checking for sys/wait.h that is POSIX.1 compatible... " >&6; } +if ${ac_cv_header_sys_wait_h+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +#ifndef WEXITSTATUS +# define WEXITSTATUS(stat_val) ((unsigned int) (stat_val) >> 8) +#endif +#ifndef WIFEXITED +# define WIFEXITED(stat_val) (((stat_val) & 255) == 0) +#endif + +int +main () +{ + int s; + wait (&s); + s = WIFEXITED (s) ? WEXITSTATUS (s) : 1; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_sys_wait_h=yes +else + ac_cv_header_sys_wait_h=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_sys_wait_h" >&5 +$as_echo "$ac_cv_header_sys_wait_h" >&6; } +if test $ac_cv_header_sys_wait_h = yes; then + +$as_echo "#define HAVE_SYS_WAIT_H 1" >>confdefs.h + +fi + + +oldcflags="$CFLAGS" + +for ac_header in sys/time.h sys/times.h sys/select.h termcap.h termio.h \ + termios.h sys/param.h sys/filio.h string.h memory.h \ + limits.h fcntl.h libc.h sys/utsname.h sys/resource.h \ + locale.h errno.h stdio.h stdarg.h varargs.h stdlib.h \ + unistd.h sys/capability.h \ + utmp.h utmpx.h sys/types.h pwd.h grp.h poll.h sys/mman.h \ + netinet/in_systm.h langinfo.h wchar.h stddef.h \ + sys/stropts.h iconv.h ncurses.h ncursesw/ncurses.h \ + ncurses/ncurses.h +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_mongrel "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + +if test x$dynamic = xyes; then + for ac_header in dlfcn.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "dlfcn.h" "ac_cv_header_dlfcn_h" "$ac_includes_default" +if test "x$ac_cv_header_dlfcn_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_DLFCN_H 1 +_ACEOF + +fi + +done + + for ac_header in dl.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "dl.h" "ac_cv_header_dl_h" "$ac_includes_default" +if test "x$ac_cv_header_dl_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_DL_H 1 +_ACEOF + +fi + +done + +fi + + +if test x$ac_cv_header_sys_time_h = xyes && test x$ac_cv_header_sys_select_h = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for conflicts in sys/time.h and sys/select.h" >&5 +$as_echo_n "checking for conflicts in sys/time.h and sys/select.h... " >&6; } +if ${zsh_cv_header_time_h_select_h_conflicts+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +int +main () +{ +int i; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_header_time_h_select_h_conflicts=no +else + zsh_cv_header_time_h_select_h_conflicts=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_header_time_h_select_h_conflicts" >&5 +$as_echo "$zsh_cv_header_time_h_select_h_conflicts" >&6; } + if test x$zsh_cv_header_time_h_select_h_conflicts = xyes; then + $as_echo "#define TIME_H_SELECT_H_CONFLICTS 1" >>confdefs.h + + fi +fi + + +if test x$ac_cv_header_termios_h = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking TIOCGWINSZ in termios.h" >&5 +$as_echo_n "checking TIOCGWINSZ in termios.h... " >&6; } +if ${zsh_cv_header_termios_h_tiocgwinsz+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include +int +main () +{ +int x = TIOCGWINSZ; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + zsh_cv_header_termios_h_tiocgwinsz=yes +else + zsh_cv_header_termios_h_tiocgwinsz=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_header_termios_h_tiocgwinsz" >&5 +$as_echo "$zsh_cv_header_termios_h_tiocgwinsz" >&6; } +else + zsh_cv_header_termios_h_tiocgwinsz=no +fi +if test x$zsh_cv_header_termios_h_tiocgwinsz = xno; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking TIOCGWINSZ in sys/ioctl.h" >&5 +$as_echo_n "checking TIOCGWINSZ in sys/ioctl.h... " >&6; } +if ${zsh_cv_header_sys_ioctl_h_tiocgwinsz+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include +int +main () +{ +int x = TIOCGWINSZ; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + zsh_cv_header_sys_ioctl_h_tiocgwinsz=yes +else + zsh_cv_header_sys_ioctl_h_tiocgwinsz=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_header_sys_ioctl_h_tiocgwinsz" >&5 +$as_echo "$zsh_cv_header_sys_ioctl_h_tiocgwinsz" >&6; } + if test x$zsh_cv_header_sys_ioctl_h_tiocgwinsz = xyes; then + $as_echo "#define GWINSZ_IN_SYS_IOCTL 1" >>confdefs.h + + fi +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for streams headers including struct winsize" >&5 +$as_echo_n "checking for streams headers including struct winsize... " >&6; } +if ${ac_cv_winsize_in_ptem+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +int +main () +{ +struct winsize wsz + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_winsize_in_ptem=yes +else + ac_cv_winsize_in_ptem=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_winsize_in_ptem" >&5 +$as_echo "$ac_cv_winsize_in_ptem" >&6; } +if test x$ac_cv_winsize_in_ptem = xyes; then + $as_echo "#define WINSIZE_IN_PTEM 1" >>confdefs.h + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for printf in -lc" >&5 +$as_echo_n "checking for printf in -lc... " >&6; } +if ${ac_cv_lib_c_printf+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lc $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char printf (); +int +main () +{ +return printf (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_c_printf=yes +else + ac_cv_lib_c_printf=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_c_printf" >&5 +$as_echo "$ac_cv_lib_c_printf" >&6; } +if test "x$ac_cv_lib_c_printf" = xyes; then : + LIBS="$LIBS -lc" +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for pow in -lm" >&5 +$as_echo_n "checking for pow in -lm... " >&6; } +if ${ac_cv_lib_m_pow+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lm $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char pow (); +int +main () +{ +return pow (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_m_pow=yes +else + ac_cv_lib_m_pow=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_m_pow" >&5 +$as_echo "$ac_cv_lib_m_pow" >&6; } +if test "x$ac_cv_lib_m_pow" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBM 1 +_ACEOF + + LIBS="-lm $LIBS" + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for clock_gettime in -lrt" >&5 +$as_echo_n "checking for clock_gettime in -lrt... " >&6; } +if ${ac_cv_lib_rt_clock_gettime+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lrt $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char clock_gettime (); +int +main () +{ +return clock_gettime (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_rt_clock_gettime=yes +else + ac_cv_lib_rt_clock_gettime=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_rt_clock_gettime" >&5 +$as_echo "$ac_cv_lib_rt_clock_gettime" >&6; } +if test "x$ac_cv_lib_rt_clock_gettime" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBRT 1 +_ACEOF + + LIBS="-lrt $LIBS" + +fi + + +if test x$ac_cv_header_ncurses_h = xyes || test x$ac_cv_header_ncurses_ncurses_h = xyes || test x$ac_cv_header_ncursesw_ncurses_h = xyes; then + ncursesw_test=ncursesw + ncurses_test=ncurses +else + ncursesw_test= + ncurses_test= +fi + + +# Check whether --with-term-lib was given. +if test "${with_term_lib+set}" = set; then : + withval=$with_term_lib; if test "x$withval" != xno && test "x$withval" != x ; then + termcap_curses_order="$withval" + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing tigetstr" >&5 +$as_echo_n "checking for library containing tigetstr... " >&6; } +if ${ac_cv_search_tigetstr+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char tigetstr (); +int +main () +{ +return tigetstr (); + ; + return 0; +} +_ACEOF +for ac_lib in '' $termcap_curses_order; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_tigetstr=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_tigetstr+:} false; then : + break +fi +done +if ${ac_cv_search_tigetstr+:} false; then : + +else + ac_cv_search_tigetstr=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_tigetstr" >&5 +$as_echo "$ac_cv_search_tigetstr" >&6; } +ac_res=$ac_cv_search_tigetstr +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +else + termcap_curses_order="$ncursesw_test tinfo termcap $ncurses_test curses" +fi +else + case "$host_os" in + solaris*) + termcap_curses_order="$ncursesw_test $ncurses_test curses termcap" ;; + hpux10.*|hpux11.*) + DL_EXT="${DL_EXT=sl}" + termcap_curses_order="Hcurses $ncursesw_test $ncurses_test curses termcap" ;; + *) + termcap_curses_order="$ncursesw_test tinfo termcap $ncurses_test curses" ;; +esac +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if _XOPEN_SOURCE_EXTENDED should not be defined" >&5 +$as_echo_n "checking if _XOPEN_SOURCE_EXTENDED should not be defined... " >&6; } +if ${zsh_cv_no_xopen+:} false; then : + $as_echo_n "(cached) " >&6 +else + case "$host_os" in + *freebsd5*|*freebsd6.[012]*|*aix*) + zsh_cv_no_xopen=yes + ;; + *) + zsh_cv_no_xopen=no + ;; +esac +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_no_xopen" >&5 +$as_echo "$zsh_cv_no_xopen" >&6; } +if test x$zsh_cv_no_xopen = xyes; then + $as_echo "#define ZSH_NO_XOPEN 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing tigetflag" >&5 +$as_echo_n "checking for library containing tigetflag... " >&6; } +if ${ac_cv_search_tigetflag+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char tigetflag (); +int +main () +{ +return tigetflag (); + ; + return 0; +} +_ACEOF +for ac_lib in '' $termcap_curses_order; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_tigetflag=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_tigetflag+:} false; then : + break +fi +done +if ${ac_cv_search_tigetflag+:} false; then : + +else + ac_cv_search_tigetflag=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_tigetflag" >&5 +$as_echo "$ac_cv_search_tigetflag" >&6; } +ac_res=$ac_cv_search_tigetflag +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing tgetent" >&5 +$as_echo_n "checking for library containing tgetent... " >&6; } +if ${ac_cv_search_tgetent+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char tgetent (); +int +main () +{ +return tgetent (); + ; + return 0; +} +_ACEOF +for ac_lib in '' $termcap_curses_order; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_tgetent=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_tgetent+:} false; then : + break +fi +done +if ${ac_cv_search_tgetent+:} false; then : + +else + ac_cv_search_tgetent=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_tgetent" >&5 +$as_echo "$ac_cv_search_tgetent" >&6; } +ac_res=$ac_cv_search_tgetent +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + true +else + { { $as_echo "$as_me:${as_lineno-$LINENO}: error: in \`$ac_pwd':" >&5 +$as_echo "$as_me: error: in \`$ac_pwd':" >&2;} +as_fn_error 255 "\"No terminal handling library was found on your system. +This is probably a library called 'curses' or 'ncurses'. You may +need to install a package called 'curses-devel' or 'ncurses-devel' on your +system.\" +See \`config.log' for more details" "$LINENO" 5; } +fi + +for ac_header in curses.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "curses.h" "ac_cv_header_curses_h" "$ac_includes_default" +if test "x$ac_cv_header_curses_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_CURSES_H 1 +_ACEOF + +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for Solaris 8 curses.h mistake" >&5 +$as_echo_n "checking for Solaris 8 curses.h mistake... " >&6; } +if ${ac_cv_header_curses_solaris+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_header_curses_h=yes +ac_cv_header_curses_solaris=yes +else + ac_cv_header_curses_h=no +ac_cv_header_curses_solaris=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_header_curses_solaris" >&5 +$as_echo "$ac_cv_header_curses_solaris" >&6; } +if test x$ac_cv_header_curses_solaris = xyes; then +$as_echo "#define HAVE_CURSES_H 1" >>confdefs.h + +fi +fi + +done + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if we need to ignore ncurses" >&5 +$as_echo_n "checking if we need to ignore ncurses... " >&6; } +if ${zsh_cv_ignore_ncurses+:} false; then : + $as_echo_n "(cached) " >&6 +else + case $LIBS in + *-lncurses*) + zsh_cv_ignore_ncurses=no + ;; + *) + zsh_cv_ignore_ncurses=yes + ;; +esac +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_ignore_ncurses" >&5 +$as_echo "$zsh_cv_ignore_ncurses" >&6; } + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing getpwnam" >&5 +$as_echo_n "checking for library containing getpwnam... " >&6; } +if ${ac_cv_search_getpwnam+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char getpwnam (); +int +main () +{ +return getpwnam (); + ; + return 0; +} +_ACEOF +for ac_lib in '' nsl; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_getpwnam=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_getpwnam+:} false; then : + break +fi +done +if ${ac_cv_search_getpwnam+:} false; then : + +else + ac_cv_search_getpwnam=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_getpwnam" >&5 +$as_echo "$ac_cv_search_getpwnam" >&6; } +ac_res=$ac_cv_search_getpwnam +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + + +if test `echo $host_os | sed 's/^\(unicos\).*/\1/'` = unicos; then + LIBS="-lcraylm -lkrb -lnisdb -lnsl -lrpcsvc $LIBS" +fi + +if test "x$dynamic" = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for dlopen in -ldl" >&5 +$as_echo_n "checking for dlopen in -ldl... " >&6; } +if ${ac_cv_lib_dl_dlopen+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-ldl $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char dlopen (); +int +main () +{ +return dlopen (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_dl_dlopen=yes +else + ac_cv_lib_dl_dlopen=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_dl_dlopen" >&5 +$as_echo "$ac_cv_lib_dl_dlopen" >&6; } +if test "x$ac_cv_lib_dl_dlopen" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBDL 1 +_ACEOF + + LIBS="-ldl $LIBS" + +fi + +fi + +if test x$enable_cap = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for cap_get_proc in -lcap" >&5 +$as_echo_n "checking for cap_get_proc in -lcap... " >&6; } +if ${ac_cv_lib_cap_cap_get_proc+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lcap $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char cap_get_proc (); +int +main () +{ +return cap_get_proc (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_cap_cap_get_proc=yes +else + ac_cv_lib_cap_cap_get_proc=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_cap_cap_get_proc" >&5 +$as_echo "$ac_cv_lib_cap_cap_get_proc" >&6; } +if test "x$ac_cv_lib_cap_cap_get_proc" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBCAP 1 +_ACEOF + + LIBS="-lcap $LIBS" + +fi + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for socket in -lsocket" >&5 +$as_echo_n "checking for socket in -lsocket... " >&6; } +if ${ac_cv_lib_socket_socket+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lsocket $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char socket (); +int +main () +{ +return socket (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_socket_socket=yes +else + ac_cv_lib_socket_socket=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_socket_socket" >&5 +$as_echo "$ac_cv_lib_socket_socket" >&6; } +if test "x$ac_cv_lib_socket_socket" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBSOCKET 1 +_ACEOF + + LIBS="-lsocket $LIBS" + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing gethostbyname2" >&5 +$as_echo_n "checking for library containing gethostbyname2... " >&6; } +if ${ac_cv_search_gethostbyname2+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char gethostbyname2 (); +int +main () +{ +return gethostbyname2 (); + ; + return 0; +} +_ACEOF +for ac_lib in '' bind; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_gethostbyname2=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_gethostbyname2+:} false; then : + break +fi +done +if ${ac_cv_search_gethostbyname2+:} false; then : + +else + ac_cv_search_gethostbyname2=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_gethostbyname2" >&5 +$as_echo "$ac_cv_search_gethostbyname2" >&6; } +ac_res=$ac_cv_search_gethostbyname2 +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + + +case $LIBS in + *-lbind*) + for ac_header in bind/netdb.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "bind/netdb.h" "ac_cv_header_bind_netdb_h" "$ac_includes_default" +if test "x$ac_cv_header_bind_netdb_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_BIND_NETDB_H 1 +_ACEOF + +fi + +done + + ;; +esac + + +if test "x$ac_cv_header_iconv_h" = "xyes"; then + ac_fn_c_check_func "$LINENO" "iconv" "ac_cv_func_iconv" +if test "x$ac_cv_func_iconv" = xyes; then : + ac_found_iconv=yes +else + ac_found_iconv=no +fi + + if test "x$ac_found_iconv" = "xno"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for iconv in -liconv" >&5 +$as_echo_n "checking for iconv in -liconv... " >&6; } +if ${ac_cv_lib_iconv_iconv+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-liconv $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char iconv (); +int +main () +{ +return iconv (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_iconv_iconv=yes +else + ac_cv_lib_iconv_iconv=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_iconv_iconv" >&5 +$as_echo "$ac_cv_lib_iconv_iconv" >&6; } +if test "x$ac_cv_lib_iconv_iconv" = xyes; then : + ac_found_iconv=yes +fi + + if test "x$ac_found_iconv" = "xno"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libiconv in -liconv" >&5 +$as_echo_n "checking for libiconv in -liconv... " >&6; } +if ${ac_cv_lib_iconv_libiconv+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-liconv $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char libiconv (); +int +main () +{ +return libiconv (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_iconv_libiconv=yes +else + ac_cv_lib_iconv_libiconv=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_iconv_libiconv" >&5 +$as_echo "$ac_cv_lib_iconv_libiconv" >&6; } +if test "x$ac_cv_lib_iconv_libiconv" = xyes; then : + ac_found_iconv=yes +fi + + fi + if test "x$ac_found_iconv" != "xno"; then + LIBS="-liconv $LIBS" + fi + else + ac_fn_c_check_decl "$LINENO" "_libiconv_version" "ac_cv_have_decl__libiconv_version" " #include +" +if test "x$ac_cv_have_decl__libiconv_version" = xyes; then : + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for libiconv in -liconv" >&5 +$as_echo_n "checking for libiconv in -liconv... " >&6; } +if ${ac_cv_lib_iconv_libiconv+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-liconv $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char libiconv (); +int +main () +{ +return libiconv (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_iconv_libiconv=yes +else + ac_cv_lib_iconv_libiconv=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_iconv_libiconv" >&5 +$as_echo "$ac_cv_lib_iconv_libiconv" >&6; } +if test "x$ac_cv_lib_iconv_libiconv" = xyes; then : + LIBS="-liconv $LIBS" +fi + +fi + + fi +fi + +if test "x$ac_found_iconv" = xyes; then + +$as_echo "#define HAVE_ICONV 1" >>confdefs.h + + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +int myversion = _libiconv_version + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + $as_echo "#define ICONV_FROM_LIBICONV 1" >>confdefs.h + +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi + +if test "x$ac_found_iconv" = "xyes"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for iconv declaration" >&5 +$as_echo_n "checking for iconv declaration... " >&6; } +if ${ac_cv_iconv_const+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + #include +int +main () +{ +#ifdef __cplusplus + "C" + #endif + #if defined(__STDC__) || defined(__cplusplus) + size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft); + #else + size_t iconv(); + #endif + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_iconv_const= +else + ac_cv_iconv_const=const +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_iconv_const" >&5 +$as_echo "$ac_cv_iconv_const" >&6; } + +cat >>confdefs.h <<_ACEOF +#define ICONV_CONST $ac_cv_iconv_const +_ACEOF + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if an include file defines ospeed" >&5 +$as_echo_n "checking if an include file defines ospeed... " >&6; } +if ${zsh_cv_decl_ospeed_include_defines+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#if HAVE_TERMIOS_H +#include +#endif +#if HAVE_TERMCAP_H +#include +#endif +int +main () +{ +ospeed = 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + zsh_cv_decl_ospeed_include_defines=yes +else + zsh_cv_decl_ospeed_include_defines=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_decl_ospeed_include_defines" >&5 +$as_echo "$zsh_cv_decl_ospeed_include_defines" >&6; } + +if test x$zsh_cv_decl_ospeed_include_defines = xno; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if you must define ospeed" >&5 +$as_echo_n "checking if you must define ospeed... " >&6; } +if ${zsh_cv_decl_ospeed_must_define+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ +extern short ospeed; ospeed = 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + zsh_cv_decl_ospeed_must_define=yes +else + zsh_cv_decl_ospeed_must_define=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_decl_ospeed_must_define" >&5 +$as_echo "$zsh_cv_decl_ospeed_must_define" >&6; } +fi + + + +if test x$zsh_cv_decl_ospeed_include_defines = xyes; then + $as_echo "#define HAVE_OSPEED 1" >>confdefs.h + +elif test x$zsh_cv_decl_ospeed_must_define = xyes; then + $as_echo "#define HAVE_OSPEED 1" >>confdefs.h + + $as_echo "#define MUST_DEFINE_OSPEED 1" >>confdefs.h + +fi + +if test x$gdbm != xno; then + for ac_header in gdbm.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "gdbm.h" "ac_cv_header_gdbm_h" "$ac_includes_default" +if test "x$ac_cv_header_gdbm_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GDBM_H 1 +_ACEOF + +fi + +done + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for gdbm_open in -lgdbm" >&5 +$as_echo_n "checking for gdbm_open in -lgdbm... " >&6; } +if ${ac_cv_lib_gdbm_gdbm_open+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_check_lib_save_LIBS=$LIBS +LIBS="-lgdbm $LIBS" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char gdbm_open (); +int +main () +{ +return gdbm_open (); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + ac_cv_lib_gdbm_gdbm_open=yes +else + ac_cv_lib_gdbm_gdbm_open=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LIBS=$ac_check_lib_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_lib_gdbm_gdbm_open" >&5 +$as_echo "$ac_cv_lib_gdbm_gdbm_open" >&6; } +if test "x$ac_cv_lib_gdbm_gdbm_open" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_LIBGDBM 1 +_ACEOF + + LIBS="-lgdbm $LIBS" + +fi + +fi + +for ac_header in sys/xattr.h +do : + ac_fn_c_check_header_mongrel "$LINENO" "sys/xattr.h" "ac_cv_header_sys_xattr_h" "$ac_includes_default" +if test "x$ac_cv_header_sys_xattr_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_SYS_XATTR_H 1 +_ACEOF + +fi + +done + + + +ac_fn_c_check_type "$LINENO" "pid_t" "ac_cv_type_pid_t" "$ac_includes_default" +if test "x$ac_cv_type_pid_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define pid_t int +_ACEOF + +fi + +ac_fn_c_check_type "$LINENO" "off_t" "ac_cv_type_off_t" "$ac_includes_default" +if test "x$ac_cv_type_off_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define off_t long int +_ACEOF + +fi + +ac_fn_c_check_type "$LINENO" "ino_t" "ac_cv_type_ino_t" "$ac_includes_default" +if test "x$ac_cv_type_ino_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define ino_t unsigned long +_ACEOF + +fi + +ac_fn_c_check_type "$LINENO" "mode_t" "ac_cv_type_mode_t" "$ac_includes_default" +if test "x$ac_cv_type_mode_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define mode_t int +_ACEOF + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for uid_t in sys/types.h" >&5 +$as_echo_n "checking for uid_t in sys/types.h... " >&6; } +if ${ac_cv_type_uid_t+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + +_ACEOF +if (eval "$ac_cpp conftest.$ac_ext") 2>&5 | + $EGREP "uid_t" >/dev/null 2>&1; then : + ac_cv_type_uid_t=yes +else + ac_cv_type_uid_t=no +fi +rm -f conftest* + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_type_uid_t" >&5 +$as_echo "$ac_cv_type_uid_t" >&6; } +if test $ac_cv_type_uid_t = no; then + +$as_echo "#define uid_t int" >>confdefs.h + + +$as_echo "#define gid_t int" >>confdefs.h + +fi + +ac_fn_c_check_type "$LINENO" "size_t" "ac_cv_type_size_t" "$ac_includes_default" +if test "x$ac_cv_type_size_t" = xyes; then : + +else + +cat >>confdefs.h <<_ACEOF +#define size_t unsigned int +_ACEOF + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if long is 64 bits" >&5 +$as_echo_n "checking if long is 64 bits... " >&6; } +if ${zsh_cv_long_is_64_bit+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_long_is_64_bit=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +int main() { return sizeof(long) < 8; } +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_long_is_64_bit=yes +else + zsh_cv_long_is_64_bit=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_long_is_64_bit" >&5 +$as_echo "$zsh_cv_long_is_64_bit" >&6; } + + + + + + + +if test x$zsh_cv_long_is_64_bit = xyes; then + $as_echo "#define LONG_IS_64_BIT 1" >>confdefs.h + +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if off_t is 64 bit" >&5 +$as_echo_n "checking if off_t is 64 bit... " >&6; } +if ${zsh_cv_off_t_is_64_bit+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_off_t_is_64_bit=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include + +main() { return sizeof(off_t) < 8; } + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_off_t_is_64_bit=yes +else + zsh_cv_off_t_is_64_bit=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_off_t_is_64_bit" >&5 +$as_echo "$zsh_cv_off_t_is_64_bit" >&6; } + if test x$zsh_cv_off_t_is_64_bit = xyes; then + $as_echo "#define OFF_T_IS_64_BIT 1" >>confdefs.h + + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if ino_t is 64 bit" >&5 +$as_echo_n "checking if ino_t is 64 bit... " >&6; } +if ${zsh_cv_ino_t_is_64_bit+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_ino_t_is_64_bit=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include + +main() { return sizeof(ino_t) < 8; } + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_ino_t_is_64_bit=yes +else + zsh_cv_ino_t_is_64_bit=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_ino_t_is_64_bit" >&5 +$as_echo "$zsh_cv_ino_t_is_64_bit" >&6; } + if test x$zsh_cv_ino_t_is_64_bit = xyes; then + $as_echo "#define INO_T_IS_64_BIT 1" >>confdefs.h + + fi + + if test x$enable_largefile != xno -o x$zsh_cv_off_t_is_64_bit = xyes \ + -o $zsh_cv_ino_t_is_64_bit = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if compiler has a 64 bit type" >&5 +$as_echo_n "checking if compiler has a 64 bit type... " >&6; } +if ${zsh_cv_64_bit_type+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + if test x != x ; then + zsh_cv_64_bit_type="long long" + else + zsh_cv_64_bit_type=no + fi +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +#include +#endif + +main() +{ + long long foo = 0; + int bar = (int) foo; + return sizeof(long long) != 8; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_64_bit_type="long long" +else + zsh_cv_64_bit_type=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + + if test "$zsh_cv_64_bit_type" = no; then + if test "$cross_compiling" = yes; then : + if test x != x ; then + zsh_cv_64_bit_type="quad_t" + else + zsh_cv_64_bit_type=no + fi +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +#include +#endif + +main() +{ + quad_t foo = 0; + int bar = (int) foo; + return sizeof(quad_t) != 8; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_64_bit_type="quad_t" +else + zsh_cv_64_bit_type=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + + fi + if test "$zsh_cv_64_bit_type" = no; then + if test "$cross_compiling" = yes; then : + if test x != x ; then + zsh_cv_64_bit_type="__int64_t" + else + zsh_cv_64_bit_type=no + fi +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +#include +#endif + +main() +{ + __int64_t foo = 0; + int bar = (int) foo; + return sizeof(__int64_t) != 8; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_64_bit_type="__int64_t" +else + zsh_cv_64_bit_type=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + + fi + if test "$zsh_cv_64_bit_type" = no && + test "$zsh_cv_off_t_is_64_bit" = yes; then + if test "$cross_compiling" = yes; then : + if test x != x ; then + zsh_cv_64_bit_type="off_t" + else + zsh_cv_64_bit_type=no + fi +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +#include +#endif + +main() +{ + off_t foo = 0; + int bar = (int) foo; + return sizeof(off_t) != 8; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_64_bit_type="off_t" +else + zsh_cv_64_bit_type=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_64_bit_type" >&5 +$as_echo "$zsh_cv_64_bit_type" >&6; } + if test "$zsh_cv_64_bit_type" != no; then + cat >>confdefs.h <<_ACEOF +#define ZSH_64_BIT_TYPE $zsh_cv_64_bit_type +_ACEOF + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for a corresponding unsigned 64 bit type" >&5 +$as_echo_n "checking for a corresponding unsigned 64 bit type... " >&6; } +if ${zsh_cv_64_bit_utype+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + if test xforce != x ; then + zsh_cv_64_bit_utype="unsigned $zsh_cv_64_bit_type" + else + zsh_cv_64_bit_utype=no + fi +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +#include +#endif + +main() +{ + unsigned $zsh_cv_64_bit_type foo = 0; + int bar = (int) foo; + return sizeof(unsigned $zsh_cv_64_bit_type) != 8; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_64_bit_utype="unsigned $zsh_cv_64_bit_type" +else + zsh_cv_64_bit_utype=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + + if test "$zsh_cv_64_bit_utype" = no; then + if test "$cross_compiling" = yes; then : + if test x != x ; then + zsh_cv_64_bit_utype="__uint64_t" + else + zsh_cv_64_bit_utype=no + fi +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +#include +#endif + +main() +{ + __uint64_t foo = 0; + int bar = (int) foo; + return sizeof(__uint64_t) != 8; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_64_bit_utype="__uint64_t" +else + zsh_cv_64_bit_utype=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + + fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_64_bit_utype" >&5 +$as_echo "$zsh_cv_64_bit_utype" >&6; } + if test "$zsh_cv_64_bit_utype" != no; then + cat >>confdefs.h <<_ACEOF +#define ZSH_64_BIT_UTYPE $zsh_cv_64_bit_utype +_ACEOF + + fi + fi + fi +fi + + +if test "$zsh_cv_64_bit_type" = "long long"; then + $as_echo "#define ZLONG_IS_LONG_LONG 1" >>confdefs.h + +else + if test "$zsh_cv_64_bit_type" = "long"; then + $as_echo "#define ZLONG_IS_LONG_64 1" >>confdefs.h + + fi +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for %lld printf support" >&5 +$as_echo_n "checking for %lld printf support... " >&6; } +if ${zsh_cv_printf_has_lld+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_printf_has_lld=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +int main(int argc, char **argv) +{ + long long foo = ((long long)0xdead << 40) | 0xf00d; + char buf[80]; + sprintf(buf, "before%lldafter", foo); + if (!strcmp(buf, "before62677660341432333after")) { + return 0; + } + return 1; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_printf_has_lld=yes +else + zsh_cv_printf_has_lld=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_printf_has_lld" >&5 +$as_echo "$zsh_cv_printf_has_lld" >&6; } + +if test x$zsh_cv_printf_has_lld = xyes; then + $as_echo "#define PRINTF_HAS_LLD 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sigset_t" >&5 +$as_echo_n "checking for sigset_t... " >&6; } +if ${zsh_cv_type_sigset_t+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#define _POSIX_C_SOURCE 200809L +#include +#include +int +main () +{ +sigset_t tempsigset; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_type_sigset_t=yes +else + zsh_cv_type_sigset_t=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_type_sigset_t" >&5 +$as_echo "$zsh_cv_type_sigset_t" >&6; } + +if test x$zsh_cv_type_sigset_t = xno; then + $as_echo "#define sigset_t unsigned int" >>confdefs.h + +fi + +ac_fn_c_check_member "$LINENO" "struct stat" "st_atim.tv_nsec" "ac_cv_member_struct_stat_st_atim_tv_nsec" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_atim_tv_nsec" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_ATIM_TV_NSEC 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_atimespec.tv_nsec" "ac_cv_member_struct_stat_st_atimespec_tv_nsec" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_atimespec_tv_nsec" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_ATIMESPEC_TV_NSEC 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_atimensec" "ac_cv_member_struct_stat_st_atimensec" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_atimensec" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_ATIMENSEC 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_mtim.tv_nsec" "ac_cv_member_struct_stat_st_mtim_tv_nsec" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_mtim_tv_nsec" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_MTIM_TV_NSEC 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_mtimespec.tv_nsec" "ac_cv_member_struct_stat_st_mtimespec_tv_nsec" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_mtimespec_tv_nsec" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_MTIMESPEC_TV_NSEC 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_mtimensec" "ac_cv_member_struct_stat_st_mtimensec" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_mtimensec" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_MTIMENSEC 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_ctim.tv_nsec" "ac_cv_member_struct_stat_st_ctim_tv_nsec" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_ctim_tv_nsec" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_CTIM_TV_NSEC 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_ctimespec.tv_nsec" "ac_cv_member_struct_stat_st_ctimespec_tv_nsec" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_ctimespec_tv_nsec" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_CTIMESPEC_TV_NSEC 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct stat" "st_ctimensec" "ac_cv_member_struct_stat_st_ctimensec" "$ac_includes_default" +if test "x$ac_cv_member_struct_stat_st_ctimensec" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_STAT_ST_CTIMENSEC 1 +_ACEOF + + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct timezone" >&5 +$as_echo_n "checking for struct timezone... " >&6; } +if ${zsh_cv_type_exists_struct_timezone+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#define _GNU_SOURCE 1 +#ifdef HAVE_SYS_TIME_H +# include +#endif + +int +main () +{ +struct timezone testvar; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_type_exists_struct_timezone=yes +else + zsh_cv_type_exists_struct_timezone=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_type_exists_struct_timezone" >&5 +$as_echo "$zsh_cv_type_exists_struct_timezone" >&6; } + +if test $zsh_cv_type_exists_struct_timezone = yes; then + $as_echo "#define HAVE_STRUCT_TIMEZONE 1" >>confdefs.h + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct timespec" >&5 +$as_echo_n "checking for struct timespec... " >&6; } +if ${zsh_cv_type_exists_struct_timespec+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#define _GNU_SOURCE 1 +#ifdef HAVE_SYS_TIME_H +# include +#endif + +int +main () +{ +struct timespec testvar; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_type_exists_struct_timespec=yes +else + zsh_cv_type_exists_struct_timespec=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_type_exists_struct_timespec" >&5 +$as_echo "$zsh_cv_type_exists_struct_timespec" >&6; } + +if test $zsh_cv_type_exists_struct_timespec = yes; then + $as_echo "#define HAVE_STRUCT_TIMESPEC 1" >>confdefs.h + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct utmp" >&5 +$as_echo_n "checking for struct utmp... " >&6; } +if ${zsh_cv_type_exists_struct_utmp+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UTMP_H +# include +#endif + +int +main () +{ +struct utmp testvar; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_type_exists_struct_utmp=yes +else + zsh_cv_type_exists_struct_utmp=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_type_exists_struct_utmp" >&5 +$as_echo "$zsh_cv_type_exists_struct_utmp" >&6; } + +if test $zsh_cv_type_exists_struct_utmp = yes; then + $as_echo "#define HAVE_STRUCT_UTMP 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for struct utmpx" >&5 +$as_echo_n "checking for struct utmpx... " >&6; } +if ${zsh_cv_type_exists_struct_utmpx+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UTMPX_H +# include +#endif + +int +main () +{ +struct utmpx testvar; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_type_exists_struct_utmpx=yes +else + zsh_cv_type_exists_struct_utmpx=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_type_exists_struct_utmpx" >&5 +$as_echo "$zsh_cv_type_exists_struct_utmpx" >&6; } + +if test $zsh_cv_type_exists_struct_utmpx = yes; then + $as_echo "#define HAVE_STRUCT_UTMPX 1" >>confdefs.h + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_host in struct utmp" >&5 +$as_echo_n "checking for ut_host in struct utmp... " >&6; } +if ${zsh_cv_struct_member_struct_utmp_ut_host+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UTMP_H +# include +#endif + +int +main () +{ +struct utmp testvar; testvar.ut_host; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_struct_member_struct_utmp_ut_host=yes +else + zsh_cv_struct_member_struct_utmp_ut_host=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_struct_member_struct_utmp_ut_host" >&5 +$as_echo "$zsh_cv_struct_member_struct_utmp_ut_host" >&6; } + +if test $zsh_cv_struct_member_struct_utmp_ut_host = yes; then + $as_echo "#define HAVE_STRUCT_UTMP_UT_HOST 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_host in struct utmpx" >&5 +$as_echo_n "checking for ut_host in struct utmpx... " >&6; } +if ${zsh_cv_struct_member_struct_utmpx_ut_host+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UTMPX_H +# include +#endif + +int +main () +{ +struct utmpx testvar; testvar.ut_host; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_struct_member_struct_utmpx_ut_host=yes +else + zsh_cv_struct_member_struct_utmpx_ut_host=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_struct_member_struct_utmpx_ut_host" >&5 +$as_echo "$zsh_cv_struct_member_struct_utmpx_ut_host" >&6; } + +if test $zsh_cv_struct_member_struct_utmpx_ut_host = yes; then + $as_echo "#define HAVE_STRUCT_UTMPX_UT_HOST 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_xtime in struct utmpx" >&5 +$as_echo_n "checking for ut_xtime in struct utmpx... " >&6; } +if ${zsh_cv_struct_member_struct_utmpx_ut_xtime+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UTMPX_H +# include +#endif + +int +main () +{ +struct utmpx testvar; testvar.ut_xtime; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_struct_member_struct_utmpx_ut_xtime=yes +else + zsh_cv_struct_member_struct_utmpx_ut_xtime=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_struct_member_struct_utmpx_ut_xtime" >&5 +$as_echo "$zsh_cv_struct_member_struct_utmpx_ut_xtime" >&6; } + +if test $zsh_cv_struct_member_struct_utmpx_ut_xtime = yes; then + $as_echo "#define HAVE_STRUCT_UTMPX_UT_XTIME 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ut_tv in struct utmpx" >&5 +$as_echo_n "checking for ut_tv in struct utmpx... " >&6; } +if ${zsh_cv_struct_member_struct_utmpx_ut_tv+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UTMPX_H +# include +#endif + +int +main () +{ +struct utmpx testvar; testvar.ut_tv; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_struct_member_struct_utmpx_ut_tv=yes +else + zsh_cv_struct_member_struct_utmpx_ut_tv=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_struct_member_struct_utmpx_ut_tv" >&5 +$as_echo "$zsh_cv_struct_member_struct_utmpx_ut_tv" >&6; } + +if test $zsh_cv_struct_member_struct_utmpx_ut_tv = yes; then + $as_echo "#define HAVE_STRUCT_UTMPX_UT_TV 1" >>confdefs.h + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for d_ino in struct dirent" >&5 +$as_echo_n "checking for d_ino in struct dirent... " >&6; } +if ${zsh_cv_struct_member_struct_dirent_d_ino+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_DIRENT_H +# include +#endif + +int +main () +{ +struct dirent testvar; testvar.d_ino; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_struct_member_struct_dirent_d_ino=yes +else + zsh_cv_struct_member_struct_dirent_d_ino=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_struct_member_struct_dirent_d_ino" >&5 +$as_echo "$zsh_cv_struct_member_struct_dirent_d_ino" >&6; } + +if test $zsh_cv_struct_member_struct_dirent_d_ino = yes; then + $as_echo "#define HAVE_STRUCT_DIRENT_D_INO 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for d_stat in struct dirent" >&5 +$as_echo_n "checking for d_stat in struct dirent... " >&6; } +if ${zsh_cv_struct_member_struct_dirent_d_stat+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_DIRENT_H +# include +#endif + +int +main () +{ +struct dirent testvar; testvar.d_stat; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_struct_member_struct_dirent_d_stat=yes +else + zsh_cv_struct_member_struct_dirent_d_stat=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_struct_member_struct_dirent_d_stat" >&5 +$as_echo "$zsh_cv_struct_member_struct_dirent_d_stat" >&6; } + +if test $zsh_cv_struct_member_struct_dirent_d_stat = yes; then + $as_echo "#define HAVE_STRUCT_DIRENT_D_STAT 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for d_ino in struct direct" >&5 +$as_echo_n "checking for d_ino in struct direct... " >&6; } +if ${zsh_cv_struct_member_struct_direct_d_ino+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_NDIR_H +# include +#endif +#ifdef HAVE_SYS_DIR_H +# include +#endif +#ifdef HAVE_NDIR_H +# include +#endif + +int +main () +{ +struct direct testvar; testvar.d_ino; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_struct_member_struct_direct_d_ino=yes +else + zsh_cv_struct_member_struct_direct_d_ino=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_struct_member_struct_direct_d_ino" >&5 +$as_echo "$zsh_cv_struct_member_struct_direct_d_ino" >&6; } + +if test $zsh_cv_struct_member_struct_direct_d_ino = yes; then + $as_echo "#define HAVE_STRUCT_DIRECT_D_INO 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for d_stat in struct direct" >&5 +$as_echo_n "checking for d_stat in struct direct... " >&6; } +if ${zsh_cv_struct_member_struct_direct_d_stat+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_NDIR_H +# include +#endif +#ifdef HAVE_SYS_DIR_H +# include +#endif +#ifdef HAVE_NDIR_H +# include +#endif + +int +main () +{ +struct direct testvar; testvar.d_stat; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_struct_member_struct_direct_d_stat=yes +else + zsh_cv_struct_member_struct_direct_d_stat=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_struct_member_struct_direct_d_stat" >&5 +$as_echo "$zsh_cv_struct_member_struct_direct_d_stat" >&6; } + +if test $zsh_cv_struct_member_struct_direct_d_stat = yes; then + $as_echo "#define HAVE_STRUCT_DIRECT_D_STAT 1" >>confdefs.h + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sin6_scope_id in struct sockaddr_in6" >&5 +$as_echo_n "checking for sin6_scope_id in struct sockaddr_in6... " >&6; } +if ${zsh_cv_struct_member_struct_sockaddr_in6_sin6_scope_id+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include + +int +main () +{ +struct sockaddr_in6 testvar; testvar.sin6_scope_id; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_struct_member_struct_sockaddr_in6_sin6_scope_id=yes +else + zsh_cv_struct_member_struct_sockaddr_in6_sin6_scope_id=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_struct_member_struct_sockaddr_in6_sin6_scope_id" >&5 +$as_echo "$zsh_cv_struct_member_struct_sockaddr_in6_sin6_scope_id" >&6; } + +if test $zsh_cv_struct_member_struct_sockaddr_in6_sin6_scope_id = yes; then + $as_echo "#define HAVE_STRUCT_SOCKADDR_IN6_SIN6_SCOPE_ID 1" >>confdefs.h + +fi + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if we need our own h_errno" >&5 +$as_echo_n "checking if we need our own h_errno... " >&6; } +if ${zsh_cv_decl_h_errno_use_local+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ +extern int h_errno; h_errno = 0; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + zsh_cv_decl_h_errno_use_local=no +else + zsh_cv_decl_h_errno_use_local=yes +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_decl_h_errno_use_local" >&5 +$as_echo "$zsh_cv_decl_h_errno_use_local" >&6; } + +if test x$zsh_cv_decl_h_errno_use_local = xyes; then + $as_echo "#define USE_LOCAL_H_ERRNO 1" >>confdefs.h + +fi + + + +for ac_func in strftime strptime mktime timelocal \ + difftime gettimeofday clock_gettime \ + select poll \ + readlink faccessx fchdir ftruncate \ + fstat lstat lchown fchown fchmod \ + fseeko ftello \ + mkfifo _mktemp mkstemp \ + waitpid wait3 \ + sigaction sigblock sighold sigrelse sigsetmask sigprocmask \ + killpg setpgid setpgrp tcsetpgrp tcgetattr nice \ + gethostname gethostbyname2 getipnodebyname \ + inet_aton inet_pton inet_ntop \ + getlogin getpwent getpwnam getpwuid getgrgid getgrnam \ + initgroups nis_list \ + setuid seteuid setreuid setresuid setsid \ + memcpy memmove strstr strerror strtoul \ + getrlimit getrusage \ + setlocale \ + isblank iswblank \ + uname \ + signgam tgamma \ + log2 \ + scalbn \ + putenv getenv setenv unsetenv xw\ + brk sbrk \ + pathconf sysconf \ + tgetent tigetflag tigetnum tigetstr setupterm initscr resize_term \ + getcchar setcchar waddwstr wget_wch win_wch use_default_colors \ + nl_langinfo \ + erand48 open_memstream \ + posix_openpt \ + wctomb iconv \ + isinf isnan \ + grantpt unlockpt ptsname \ + htons ntohs \ + regcomp regexec regerror regfree \ + gdbm_open getxattr \ + realpath canonicalize_file_name \ + symlink getcwd \ + cygwin_conv_path \ + nanosleep \ + srand_deterministic \ + setutxent getutxent endutxent getutent \ + getline +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working strcoll" >&5 +$as_echo_n "checking for working strcoll... " >&6; } +if ${ac_cv_func_strcoll_works+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_strcoll_works=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +return (strcoll ("abc", "def") >= 0 || + strcoll ("ABC", "DEF") >= 0 || + strcoll ("123", "456") >= 0) + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_strcoll_works=yes +else + ac_cv_func_strcoll_works=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_strcoll_works" >&5 +$as_echo "$ac_cv_func_strcoll_works" >&6; } +if test $ac_cv_func_strcoll_works = yes; then + +$as_echo "#define HAVE_STRCOLL 1" >>confdefs.h + +fi + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if realpath accepts NULL" >&5 +$as_echo_n "checking if realpath accepts NULL... " >&6; } +if ${zsh_cv_func_realpath_accepts_null+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_func_realpath_accepts_null=$ac_cv_func_canonicalize_file_name +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include + +int +main () +{ + +exit(!realpath("/", (char*)0)); + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_func_realpath_accepts_null=yes +else + zsh_cv_func_realpath_accepts_null=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_func_realpath_accepts_null" >&5 +$as_echo "$zsh_cv_func_realpath_accepts_null" >&6; } +if test x$zsh_cv_func_realpath_accepts_null = xyes; then + $as_echo "#define REALPATH_ACCEPTS_NULL 1" >>confdefs.h + +fi + +if test x$enable_cap = xyes; then + for ac_func in cap_get_proc +do : + ac_fn_c_check_func "$LINENO" "cap_get_proc" "ac_cv_func_cap_get_proc" +if test "x$ac_cv_func_cap_get_proc" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_CAP_GET_PROC 1 +_ACEOF + +fi +done + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if tgetent accepts NULL" >&5 +$as_echo_n "checking if tgetent accepts NULL... " >&6; } +if ${zsh_cv_func_tgetent_accepts_null+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_func_tgetent_accepts_null=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +main() +{ + char buf[4096]; + int r1 = tgetent(buf, "vt100"); + int r2 = tgetent((char*)0,"vt100"); + if (r1 >= 0 && r1 == r2) { + char tbuf[1024], *u; + u = tbuf; + tgetstr("cl", &u); + creat("conftest.tgetent", 0640); + } + exit((r1 != r2) || r2 == -1); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + if test -f conftest.tgetent; then + zsh_cv_func_tgetent_accepts_null=yes + else + zsh_cv_func_tgetent_accepts_null=no + fi +else + zsh_cv_func_tgetent_accepts_null=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_func_tgetent_accepts_null" >&5 +$as_echo "$zsh_cv_func_tgetent_accepts_null" >&6; } +if test x$zsh_cv_func_tgetent_accepts_null = xyes; then + $as_echo "#define TGETENT_ACCEPTS_NULL 1" >>confdefs.h + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if tgetent returns 0 on success" >&5 +$as_echo_n "checking if tgetent returns 0 on success... " >&6; } +if ${zsh_cv_func_tgetent_zero_success+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_func_tgetent_zero_success=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +main() +{ + char buf[4096]; + int r1 = tgetent(buf, "!@#$%^&*"); + int r2 = tgetent(buf, "vt100"); + if (r1 < 0 && r2 == 0) { + char tbuf[1024], *u; + u = tbuf; + tgetstr("cl", &u); + creat("conftest.tgetent0", 0640); + } + exit(r1 == r2); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + if test -f conftest.tgetent0; then + zsh_cv_func_tgetent_zero_success=yes + else + zsh_cv_func_tgetent_zero_success=no + fi +else + zsh_cv_func_tgetent_zero_success=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_func_tgetent_zero_success" >&5 +$as_echo "$zsh_cv_func_tgetent_zero_success" >&6; } + +if test x$zsh_cv_func_tgetent_zero_success = xyes; then + $as_echo "#define TGETENT_SUCCESS 0" >>confdefs.h + +else + $as_echo "#define TGETENT_SUCCESS 1" >>confdefs.h + +fi + + + + + for ac_header in $ac_header_list +do : + as_ac_Header=`$as_echo "ac_cv_header_$ac_header" | $as_tr_sh` +ac_fn_c_check_header_compile "$LINENO" "$ac_header" "$as_ac_Header" "$ac_includes_default +" +if eval test \"x\$"$as_ac_Header"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_header" | $as_tr_cpp` 1 +_ACEOF + +fi + +done + + + + + + + + +for ac_func in getpagesize +do : + ac_fn_c_check_func "$LINENO" "getpagesize" "ac_cv_func_getpagesize" +if test "x$ac_cv_func_getpagesize" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_GETPAGESIZE 1 +_ACEOF + +fi +done + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for working mmap" >&5 +$as_echo_n "checking for working mmap... " >&6; } +if ${ac_cv_func_mmap_fixed_mapped+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + ac_cv_func_mmap_fixed_mapped=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +/* malloc might have been renamed as rpl_malloc. */ +#undef malloc + +/* Thanks to Mike Haertel and Jim Avera for this test. + Here is a matrix of mmap possibilities: + mmap private not fixed + mmap private fixed at somewhere currently unmapped + mmap private fixed at somewhere already mapped + mmap shared not fixed + mmap shared fixed at somewhere currently unmapped + mmap shared fixed at somewhere already mapped + For private mappings, we should verify that changes cannot be read() + back from the file, nor mmap's back from the file at a different + address. (There have been systems where private was not correctly + implemented like the infamous i386 svr4.0, and systems where the + VM page cache was not coherent with the file system buffer cache + like early versions of FreeBSD and possibly contemporary NetBSD.) + For shared mappings, we should conversely verify that changes get + propagated back to all the places they're supposed to be. + + Grep wants private fixed already mapped. + The main things grep needs to know about mmap are: + * does it exist and is it safe to write into the mmap'd area + * how to use it (BSD variants) */ + +#include +#include + +#if !defined STDC_HEADERS && !defined HAVE_STDLIB_H +char *malloc (); +#endif + +/* This mess was copied from the GNU getpagesize.h. */ +#ifndef HAVE_GETPAGESIZE +# ifdef _SC_PAGESIZE +# define getpagesize() sysconf(_SC_PAGESIZE) +# else /* no _SC_PAGESIZE */ +# ifdef HAVE_SYS_PARAM_H +# include +# ifdef EXEC_PAGESIZE +# define getpagesize() EXEC_PAGESIZE +# else /* no EXEC_PAGESIZE */ +# ifdef NBPG +# define getpagesize() NBPG * CLSIZE +# ifndef CLSIZE +# define CLSIZE 1 +# endif /* no CLSIZE */ +# else /* no NBPG */ +# ifdef NBPC +# define getpagesize() NBPC +# else /* no NBPC */ +# ifdef PAGESIZE +# define getpagesize() PAGESIZE +# endif /* PAGESIZE */ +# endif /* no NBPC */ +# endif /* no NBPG */ +# endif /* no EXEC_PAGESIZE */ +# else /* no HAVE_SYS_PARAM_H */ +# define getpagesize() 8192 /* punt totally */ +# endif /* no HAVE_SYS_PARAM_H */ +# endif /* no _SC_PAGESIZE */ + +#endif /* no HAVE_GETPAGESIZE */ + +int +main () +{ + char *data, *data2, *data3; + const char *cdata2; + int i, pagesize; + int fd, fd2; + + pagesize = getpagesize (); + + /* First, make a file with some known garbage in it. */ + data = (char *) malloc (pagesize); + if (!data) + return 1; + for (i = 0; i < pagesize; ++i) + *(data + i) = rand (); + umask (0); + fd = creat ("conftest.mmap", 0600); + if (fd < 0) + return 2; + if (write (fd, data, pagesize) != pagesize) + return 3; + close (fd); + + /* Next, check that the tail of a page is zero-filled. File must have + non-zero length, otherwise we risk SIGBUS for entire page. */ + fd2 = open ("conftest.txt", O_RDWR | O_CREAT | O_TRUNC, 0600); + if (fd2 < 0) + return 4; + cdata2 = ""; + if (write (fd2, cdata2, 1) != 1) + return 5; + data2 = (char *) mmap (0, pagesize, PROT_READ | PROT_WRITE, MAP_SHARED, fd2, 0L); + if (data2 == MAP_FAILED) + return 6; + for (i = 0; i < pagesize; ++i) + if (*(data2 + i)) + return 7; + close (fd2); + if (munmap (data2, pagesize)) + return 8; + + /* Next, try to mmap the file at a fixed address which already has + something else allocated at it. If we can, also make sure that + we see the same garbage. */ + fd = open ("conftest.mmap", O_RDWR); + if (fd < 0) + return 9; + if (data2 != mmap (data2, pagesize, PROT_READ | PROT_WRITE, + MAP_PRIVATE | MAP_FIXED, fd, 0L)) + return 10; + for (i = 0; i < pagesize; ++i) + if (*(data + i) != *(data2 + i)) + return 11; + + /* Finally, make sure that changes to the mapped area do not + percolate back to the file as seen by read(). (This is a bug on + some variants of i386 svr4.0.) */ + for (i = 0; i < pagesize; ++i) + *(data2 + i) = *(data2 + i) + 1; + data3 = (char *) malloc (pagesize); + if (!data3) + return 12; + if (read (fd, data3, pagesize) != pagesize) + return 13; + for (i = 0; i < pagesize; ++i) + if (*(data + i) != *(data3 + i)) + return 14; + close (fd); + return 0; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + ac_cv_func_mmap_fixed_mapped=yes +else + ac_cv_func_mmap_fixed_mapped=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_mmap_fixed_mapped" >&5 +$as_echo "$ac_cv_func_mmap_fixed_mapped" >&6; } +if test $ac_cv_func_mmap_fixed_mapped = yes; then + +$as_echo "#define HAVE_MMAP 1" >>confdefs.h + +fi +rm -f conftest.mmap conftest.txt + +if test x$ac_cv_func_mmap_fixed_mapped = xyes; then + for ac_func in munmap msync +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + +fi + +if test x$ac_cv_func_setpgrp = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether getpgrp requires zero arguments" >&5 +$as_echo_n "checking whether getpgrp requires zero arguments... " >&6; } +if ${ac_cv_func_getpgrp_void+:} false; then : + $as_echo_n "(cached) " >&6 +else + # Use it with a single arg. +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$ac_includes_default +int +main () +{ +getpgrp (0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_func_getpgrp_void=no +else + ac_cv_func_getpgrp_void=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_func_getpgrp_void" >&5 +$as_echo "$ac_cv_func_getpgrp_void" >&6; } +if test $ac_cv_func_getpgrp_void = yes; then + +$as_echo "#define GETPGRP_VOID 1" >>confdefs.h + +fi + +else + ac_cv_func_getpgrp_void=yes + $as_echo "#define GETPGRP_VOID 1" >>confdefs.h + +fi + +if test x$dynamic = xyes; then + for ac_func in dlopen dlerror dlsym dlclose load loadquery loadbind unload \ + shl_load shl_unload shl_findsym +do : + as_ac_var=`$as_echo "ac_cv_func_$ac_func" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$ac_func" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + cat >>confdefs.h <<_ACEOF +#define `$as_echo "HAVE_$ac_func" | $as_tr_cpp` 1 +_ACEOF + +fi +done + +fi + + +if test x$ac_cv_func_getxattr = xyes && test x$ac_cv_header_sys_xattr_h = xyes +then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if getxattr etc. are Linux-like" >&5 +$as_echo_n "checking if getxattr etc. are Linux-like... " >&6; } +if ${zsh_cv_getxattr_linux+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +int +main () +{ + + (void)listxattr("", 0, 0); + (void)getxattr("", "", 0, 0); + (void)setxattr("", "", "", 0, 0); + (void)removexattr("", ""); + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_getxattr_linux=yes +else + zsh_cv_getxattr_linux=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_getxattr_linux" >&5 +$as_echo "$zsh_cv_getxattr_linux" >&6; } + + if test x$zsh_cv_getxattr_linux != xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if getxattr etc. are MAC-like" >&5 +$as_echo_n "checking if getxattr etc. are MAC-like... " >&6; } +if ${zsh_cv_getxattr_mac+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +#include +int +main () +{ +(void)listxattr("", 0, 0, 0); + (void)getxattr("", "", 0, 0, 0, 0); + (void)setxattr("", "", "", 0, 0, 0); + (void)removexattr("", "", 0); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_getxattr_mac=yes +else + zsh_cv_getxattr_mac=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_getxattr_mac" >&5 +$as_echo "$zsh_cv_getxattr_mac" >&6; } + + if test x$zsh_cv_getxattr_mac = xyes; then + $as_echo "#define XATTR_EXTRA_ARGS 1" >>confdefs.h + + fi + fi +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if getxattr etc. are usable" >&5 +$as_echo_n "checking if getxattr etc. are usable... " >&6; } +if ${zsh_cv_use_xattr+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test x$zsh_cv_getxattr_linux = xyes || test x$zsh_cv_getxattr_mac = xyes +then +zsh_cv_use_xattr=yes +else +zsh_cv_use_xattr=no +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_use_xattr" >&5 +$as_echo "$zsh_cv_use_xattr" >&6; } + + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking what style of signals to use" >&5 +$as_echo_n "checking what style of signals to use... " >&6; } +if test x$ac_cv_func_sigaction = xyes && test x$ac_cv_func_sigprocmask = xyes; then + signals_style=POSIX_SIGNALS + $as_echo "#define POSIX_SIGNALS 1" >>confdefs.h + +elif test x$ac_cv_func_sigblock = xyes && test x$ac_cv_func_sigsetmask = xyes; then + signals_style=BSD_SIGNALS + $as_echo "#define BSD_SIGNALS 1" >>confdefs.h + +elif test x$ac_cv_func_sighold = xyes && test x$ac_cv_func_sigrelse = xyes; then + signals_style=SYSV_SIGNALS + $as_echo "#define SYSV_SIGNALS 1" >>confdefs.h + +else + signals_style=NO_SIGNAL_BLOCKING + $as_echo "#define NO_SIGNAL_BLOCKING 1" >>confdefs.h + +fi +cat >>confdefs.h <<_ACEOF +#define $signals_style 1 +_ACEOF + +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $signals_style" >&5 +$as_echo "$signals_style" >&6; } + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking where signal.h is located" >&5 +$as_echo_n "checking where signal.h is located... " >&6; } +if ${zsh_cv_path_signal_h+:} false; then : + $as_echo_n "(cached) " >&6 +else + echo "#include " > nametmp.c +sigfile_list="`$CPP $CPPFLAGS nametmp.c | +sed -n -e 's/^#line[ ].*\"\(.*\)\"/\1/p' \ + -e 's/^#[ ].*\"\(.*\)\"/\1/p' | +sed 's/\\\\\\\\/\//g' | +$AWK '{ if ($1 ~ /sig/) files[$1] = $1 } + END { for (var in files) print var }'`" +rm -f nametmp.c +if test -z "$sigfile_list"; then + sigfile_list="/usr/include/sys/iso/signal_iso.h +/usr/include/bsd/sys/signal.h +/usr/include/signum.h +/usr/include/asm/signum.h +/usr/include/asm/signal.h +/usr/include/linux/signal.h +/usr/include/sys/signal.h +/usr/include/bits/signum.h +/dev/null" +fi +for SIGNAL_TRY_H in $sigfile_list +do + nsigs=`test -f $SIGNAL_TRY_H && \ + grep '#[ ]*define[ ][ ]*SIG[0-9A-Z]*[ ]*[0-9][0-9]*' $SIGNAL_TRY_H | \ + wc -l | sed 's/ //g'` + if test "x$nsigs" != x && test "$nsigs" -ge 7 + then + SIGNAL_H="$SIGNAL_H $SIGNAL_TRY_H" + fi +done +if test "x$SIGNAL_H" = x; then + as_fn_error $? "SIGNAL MACROS NOT FOUND: please report to developers" "$LINENO" 5 +fi +zsh_cv_path_signal_h="$SIGNAL_H" + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_path_signal_h" >&5 +$as_echo "$zsh_cv_path_signal_h" >&6; } +SIGNAL_H="$zsh_cv_path_signal_h" + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking where error names are located" >&5 +$as_echo_n "checking where error names are located... " >&6; } +if ${zsh_cv_path_errno_h+:} false; then : + $as_echo_n "(cached) " >&6 +else + echo "#include " > nametmp.c +errfile_list="`$CPP $CPPFLAGS nametmp.c | +sed -n -e 's/^#line[ ].*\"\(.*\)\"/\1/p' \ + -e 's/^#[ 0-9].*\"\(.*\)\"/\1/p' | +sed 's/\\\\\\\\/\//g' | +$AWK '{ if ($1 ~ /err/) files[$1] = $1 } + END { for (var in files) print var }'`" +rm -f nametmp.c +for ERRNO_TRY_H in $errfile_list /dev/null +do + nerrs=`test -f $ERRNO_TRY_H && \ + $EGREP '#[ ]*define[ ][ ]*E[0-9A-Z]*[ ]*(_HURD_ERRNO )?\(?[_A-Z0-9]' $ERRNO_TRY_H | \ + wc -l | sed 's/ //g'` + if test "x$nerrs" != x && test "$nerrs" -ge 1 + then + ERRNO_H="$ERRNO_H $ERRNO_TRY_H" + fi +done +if test x"$ERRNO_H" = x; then + as_fn_error $? "ERROR MACROS NOT FOUND: please report to developers" "$LINENO" 5 +fi +zsh_cv_path_errno_h="$ERRNO_H" + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_path_errno_h" >&5 +$as_echo "$zsh_cv_path_errno_h" >&6; } +ERRNO_H="$zsh_cv_path_errno_h" + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking location of curses header" >&5 +$as_echo_n "checking location of curses header... " >&6; } +if ${zsh_cv_path_curses_header+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test x$zsh_cv_ignore_ncurses = xyes; then + if test x$ac_cv_header_curses_h = xyes; then + zsh_cv_path_curses_header=curses.h + else + zsh_cv_path_curses_header=none + fi +elif test x$ac_cv_header_ncursesw_ncurses_h = xyes; then + zsh_cv_path_curses_header=ncursesw/ncurses.h +elif test x$ac_cv_header_ncurses_ncurses_h = xyes; then + zsh_cv_path_curses_header=ncurses/ncurses.h +elif test x$ac_cv_header_ncurses_h = xyes; then + zsh_cv_path_curses_header=ncurses.h +elif test x$ac_cv_header_curses_h = xyes; then + zsh_cv_path_curses_header=curses.h +else + zsh_cv_path_curses_header=none +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_path_curses_header" >&5 +$as_echo "$zsh_cv_path_curses_header" >&6; } + +if test x$zsh_cv_path_curses_header != xnone; then + $as_echo "#define ZSH_HAVE_CURSES_H 1" >>confdefs.h + + ZSH_CURSES_H=$zsh_cv_path_curses_header +else + ZSH_CURSES_H= +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking where curses key definitions are located" >&5 +$as_echo_n "checking where curses key definitions are located... " >&6; } +if ${zsh_cv_path_curses_keys_h+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test x$zsh_cv_path_curses_header = xnone; then + echo >nametmp.c +else + echo "#include <$zsh_cv_path_curses_header>" >nametmp.c +fi + +curses_list="`$CPP $CPPFLAGS nametmp.c | +sed -n -e 's/^#line[ ].*\"\(.*\)\"/\1/p' \ + -e 's/^#[ 0-9].*\"\(.*\)\"/\1/p' | +sed 's/\\\\\\\\/\//g' | +$AWK '{ if ($1 ~ /\.h/) files[$1] = $1 } + END { for (var in files) print var }'`" +rm -f nametmp.c +for CURSES_TRY_H in $curses_list /dev/null +do + nkeys=`test -f $CURSES_TRY_H && \ + $EGREP '#[ ]*define[ ][ ]*KEY_' $CURSES_TRY_H | \ + wc -l | sed 's/ //g'` + if test "x$nkeys" != x && test "$nkeys" -ge 10 + then + CURSES_KEYS_H=$CURSES_TRY_H + break + fi +done +zsh_cv_path_curses_keys_h="$CURSES_KEYS_H" + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_path_curses_keys_h" >&5 +$as_echo "$zsh_cv_path_curses_keys_h" >&6; } +CURSES_KEYS_H="$zsh_cv_path_curses_keys_h" + +for ac_header in ncursesw/term.h +do : + ac_fn_c_check_header_compile "$LINENO" "ncursesw/term.h" "ac_cv_header_ncursesw_term_h" "#include +" +if test "x$ac_cv_header_ncursesw_term_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_NCURSESW_TERM_H 1 +_ACEOF + true +else + true +fi + +done + +for ac_header in ncurses/term.h +do : + ac_fn_c_check_header_compile "$LINENO" "ncurses/term.h" "ac_cv_header_ncurses_term_h" "#include +" +if test "x$ac_cv_header_ncurses_term_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_NCURSES_TERM_H 1 +_ACEOF + true +else + true +fi + +done + +for ac_header in term.h +do : + ac_fn_c_check_header_compile "$LINENO" "term.h" "ac_cv_header_term_h" "#include +" +if test "x$ac_cv_header_term_h" = xyes; then : + cat >>confdefs.h <<_ACEOF +#define HAVE_TERM_H 1 +_ACEOF + true +else + true +fi + +done + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking where term.h is located" >&5 +$as_echo_n "checking where term.h is located... " >&6; } +if ${zsh_cv_path_term_header+:} false; then : + $as_echo_n "(cached) " >&6 +else + case x$zsh_cv_path_curses_header in + xncursesw/*) + if test x$ac_cv_header_ncursesw_term_h = xyes; then + zsh_cv_path_term_header=ncursesw/term.h + fi + ;; + xncurses/*) + if test x$ac_cv_header_ncurses_term_h = xyes; then + zsh_cv_path_term_header=ncurses/term.h + fi + ;; +esac +if test x$zsh_cv_path_term_header = x; then + if test x$ac_cv_header_term_h = xyes; then + zsh_cv_path_term_header=term.h + else + zsh_cv_path_term_header=none + fi +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_path_term_header" >&5 +$as_echo "$zsh_cv_path_term_header" >&6; } + + + + + + + + + + +if test x$zsh_cv_path_term_header != xnone; then + $as_echo "#define ZSH_HAVE_TERM_H 1" >>confdefs.h + + ZSH_TERM_H=$zsh_cv_path_term_header + if test x$zsh_cv_path_curses_header != xnone; then + term_includes="#include <$zsh_cv_path_curses_header> +#include <$zsh_cv_path_term_header>" + else + term_includes="#include <$zsh_cv_path_term_header>" + fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if boolcodes is available" >&5 +$as_echo_n "checking if boolcodes is available... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$term_includes +int +main () +{ +char **test = boolcodes; puts(*test); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + $as_echo "#define HAVE_BOOLCODES 1" >>confdefs.h + boolcodes=yes +else + boolcodes=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $boolcodes" >&5 +$as_echo "$boolcodes" >&6; } + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if numcodes is available" >&5 +$as_echo_n "checking if numcodes is available... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$term_includes +int +main () +{ +char **test = numcodes; puts(*test); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + $as_echo "#define HAVE_NUMCODES 1" >>confdefs.h + numcodes=yes +else + numcodes=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $numcodes" >&5 +$as_echo "$numcodes" >&6; } + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if strcodes is available" >&5 +$as_echo_n "checking if strcodes is available... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$term_includes +int +main () +{ +char **test = strcodes; puts(*test); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + $as_echo "#define HAVE_STRCODES 1" >>confdefs.h + strcodes=yes +else + strcodes=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $strcodes" >&5 +$as_echo "$strcodes" >&6; } + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if boolnames is available" >&5 +$as_echo_n "checking if boolnames is available... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$term_includes +int +main () +{ +char **test = boolnames; puts(*test); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + $as_echo "#define HAVE_BOOLNAMES 1" >>confdefs.h + boolnames=yes +else + boolnames=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $boolnames" >&5 +$as_echo "$boolnames" >&6; } + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if numnames is available" >&5 +$as_echo_n "checking if numnames is available... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$term_includes +int +main () +{ +char **test = numnames; puts(*test); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + $as_echo "#define HAVE_NUMNAMES 1" >>confdefs.h + numnames=yes +else + numnames=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $numnames" >&5 +$as_echo "$numnames" >&6; } + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if strnames is available" >&5 +$as_echo_n "checking if strnames is available... " >&6; } + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$term_includes +int +main () +{ +char **test = strnames; puts(*test); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + $as_echo "#define HAVE_STRNAMES 1" >>confdefs.h + strnames=yes +else + strnames=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $strnames" >&5 +$as_echo "$strnames" >&6; } + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if tgoto prototype is missing" >&5 +$as_echo_n "checking if tgoto prototype is missing... " >&6; } + tgoto_includes="$term_includes +/* guaranteed to clash with any valid tgoto prototype */ +extern void tgoto(int **stuff, float **more_stuff);" + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$tgoto_includes +int +main () +{ +int *stuff; float *more_stuff; tgoto(&stuff, &more_stuff); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + $as_echo "#define TGOTO_PROTO_MISSING 1" >>confdefs.h + tgotoprotomissing=yes +else + tgotoprotomissing=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext + { $as_echo "$as_me:${as_lineno-$LINENO}: result: $tgotoprotomissing" >&5 +$as_echo "$tgotoprotomissing" >&6; } +else + ZSH_TERM_H= +fi + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking where the RLIMIT macros are located" >&5 +$as_echo_n "checking where the RLIMIT macros are located... " >&6; } +if ${zsh_cv_path_rlimit_h+:} false; then : + $as_echo_n "(cached) " >&6 +else + echo "#include " >restmp.c +resourcefile_list="`$CPP $CPPFLAGS restmp.c | +sed -n -e 's/^#line[ ].*\"\(.*\)\"/\1/p' \ + -e 's/^#[ ].*\"\(.*\)\"/\1/p' | +sed 's/\\\\\\\\/\//g' | +$AWK '{ if ($1 ~ /resource/) files[$1] = $1 } + END { for (var in files) print var }'`" +rm -f restmp.c +if test -z "$resourcefile_list"; then + resourcefile_list="/usr/include/bsd/sys/resource.h +/usr/include/asm/resource.h +/usr/include/linux/resource.h +/usr/include/sys/resource.h +/usr/include/bits/resource.h +/usr/include/resourcebits.h" +fi +for RESOURCE_H in $resourcefile_list /dev/null; +do + test -f $RESOURCE_H && \ + grep '#[ ]*define[ ][ ]*RLIMIT_[A-Z]*[ ]*[0-9A-Z][0-9]*' $RESOURCE_H > /dev/null && \ + break +done +zsh_cv_path_rlimit_h=$RESOURCE_H +if test x$RESOURCE_H = x"/dev/null" && test x$ac_cv_func_getrlimit = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: RLIMIT MACROS NOT FOUND: please report to developers" >&5 +$as_echo "$as_me: WARNING: RLIMIT MACROS NOT FOUND: please report to developers" >&2;} +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_path_rlimit_h" >&5 +$as_echo "$zsh_cv_path_rlimit_h" >&6; } +RLIMITS_INC_H=$zsh_cv_path_rlimit_h +if test "$RLIMITS_INC_H" = "/dev/null"; then + RLIMITS_INC_H='' +fi + + + + + +DEFAULT_RLIM_T=long +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if rlim_t is longer than a long" >&5 +$as_echo_n "checking if rlim_t is longer than a long... " >&6; } +if ${zsh_cv_rlim_t_is_longer+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_rlim_t_is_longer=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +main(){struct rlimit r;exit(sizeof(r.rlim_cur) <= sizeof(long));} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_rlim_t_is_longer=yes +else + zsh_cv_rlim_t_is_longer=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_rlim_t_is_longer" >&5 +$as_echo "$zsh_cv_rlim_t_is_longer" >&6; } +if test x$zsh_cv_rlim_t_is_longer = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if rlim_t is a quad" >&5 +$as_echo_n "checking if rlim_t is a quad... " >&6; } +if ${zsh_cv_rlim_t_is_quad_t+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_rlim_t_is_quad_t=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +#include +main() { + struct rlimit r; + char buf[20]; + r.rlim_cur = 0; + sprintf(buf, "%qd", r.rlim_cur); + exit(strcmp(buf, "0")); +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_rlim_t_is_quad_t=yes +else + zsh_cv_rlim_t_is_quad_t=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_rlim_t_is_quad_t" >&5 +$as_echo "$zsh_cv_rlim_t_is_quad_t" >&6; } + if test x$zsh_cv_rlim_t_is_quad_t = xyes; then + $as_echo "#define RLIM_T_IS_QUAD_T 1" >>confdefs.h + + DEFAULT_RLIM_T=quad_t + else + $as_echo "#define RLIM_T_IS_LONG_LONG 1" >>confdefs.h + + DEFAULT_RLIM_T='long long' + fi +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the rlim_t is unsigned" >&5 +$as_echo_n "checking if the rlim_t is unsigned... " >&6; } +if ${zsh_cv_type_rlim_t_is_unsigned+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_type_rlim_t_is_unsigned=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include + main(){struct rlimit r;r.rlim_cur=-1;exit(r.rlim_cur<0);} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_type_rlim_t_is_unsigned=yes +else + zsh_cv_type_rlim_t_is_unsigned=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_type_rlim_t_is_unsigned" >&5 +$as_echo "$zsh_cv_type_rlim_t_is_unsigned" >&6; } + if test x$zsh_cv_type_rlim_t_is_unsigned = xyes; then + $as_echo "#define RLIM_T_IS_UNSIGNED 1" >>confdefs.h + + DEFAULT_RLIM_T="unsigned $DEFAULT_RLIM_T" + fi +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for rlim_t" >&5 +$as_echo_n "checking for rlim_t... " >&6; } +if ${zsh_cv_type_rlim_t+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +rlim_t l; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_type_rlim_t=yes +else + zsh_cv_type_rlim_t=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_type_rlim_t" >&5 +$as_echo "$zsh_cv_type_rlim_t" >&6; } +if test x$zsh_cv_type_rlim_t = xno; then + cat >>confdefs.h <<_ACEOF +#define rlim_t $DEFAULT_RLIM_T +_ACEOF + +fi + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_AIO_MEM" >&5 +$as_echo_n "checking for limit RLIMIT_AIO_MEM... " >&6; } +if ${zsh_cv_have_RLIMIT_AIO_MEM+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_AIO_MEM + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_AIO_MEM=yes +else + zsh_cv_have_RLIMIT_AIO_MEM=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_AIO_MEM" >&5 +$as_echo "$zsh_cv_have_RLIMIT_AIO_MEM" >&6; } + +if test $zsh_cv_have_RLIMIT_AIO_MEM = yes; then + $as_echo "#define HAVE_RLIMIT_AIO_MEM 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_AIO_OPS" >&5 +$as_echo_n "checking for limit RLIMIT_AIO_OPS... " >&6; } +if ${zsh_cv_have_RLIMIT_AIO_OPS+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_AIO_OPS + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_AIO_OPS=yes +else + zsh_cv_have_RLIMIT_AIO_OPS=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_AIO_OPS" >&5 +$as_echo "$zsh_cv_have_RLIMIT_AIO_OPS" >&6; } + +if test $zsh_cv_have_RLIMIT_AIO_OPS = yes; then + $as_echo "#define HAVE_RLIMIT_AIO_OPS 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_AS" >&5 +$as_echo_n "checking for limit RLIMIT_AS... " >&6; } +if ${zsh_cv_have_RLIMIT_AS+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_AS + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_AS=yes +else + zsh_cv_have_RLIMIT_AS=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_AS" >&5 +$as_echo "$zsh_cv_have_RLIMIT_AS" >&6; } + +if test $zsh_cv_have_RLIMIT_AS = yes; then + $as_echo "#define HAVE_RLIMIT_AS 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_LOCKS" >&5 +$as_echo_n "checking for limit RLIMIT_LOCKS... " >&6; } +if ${zsh_cv_have_RLIMIT_LOCKS+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_LOCKS + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_LOCKS=yes +else + zsh_cv_have_RLIMIT_LOCKS=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_LOCKS" >&5 +$as_echo "$zsh_cv_have_RLIMIT_LOCKS" >&6; } + +if test $zsh_cv_have_RLIMIT_LOCKS = yes; then + $as_echo "#define HAVE_RLIMIT_LOCKS 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_MEMLOCK" >&5 +$as_echo_n "checking for limit RLIMIT_MEMLOCK... " >&6; } +if ${zsh_cv_have_RLIMIT_MEMLOCK+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_MEMLOCK + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_MEMLOCK=yes +else + zsh_cv_have_RLIMIT_MEMLOCK=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_MEMLOCK" >&5 +$as_echo "$zsh_cv_have_RLIMIT_MEMLOCK" >&6; } + +if test $zsh_cv_have_RLIMIT_MEMLOCK = yes; then + $as_echo "#define HAVE_RLIMIT_MEMLOCK 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_NPROC" >&5 +$as_echo_n "checking for limit RLIMIT_NPROC... " >&6; } +if ${zsh_cv_have_RLIMIT_NPROC+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_NPROC + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_NPROC=yes +else + zsh_cv_have_RLIMIT_NPROC=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_NPROC" >&5 +$as_echo "$zsh_cv_have_RLIMIT_NPROC" >&6; } + +if test $zsh_cv_have_RLIMIT_NPROC = yes; then + $as_echo "#define HAVE_RLIMIT_NPROC 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_NTHR" >&5 +$as_echo_n "checking for limit RLIMIT_NTHR... " >&6; } +if ${zsh_cv_have_RLIMIT_NTHR+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_NTHR + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_NTHR=yes +else + zsh_cv_have_RLIMIT_NTHR=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_NTHR" >&5 +$as_echo "$zsh_cv_have_RLIMIT_NTHR" >&6; } + +if test $zsh_cv_have_RLIMIT_NTHR = yes; then + $as_echo "#define HAVE_RLIMIT_NTHR 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_NOFILE" >&5 +$as_echo_n "checking for limit RLIMIT_NOFILE... " >&6; } +if ${zsh_cv_have_RLIMIT_NOFILE+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_NOFILE + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_NOFILE=yes +else + zsh_cv_have_RLIMIT_NOFILE=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_NOFILE" >&5 +$as_echo "$zsh_cv_have_RLIMIT_NOFILE" >&6; } + +if test $zsh_cv_have_RLIMIT_NOFILE = yes; then + $as_echo "#define HAVE_RLIMIT_NOFILE 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_PTHREAD" >&5 +$as_echo_n "checking for limit RLIMIT_PTHREAD... " >&6; } +if ${zsh_cv_have_RLIMIT_PTHREAD+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_PTHREAD + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_PTHREAD=yes +else + zsh_cv_have_RLIMIT_PTHREAD=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_PTHREAD" >&5 +$as_echo "$zsh_cv_have_RLIMIT_PTHREAD" >&6; } + +if test $zsh_cv_have_RLIMIT_PTHREAD = yes; then + $as_echo "#define HAVE_RLIMIT_PTHREAD 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_RSS" >&5 +$as_echo_n "checking for limit RLIMIT_RSS... " >&6; } +if ${zsh_cv_have_RLIMIT_RSS+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_RSS + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_RSS=yes +else + zsh_cv_have_RLIMIT_RSS=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_RSS" >&5 +$as_echo "$zsh_cv_have_RLIMIT_RSS" >&6; } + +if test $zsh_cv_have_RLIMIT_RSS = yes; then + $as_echo "#define HAVE_RLIMIT_RSS 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_SBSIZE" >&5 +$as_echo_n "checking for limit RLIMIT_SBSIZE... " >&6; } +if ${zsh_cv_have_RLIMIT_SBSIZE+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_SBSIZE + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_SBSIZE=yes +else + zsh_cv_have_RLIMIT_SBSIZE=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_SBSIZE" >&5 +$as_echo "$zsh_cv_have_RLIMIT_SBSIZE" >&6; } + +if test $zsh_cv_have_RLIMIT_SBSIZE = yes; then + $as_echo "#define HAVE_RLIMIT_SBSIZE 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_TCACHE" >&5 +$as_echo_n "checking for limit RLIMIT_TCACHE... " >&6; } +if ${zsh_cv_have_RLIMIT_TCACHE+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_TCACHE + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_TCACHE=yes +else + zsh_cv_have_RLIMIT_TCACHE=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_TCACHE" >&5 +$as_echo "$zsh_cv_have_RLIMIT_TCACHE" >&6; } + +if test $zsh_cv_have_RLIMIT_TCACHE = yes; then + $as_echo "#define HAVE_RLIMIT_TCACHE 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_VMEM" >&5 +$as_echo_n "checking for limit RLIMIT_VMEM... " >&6; } +if ${zsh_cv_have_RLIMIT_VMEM+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_VMEM + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_VMEM=yes +else + zsh_cv_have_RLIMIT_VMEM=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_VMEM" >&5 +$as_echo "$zsh_cv_have_RLIMIT_VMEM" >&6; } + +if test $zsh_cv_have_RLIMIT_VMEM = yes; then + $as_echo "#define HAVE_RLIMIT_VMEM 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_SIGPENDING" >&5 +$as_echo_n "checking for limit RLIMIT_SIGPENDING... " >&6; } +if ${zsh_cv_have_RLIMIT_SIGPENDING+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_SIGPENDING + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_SIGPENDING=yes +else + zsh_cv_have_RLIMIT_SIGPENDING=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_SIGPENDING" >&5 +$as_echo "$zsh_cv_have_RLIMIT_SIGPENDING" >&6; } + +if test $zsh_cv_have_RLIMIT_SIGPENDING = yes; then + $as_echo "#define HAVE_RLIMIT_SIGPENDING 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_MSGQUEUE" >&5 +$as_echo_n "checking for limit RLIMIT_MSGQUEUE... " >&6; } +if ${zsh_cv_have_RLIMIT_MSGQUEUE+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_MSGQUEUE + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_MSGQUEUE=yes +else + zsh_cv_have_RLIMIT_MSGQUEUE=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_MSGQUEUE" >&5 +$as_echo "$zsh_cv_have_RLIMIT_MSGQUEUE" >&6; } + +if test $zsh_cv_have_RLIMIT_MSGQUEUE = yes; then + $as_echo "#define HAVE_RLIMIT_MSGQUEUE 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_NICE" >&5 +$as_echo_n "checking for limit RLIMIT_NICE... " >&6; } +if ${zsh_cv_have_RLIMIT_NICE+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_NICE + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_NICE=yes +else + zsh_cv_have_RLIMIT_NICE=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_NICE" >&5 +$as_echo "$zsh_cv_have_RLIMIT_NICE" >&6; } + +if test $zsh_cv_have_RLIMIT_NICE = yes; then + $as_echo "#define HAVE_RLIMIT_NICE 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_RTPRIO" >&5 +$as_echo_n "checking for limit RLIMIT_RTPRIO... " >&6; } +if ${zsh_cv_have_RLIMIT_RTPRIO+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_RTPRIO + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_RTPRIO=yes +else + zsh_cv_have_RLIMIT_RTPRIO=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_RTPRIO" >&5 +$as_echo "$zsh_cv_have_RLIMIT_RTPRIO" >&6; } + +if test $zsh_cv_have_RLIMIT_RTPRIO = yes; then + $as_echo "#define HAVE_RLIMIT_RTPRIO 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_POSIXLOCKS" >&5 +$as_echo_n "checking for limit RLIMIT_POSIXLOCKS... " >&6; } +if ${zsh_cv_have_RLIMIT_POSIXLOCKS+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_POSIXLOCKS + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_POSIXLOCKS=yes +else + zsh_cv_have_RLIMIT_POSIXLOCKS=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_POSIXLOCKS" >&5 +$as_echo "$zsh_cv_have_RLIMIT_POSIXLOCKS" >&6; } + +if test $zsh_cv_have_RLIMIT_POSIXLOCKS = yes; then + $as_echo "#define HAVE_RLIMIT_POSIXLOCKS 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_NPTS" >&5 +$as_echo_n "checking for limit RLIMIT_NPTS... " >&6; } +if ${zsh_cv_have_RLIMIT_NPTS+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_NPTS + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_NPTS=yes +else + zsh_cv_have_RLIMIT_NPTS=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_NPTS" >&5 +$as_echo "$zsh_cv_have_RLIMIT_NPTS" >&6; } + +if test $zsh_cv_have_RLIMIT_NPTS = yes; then + $as_echo "#define HAVE_RLIMIT_NPTS 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_SWAP" >&5 +$as_echo_n "checking for limit RLIMIT_SWAP... " >&6; } +if ${zsh_cv_have_RLIMIT_SWAP+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_SWAP + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_SWAP=yes +else + zsh_cv_have_RLIMIT_SWAP=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_SWAP" >&5 +$as_echo "$zsh_cv_have_RLIMIT_SWAP" >&6; } + +if test $zsh_cv_have_RLIMIT_SWAP = yes; then + $as_echo "#define HAVE_RLIMIT_SWAP 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for limit RLIMIT_KQUEUES" >&5 +$as_echo_n "checking for limit RLIMIT_KQUEUES... " >&6; } +if ${zsh_cv_have_RLIMIT_KQUEUES+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int +main () +{ +RLIMIT_KQUEUES + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_have_RLIMIT_KQUEUES=yes +else + zsh_cv_have_RLIMIT_KQUEUES=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_have_RLIMIT_KQUEUES" >&5 +$as_echo "$zsh_cv_have_RLIMIT_KQUEUES" >&6; } + +if test $zsh_cv_have_RLIMIT_KQUEUES = yes; then + $as_echo "#define HAVE_RLIMIT_KQUEUES 1" >>confdefs.h + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if RLIMIT_VMEM and RLIMIT_RSS are the same" >&5 +$as_echo_n "checking if RLIMIT_VMEM and RLIMIT_RSS are the same... " >&6; } +if ${zsh_cv_rlimit_vmem_is_rss+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_rlimit_vmem_is_rss=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int main() +{ +int ret = 1; +#if defined(HAVE_RLIMIT_VMEM) && defined(HAVE_RLIMIT_RSS) +if (RLIMIT_RSS == RLIMIT_VMEM) ret = 0; +#endif +return ret; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_rlimit_vmem_is_rss=yes +else + zsh_cv_rlimit_vmem_is_rss=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_rlimit_vmem_is_rss" >&5 +$as_echo "$zsh_cv_rlimit_vmem_is_rss" >&6; } + +if test x$zsh_cv_rlimit_vmem_is_rss = xyes; then + $as_echo "#define RLIMIT_VMEM_IS_RSS 1" >>confdefs.h + +fi + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if RLIMIT_VMEM and RLIMIT_AS are the same" >&5 +$as_echo_n "checking if RLIMIT_VMEM and RLIMIT_AS are the same... " >&6; } +if ${zsh_cv_rlimit_vmem_is_as+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_rlimit_vmem_is_as=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int main() +{ +int ret = 1; +#if defined(HAVE_RLIMIT_VMEM) && defined(HAVE_RLIMIT_AS) +if (RLIMIT_AS == RLIMIT_VMEM) ret = 0; +#endif +return ret; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_rlimit_vmem_is_as=yes +else + zsh_cv_rlimit_vmem_is_as=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_rlimit_vmem_is_as" >&5 +$as_echo "$zsh_cv_rlimit_vmem_is_as" >&6; } + +if test x$zsh_cv_rlimit_vmem_is_as = xyes; then + $as_echo "#define RLIMIT_VMEM_IS_AS 1" >>confdefs.h + +fi + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if RLIMIT_RSS and RLIMIT_AS are the same" >&5 +$as_echo_n "checking if RLIMIT_RSS and RLIMIT_AS are the same... " >&6; } +if ${zsh_cv_rlimit_rss_is_as+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_rlimit_rss_is_as=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int main() +{ +int ret = 1; +#if defined(HAVE_RLIMIT_RSS) && defined(HAVE_RLIMIT_AS) +if (RLIMIT_AS == RLIMIT_RSS) ret = 0; +#endif +return ret; +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_rlimit_rss_is_as=yes +else + zsh_cv_rlimit_rss_is_as=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_rlimit_rss_is_as" >&5 +$as_echo "$zsh_cv_rlimit_rss_is_as" >&6; } + +if test x$zsh_cv_rlimit_rss_is_as = xyes; then + $as_echo "#define RLIMIT_RSS_IS_AS 1" >>confdefs.h + +fi + + +if test x$ac_cv_func_getrusage = xyes; then + ac_fn_c_check_member "$LINENO" "struct rusage" "ru_maxrss" "ac_cv_member_struct_rusage_ru_maxrss" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_maxrss" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_MAXRSS 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_ixrss" "ac_cv_member_struct_rusage_ru_ixrss" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_ixrss" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_IXRSS 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_idrss" "ac_cv_member_struct_rusage_ru_idrss" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_idrss" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_IDRSS 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_isrss" "ac_cv_member_struct_rusage_ru_isrss" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_isrss" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_ISRSS 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_minflt" "ac_cv_member_struct_rusage_ru_minflt" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_minflt" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_MINFLT 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_majflt" "ac_cv_member_struct_rusage_ru_majflt" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_majflt" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_MAJFLT 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_nswap" "ac_cv_member_struct_rusage_ru_nswap" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_nswap" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_NSWAP 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_inblock" "ac_cv_member_struct_rusage_ru_inblock" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_inblock" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_INBLOCK 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_oublock" "ac_cv_member_struct_rusage_ru_oublock" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_oublock" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_OUBLOCK 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_msgsnd" "ac_cv_member_struct_rusage_ru_msgsnd" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_msgsnd" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_MSGSND 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_msgrcv" "ac_cv_member_struct_rusage_ru_msgrcv" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_msgrcv" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_MSGRCV 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_nsignals" "ac_cv_member_struct_rusage_ru_nsignals" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_nsignals" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_NSIGNALS 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_nvcsw" "ac_cv_member_struct_rusage_ru_nvcsw" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_nvcsw" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_NVCSW 1 +_ACEOF + + +fi +ac_fn_c_check_member "$LINENO" "struct rusage" "ru_nivcsw" "ac_cv_member_struct_rusage_ru_nivcsw" "#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +" +if test "x$ac_cv_member_struct_rusage_ru_nivcsw" = xyes; then : + +cat >>confdefs.h <<_ACEOF +#define HAVE_STRUCT_RUSAGE_RU_NIVCSW 1 +_ACEOF + + +fi + +fi + + +if ${zsh_cv_cs_path+:} false; then : + $as_echo_n "(cached) " >&6 +else + if getconf _CS_PATH >/dev/null 2>&1; then + zsh_cv_cs_path=`getconf _CS_PATH` +elif getconf CS_PATH >/dev/null 2>&1; then + zsh_cv_cs_path=`getconf CS_PATH` +elif getconf PATH >/dev/null 2>&1; then + zsh_cv_cs_path=`getconf PATH` +else + zsh_cv_cs_path="/bin:/usr/bin" +fi +fi + + +cat >>confdefs.h <<_ACEOF +#define DEFAULT_PATH "$zsh_cv_cs_path" +_ACEOF + + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for /dev/fd filesystem" >&5 +$as_echo_n "checking for /dev/fd filesystem... " >&6; } +if ${zsh_cv_sys_path_dev_fd+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$host_os" = cygwin; then +zsh_cv_sys_path_dev_fd=no +else +for zsh_cv_sys_path_dev_fd in /proc/self/fd /dev/fd no; do + test x`echo ok|(exec 3<&0; cat $zsh_cv_sys_path_dev_fd/3 2>/dev/null;)` = xok && break + done +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_path_dev_fd" >&5 +$as_echo "$zsh_cv_sys_path_dev_fd" >&6; } +if test x$zsh_cv_sys_path_dev_fd != xno; then + cat >>confdefs.h <<_ACEOF +#define PATH_DEV_FD "$zsh_cv_sys_path_dev_fd" +_ACEOF + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for RFS superroot directory" >&5 +$as_echo_n "checking for RFS superroot directory... " >&6; } +if ${zsh_cv_sys_superroot+:} false; then : + $as_echo_n "(cached) " >&6 +else + test -d /../.LOCALROOT && zsh_cv_sys_superroot=yes || zsh_cv_sys_superroot=no +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_superroot" >&5 +$as_echo "$zsh_cv_sys_superroot" >&6; } + +if test x$zsh_cv_sys_superroot = xyes; then + $as_echo "#define HAVE_SUPERROOT 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether we should use the native getcwd" >&5 +$as_echo_n "checking whether we should use the native getcwd... " >&6; } +if ${zsh_cv_use_getcwd+:} false; then : + $as_echo_n "(cached) " >&6 +else + case "${host_cpu}-${host_vendor}-${host_os}" in + *QNX*) zsh_cv_use_getcwd=yes ;; + *) zsh_cv_use_getcwd=no ;; + esac +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_use_getcwd" >&5 +$as_echo "$zsh_cv_use_getcwd" >&6; } + +if test x$zsh_cv_use_getcwd = xyes; then + $as_echo "#define USE_GETCWD 1" >>confdefs.h + +fi + + +if test x$ac_cv_func_getcwd = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether getcwd calls malloc to allocate memory" >&5 +$as_echo_n "checking whether getcwd calls malloc to allocate memory... " >&6; } +if ${zsh_cv_getcwd_malloc+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_getcwd_malloc=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include +int main() { + char buf[1024], *ptr1, *ptr2; + ptr1 = getcwd(buf, 1024); + ptr2 = getcwd(NULL, 0); + if (ptr1 && ptr2 && !strcmp(ptr1, ptr2)) { + return 0; + } + return 1; +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_getcwd_malloc=yes +else + zsh_cv_getcwd_malloc=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_getcwd_malloc" >&5 +$as_echo "$zsh_cv_getcwd_malloc" >&6; } + if test x$zsh_cv_getcwd_malloc = xyes; then + $as_echo "#define GETCWD_CALLS_MALLOC 1" >>confdefs.h + + fi +fi + + +ac_fn_c_check_func "$LINENO" "setproctitle" "ac_cv_func_setproctitle" +if test "x$ac_cv_func_setproctitle" = xyes; then : + $as_echo "#define HAVE_SETPROCTITLE 1" >>confdefs.h + +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing setproctitle" >&5 +$as_echo_n "checking for library containing setproctitle... " >&6; } +if ${ac_cv_search_setproctitle+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char setproctitle (); +int +main () +{ +return setproctitle (); + ; + return 0; +} +_ACEOF +for ac_lib in '' util; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_setproctitle=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_setproctitle+:} false; then : + break +fi +done +if ${ac_cv_search_setproctitle+:} false; then : + +else + ac_cv_search_setproctitle=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_setproctitle" >&5 +$as_echo "$ac_cv_search_setproctitle" >&6; } +ac_res=$ac_cv_search_setproctitle +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + $as_echo "#define HAVE_SETPROCTITLE 1" >>confdefs.h + +fi + +fi + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for NIS" >&5 +$as_echo_n "checking for NIS... " >&6; } +if ${zsh_cv_sys_nis+:} false; then : + $as_echo_n "(cached) " >&6 +else + test -f /usr/bin/ypcat && /usr/bin/ypcat passwd.byname > /dev/null 2>&1 && \ +zsh_cv_sys_nis=yes || zsh_cv_sys_nis=no +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_nis" >&5 +$as_echo "$zsh_cv_sys_nis" >&6; } +if test x$zsh_cv_sys_nis = xyes; then + $as_echo "#define HAVE_NIS 1" >>confdefs.h + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for library containing yp_all" >&5 +$as_echo_n "checking for library containing yp_all... " >&6; } +if ${ac_cv_search_yp_all+:} false; then : + $as_echo_n "(cached) " >&6 +else + ac_func_search_save_LIBS=$LIBS +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +/* Override any GCC internal prototype to avoid an error. + Use char because int might match the return type of a GCC + builtin and then its argument prototype would still apply. */ +#ifdef __cplusplus +extern "C" +#endif +char yp_all (); +int +main () +{ +return yp_all (); + ; + return 0; +} +_ACEOF +for ac_lib in '' nsl; do + if test -z "$ac_lib"; then + ac_res="none required" + else + ac_res=-l$ac_lib + LIBS="-l$ac_lib $ac_func_search_save_LIBS" + fi + if ac_fn_c_try_link "$LINENO"; then : + ac_cv_search_yp_all=$ac_res +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext + if ${ac_cv_search_yp_all+:} false; then : + break +fi +done +if ${ac_cv_search_yp_all+:} false; then : + +else + ac_cv_search_yp_all=no +fi +rm conftest.$ac_ext +LIBS=$ac_func_search_save_LIBS +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_search_yp_all" >&5 +$as_echo "$ac_cv_search_yp_all" >&6; } +ac_res=$ac_cv_search_yp_all +if test "$ac_res" != no; then : + test "$ac_res" = "none required" || LIBS="$ac_res $LIBS" + +fi + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for NIS+" >&5 +$as_echo_n "checking for NIS+... " >&6; } +if ${zsh_cv_sys_nis_plus+:} false; then : + $as_echo_n "(cached) " >&6 +else + test x$ac_cv_func_nis_list = xyes && test -f /usr/bin/nisls && \ + /usr/bin/nisls > /dev/null 2>&1 && \ +zsh_cv_sys_nis_plus=yes || zsh_cv_sys_nis_plus=no +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_nis_plus" >&5 +$as_echo "$zsh_cv_sys_nis_plus" >&6; } +if test x$zsh_cv_sys_nis_plus = xyes; then + $as_echo "#define HAVE_NIS_PLUS 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for utmp file" >&5 +$as_echo_n "checking for utmp file... " >&6; } +if ${zsh_cv_path_utmp+:} false; then : + $as_echo_n "(cached) " >&6 +else + for dir in /etc /usr/etc /var/adm /usr/adm /var/run /var/log ./conftest; do + zsh_cv_path_utmp=${dir}/utmp + test -f $zsh_cv_path_utmp && break + zsh_cv_path_utmp=no +done + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_path_utmp" >&5 +$as_echo "$zsh_cv_path_utmp" >&6; } + +if test $zsh_cv_path_utmp != no; then + cat >>confdefs.h <<_ACEOF +#define PATH_UTMP_FILE "$zsh_cv_path_utmp" +_ACEOF + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for wtmp file" >&5 +$as_echo_n "checking for wtmp file... " >&6; } +if ${zsh_cv_path_wtmp+:} false; then : + $as_echo_n "(cached) " >&6 +else + for dir in /etc /usr/etc /var/adm /usr/adm /var/run /var/log ./conftest; do + zsh_cv_path_wtmp=${dir}/wtmp + test -f $zsh_cv_path_wtmp && break + zsh_cv_path_wtmp=no +done + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_path_wtmp" >&5 +$as_echo "$zsh_cv_path_wtmp" >&6; } + +if test $zsh_cv_path_wtmp != no; then + cat >>confdefs.h <<_ACEOF +#define PATH_WTMP_FILE "$zsh_cv_path_wtmp" +_ACEOF + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for utmpx file" >&5 +$as_echo_n "checking for utmpx file... " >&6; } +if ${zsh_cv_path_utmpx+:} false; then : + $as_echo_n "(cached) " >&6 +else + for dir in /etc /usr/etc /var/adm /usr/adm /var/run /var/log ./conftest; do + zsh_cv_path_utmpx=${dir}/utmpx + test -f $zsh_cv_path_utmpx && break + zsh_cv_path_utmpx=no +done + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_path_utmpx" >&5 +$as_echo "$zsh_cv_path_utmpx" >&6; } + +if test $zsh_cv_path_utmpx != no; then + cat >>confdefs.h <<_ACEOF +#define PATH_UTMPX_FILE "$zsh_cv_path_utmpx" +_ACEOF + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for wtmpx file" >&5 +$as_echo_n "checking for wtmpx file... " >&6; } +if ${zsh_cv_path_wtmpx+:} false; then : + $as_echo_n "(cached) " >&6 +else + for dir in /etc /usr/etc /var/adm /usr/adm /var/run /var/log ./conftest; do + zsh_cv_path_wtmpx=${dir}/wtmpx + test -f $zsh_cv_path_wtmpx && break + zsh_cv_path_wtmpx=no +done + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_path_wtmpx" >&5 +$as_echo "$zsh_cv_path_wtmpx" >&6; } + +if test $zsh_cv_path_wtmpx != no; then + cat >>confdefs.h <<_ACEOF +#define PATH_WTMPX_FILE "$zsh_cv_path_wtmpx" +_ACEOF + +fi + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for brk() prototype in " >&5 +$as_echo_n "checking for brk() prototype in ... " >&6; } +if ${zsh_cv_header_unistd_h_brk_proto+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +double brk(); +int +main () +{ +int i; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_header_unistd_h_brk_proto=no +else + zsh_cv_header_unistd_h_brk_proto=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_header_unistd_h_brk_proto" >&5 +$as_echo "$zsh_cv_header_unistd_h_brk_proto" >&6; } + +if test x$zsh_cv_header_unistd_h_brk_proto = xyes; then + $as_echo "#define HAVE_BRK_PROTO 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for sbrk() prototype in " >&5 +$as_echo_n "checking for sbrk() prototype in ... " >&6; } +if ${zsh_cv_header_unistd_h_sbrk_proto+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +double sbrk(); +int +main () +{ +int i; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_header_unistd_h_sbrk_proto=no +else + zsh_cv_header_unistd_h_sbrk_proto=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_header_unistd_h_sbrk_proto" >&5 +$as_echo "$zsh_cv_header_unistd_h_sbrk_proto" >&6; } + +if test x$zsh_cv_header_unistd_h_sbrk_proto = xyes; then + $as_echo "#define HAVE_SBRK_PROTO 1" >>confdefs.h + +fi + + +if test "$ac_cv_prog_cc_stdc" != no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for mknod prototype in " >&5 +$as_echo_n "checking for mknod prototype in ... " >&6; } +if ${zsh_cv_header_sys_stat_h_mknod_proto+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + int mknod(double x); +int +main () +{ +int i; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_header_sys_stat_h_mknod_proto=no +else + zsh_cv_header_sys_stat_h_mknod_proto=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_header_sys_stat_h_mknod_proto" >&5 +$as_echo "$zsh_cv_header_sys_stat_h_mknod_proto" >&6; } + if test x$zsh_cv_header_sys_stat_h_mknod_proto = xyes; then + $as_echo "#define HAVE_MKNOD_PROTO 1" >>confdefs.h + + fi +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking for ioctl prototype in or " >&5 +$as_echo_n "checking for ioctl prototype in or ... " >&6; } +if ${zsh_cv_header_unistd_h_termios_h_ioctl_proto+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HAVE_UNISTD_H +# include +#endif +#ifdef HAVE_TERMIOS_H +# include +#endif +double ioctl(); +int +main () +{ +int i; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_header_unistd_h_termios_h_ioctl_proto=no +else + zsh_cv_header_unistd_h_termios_h_ioctl_proto=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_header_unistd_h_termios_h_ioctl_proto" >&5 +$as_echo "$zsh_cv_header_unistd_h_termios_h_ioctl_proto" >&6; } + +if test x$zsh_cv_header_unistd_h_termios_h_ioctl_proto = xno; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for ioctl prototype in " >&5 +$as_echo_n "checking for ioctl prototype in ... " >&6; } +if ${zsh_cv_header_sys_ioctl_h_ioctl_proto+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + double ioctl(); +int +main () +{ +int i; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_header_sys_ioctl_h_ioctl_proto=no +else + zsh_cv_header_sys_ioctl_h_ioctl_proto=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_header_sys_ioctl_h_ioctl_proto" >&5 +$as_echo "$zsh_cv_header_sys_ioctl_h_ioctl_proto" >&6; } +else + zsh_cv_header_sys_ioctl_h_ioctl_proto=no +fi + + +if test x$zsh_cv_header_unistd_h_termios_h_ioctl_proto = xyes || \ + test x$zsh_cv_header_sys_ioctl_h_ioctl_proto = xyes; then + $as_echo "#define HAVE_IOCTL_PROTO 1" >>confdefs.h + +fi + +if test x$zsh_cv_header_sys_ioctl_h_ioctl_proto = xyes; then + $as_echo "#define IOCTL_IN_SYS_IOCTL 1" >>confdefs.h + +fi + + +if test x$ac_cv_header_sys_select_h != xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for select() in " >&5 +$as_echo_n "checking for select() in ... " >&6; } +if ${zsh_cv_header_socket_h_select_proto+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include +int +main () +{ +fd_set fd; + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_header_socket_h_select_proto=yes +else + zsh_cv_header_socket_h_select_proto=no +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_header_socket_h_select_proto" >&5 +$as_echo "$zsh_cv_header_socket_h_select_proto" >&6; } + if test x$zsh_cv_header_socket_h_select_proto = xyes; then + $as_echo "#define SELECT_IN_SYS_SOCKET_H 1" >>confdefs.h + + fi +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if named FIFOs work" >&5 +$as_echo_n "checking if named FIFOs work... " >&6; } +if ${zsh_cv_sys_fifo+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$host_os" = cygwin; then +zsh_cv_sys_fifo=yes +else +if test "$cross_compiling" = yes; then : + zsh_cv_sys_fifo=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include +main() +{ + char c; + int fd; + int pid, ret; + unlink("/tmp/fifo$$"); +#ifdef HAVE_MKFIFO + if(mkfifo("/tmp/fifo$$", 0600) < 0) +#else + if(mknod("/tmp/fifo$$", 0010600, 0) < 0) +#endif + exit(1); + pid = fork(); + if(pid < 0) + exit(1); + if(pid) { + fd = open("/tmp/fifo$$", O_RDONLY); + exit(fd < 0 || read(fd, &c, 1) != 1 || c != 'x'); + } + fd = open("/tmp/fifo$$", O_WRONLY); + ret = (fd < 0 || write(fd, "x", 1) < 1); + unlink("/tmp/fifo$$"); + exit(ret); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_sys_fifo=yes +else + zsh_cv_sys_fifo=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_fifo" >&5 +$as_echo "$zsh_cv_sys_fifo" >&6; } + +if test x$zsh_cv_sys_fifo = xyes; then + $as_echo "#define HAVE_FIFOS 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if link() works" >&5 +$as_echo_n "checking if link() works... " >&6; } +if ${zsh_cv_sys_link+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_sys_link=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include +main() +{ + int ret; + char *tmpfile, *newfile; + tmpfile="/tmp/zsh.linktest$$"; + newfile="/tmp/zsh.linktest2$$"; + unlink(tmpfile); + unlink(newfile); + if(creat(tmpfile, 0644) < 0) + exit(1); + ret = link(tmpfile, newfile); + unlink(tmpfile); + unlink(newfile); + exit(ret<0); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_sys_link=yes +else + zsh_cv_sys_link=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_link" >&5 +$as_echo "$zsh_cv_sys_link" >&6; } + +if test x$zsh_cv_sys_link = xyes; then + $as_echo "#define HAVE_LINK 1" >>confdefs.h + +fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if kill(pid, 0) returns ESRCH correctly" >&5 +$as_echo_n "checking if kill(pid, 0) returns ESRCH correctly... " >&6; } +if ${zsh_cv_sys_killesrch+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_sys_killesrch=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include +#include +main() +{ + int pid = (getpid() + 10000) & 0xffffff; + while (pid && (kill(pid, 0) == 0 || errno != ESRCH)) pid >>= 1; + exit(errno!=ESRCH); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_sys_killesrch=yes +else + zsh_cv_sys_killesrch=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_killesrch" >&5 +$as_echo "$zsh_cv_sys_killesrch" >&6; } + +if test x$zsh_cv_sys_killesrch = xno; then + $as_echo "#define BROKEN_KILL_ESRCH 1" >>confdefs.h + +fi + + +if test x$signals_style = xPOSIX_SIGNALS; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if POSIX sigsuspend() works" >&5 +$as_echo_n "checking if POSIX sigsuspend() works... " >&6; } +if ${zsh_cv_sys_sigsuspend+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_sys_sigsuspend=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include +int child=0; +void handler(sig) + int sig; +{if(sig==SIGCHLD) child=1;} +main() { + struct sigaction act; + sigset_t set; + int pid, ret; + act.sa_handler = &handler; + sigfillset(&act.sa_mask); + act.sa_flags = 0; + sigaction(SIGCHLD, &act, 0); + sigfillset(&set); + sigprocmask(SIG_SETMASK, &set, 0); + pid=fork(); + if(pid==0) return 0; + if(pid>0) { + sigemptyset(&set); + ret=sigsuspend(&set); + exit(child==0); + } +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_sys_sigsuspend=yes +else + zsh_cv_sys_sigsuspend=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_sigsuspend" >&5 +$as_echo "$zsh_cv_sys_sigsuspend" >&6; } + if test x$zsh_cv_sys_sigsuspend = xno; then + $as_echo "#define BROKEN_POSIX_SIGSUSPEND 1" >>confdefs.h + + fi +fi + + + +# Check whether --with-tcsetpgrp was given. +if test "${with_tcsetpgrp+set}" = set; then : + withval=$with_tcsetpgrp; +case "x$withval" in + xyes) zsh_working_tcsetpgrp=yes;; + xno) zsh_working_tcsetpgrp=no;; + *) as_fn_error $? "please use --with-tcsetpgrp=yes or --with-tcsetpgrp=no" "$LINENO" 5;; +esac +else + zsh_working_tcsetpgrp=check +fi + +if test "x$ac_cv_func_tcsetpgrp" = xyes; then +case "x$zsh_working_tcsetpgrp" in + xcheck) + trap "" TTOU > /dev/null 2>&1 || : + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if tcsetpgrp() actually works" >&5 +$as_echo_n "checking if tcsetpgrp() actually works... " >&6; } +if ${zsh_cv_sys_tcsetpgrp+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_sys_tcsetpgrp=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#include +#include +main() { + int fd; + int ret; + fd=open("/dev/tty", O_RDWR); + if (fd < 0) exit(2); + ret=tcsetpgrp(fd, tcgetpgrp(fd)); + if (ret < 0) exit(1); + exit(0); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_sys_tcsetpgrp=yes +else + +case $? in + 1) zsh_cv_sys_tcsetpgrp=no;; + 2) zsh_cv_sys_tcsetpgrp=notty;; + *) zsh_cv_sys_tcsetpgrp=error;; +esac + +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_tcsetpgrp" >&5 +$as_echo "$zsh_cv_sys_tcsetpgrp" >&6; } + case "x$zsh_cv_sys_tcsetpgrp" in + xno) $as_echo "#define BROKEN_TCSETPGRP 1" >>confdefs.h +;; + xyes) :;; + xnotty) as_fn_error $? "no controlling tty +Try running configure with --with-tcsetpgrp or --without-tcsetpgrp" "$LINENO" 5;; + *) as_fn_error $? "unexpected return status" "$LINENO" 5;; + esac + trap - TTOU > /dev/null 2>&1 || : + ;; + xyes) :;; + xno) $as_echo "#define BROKEN_TCSETPGRP 1" >>confdefs.h +;; + *) as_fn_error $? "unexpected value zsh_working_tcsetpgrp=$zsh_working_tcsetpgrp" "$LINENO" 5;; +esac +fi + + +if test x$ac_cv_func_getpwnam = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if getpwnam() is faked" >&5 +$as_echo_n "checking if getpwnam() is faked... " >&6; } +if ${zsh_cv_sys_getpwnam_faked+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_sys_getpwnam_faked=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +main() { + struct passwd *pw1, *pw2; + char buf[1024], name[1024]; + sprintf(buf, "%d:%d", getpid(), rand()); + pw1=getpwnam(buf); + if (pw1) strcpy(name, pw1->pw_name); + sprintf(buf, "%d:%d", rand(), getpid()); + pw2=getpwnam(buf); + exit(pw1!=0 && pw2!=0 && !strcmp(name, pw2->pw_name)); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_sys_getpwnam_faked=no +else + zsh_cv_sys_getpwnam_faked=yes +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_getpwnam_faked" >&5 +$as_echo "$zsh_cv_sys_getpwnam_faked" >&6; } + if test x$zsh_cv_sys_getpwnam_faked = xyes; then + $as_echo "#define GETPWNAM_FAKED 1" >>confdefs.h + + fi +fi + + + + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking base type of the third argument to accept" >&5 +$as_echo_n "checking base type of the third argument to accept... " >&6; } +if ${zsh_cv_type_socklen_t+:} false; then : + $as_echo_n "(cached) " >&6 +else + zsh_cv_type_socklen_t= + for zsh_type in socklen_t int "unsigned long" size_t ; do + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#include + #include +int +main () +{ +extern int accept (int, struct sockaddr *, $zsh_type *); + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + zsh_cv_type_socklen_t="$zsh_type"; break +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext + done + if test -z "$zsh_cv_type_socklen_t"; then + zsh_cv_type_socklen_t=int + fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_type_socklen_t" >&5 +$as_echo "$zsh_cv_type_socklen_t" >&6; } + +cat >>confdefs.h <<_ACEOF +#define ZSOCKLEN_T $zsh_cv_type_socklen_t +_ACEOF + + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if your system has /dev/ptmx" >&5 +$as_echo_n "checking if your system has /dev/ptmx... " >&6; } +if ${ac_cv_have_dev_ptmx+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test -w /dev/ptmx; then + ac_cv_have_dev_ptmx=yes +else + ac_cv_have_dev_ptmx=no +fi +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_have_dev_ptmx" >&5 +$as_echo "$ac_cv_have_dev_ptmx" >&6; } + + +if test x$ac_cv_have_dev_ptmx = xyes -o x$ac_cv_func_posix_openpt = xyes && \ + test x$ac_cv_func_grantpt = xyes && \ + test x$ac_cv_func_unlockpt = xyes && \ + test x$ac_cv_func_ptsname = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if /dev/ptmx is usable" >&5 +$as_echo_n "checking if /dev/ptmx is usable... " >&6; } +if ${ac_cv_use_dev_ptmx+:} false; then : + $as_echo_n "(cached) " >&6 +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +#ifdef __linux +#define _GNU_SOURCE 1 +#endif +#include +int ptsname(); +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_compile "$LINENO"; then : + ac_cv_use_dev_ptmx=no +else + ac_cv_use_dev_ptmx=yes +fi +rm -f core conftest.err conftest.$ac_objext conftest.$ac_ext +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $ac_cv_use_dev_ptmx" >&5 +$as_echo "$ac_cv_use_dev_ptmx" >&6; } + if test x$ac_cv_use_dev_ptmx = xyes; then + $as_echo "#define USE_DEV_PTMX 1" >>confdefs.h + + fi +fi + +# Check whether --enable-multibyte was given. +if test "${enable_multibyte+set}" = set; then : + enableval=$enable_multibyte; zsh_cv_c_unicode_support=$enableval +else + if ${zsh_cv_c_unicode_support+:} false; then : + $as_echo_n "(cached) " >&6 +else + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for functions supporting multibyte characters" >&5 +$as_echo "$as_me: checking for functions supporting multibyte characters" >&6;} + zfuncs_absent= + for zfunc in iswalnum iswcntrl iswdigit iswgraph iswlower iswprint \ +iswpunct iswspace iswupper iswxdigit mbrlen mbrtowc towupper towlower \ +wcschr wcscpy wcslen wcsncmp wcsncpy wcrtomb wcwidth wmemchr wmemcmp \ +wmemcpy wmemmove wmemset; do + as_ac_var=`$as_echo "ac_cv_func_$zfunc" | $as_tr_sh` +ac_fn_c_check_func "$LINENO" "$zfunc" "$as_ac_var" +if eval test \"x\$"$as_ac_var"\" = x"yes"; then : + : +else + zfuncs_absent="$zfuncs_absent $zfunc" +fi + + done + if test x"$zfuncs_absent" = x; then + { $as_echo "$as_me:${as_lineno-$LINENO}: all functions found, multibyte support enabled" >&5 +$as_echo "$as_me: all functions found, multibyte support enabled" >&6;} + zsh_cv_c_unicode_support=yes + else + { $as_echo "$as_me:${as_lineno-$LINENO}: missing functions, multibyte support disabled" >&5 +$as_echo "$as_me: missing functions, multibyte support disabled" >&6;} + zsh_cv_c_unicode_support=no + fi + +fi + + +fi + + + + +# Check whether --enable-unicode9 was given. +if test "${enable_unicode9+set}" = set; then : + enableval=$enable_unicode9; if test x$enableval = xyes; then + $as_echo "#define ENABLE_UNICODE9 1" >>confdefs.h + +fi +fi + + + + +if test x$zsh_cv_c_unicode_support = xyes; then + $as_echo "#define MULTIBYTE_SUPPORT 1" >>confdefs.h + + + locale_prog='char *my_locales[] = { + "en_US.UTF-8", "en_GB.UTF-8", "en.UTF-8", ' + locale_prog="$locale_prog"`locale -a 2>/dev/null | \ + sed -e 's/utf8/UTF-8/' | grep UTF-8 | \ + while read line; do echo " \"$line\","; done;` + locale_prog="$locale_prog 0 }; + #define _XOPEN_SOURCE + #include + #include + #include + #include + + int main() { + char **localep; + char comb_acute_mb[] = { (char)0xcc, (char)0x81 }; + char u_0234[] = { (char)0xc8, (char)0xb4 }; + wchar_t wc; + #if !defined(__STDC_ISO_10646__) && !defined(__APPLE__) + return 1; + #endif + + for (localep = my_locales; *localep; localep++) + if (setlocale(LC_ALL, *localep)) + break; + if (!*localep) + return 1; + if (mbtowc(&wc, comb_acute_mb, 2) == 2 && (wcwidth(wc) != 0 || !iswprint(wc))) + return 0; + if (mbtowc(&wc, u_0234, 2) == 2 && (wcwidth(wc) != 1 || !iswprint(wc))) + return 0; + return 1; + } + " + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the wcwidth() and/or iswprint() functions are broken" >&5 +$as_echo_n "checking if the wcwidth() and/or iswprint() functions are broken... " >&6; } +if ${zsh_cv_c_broken_wcwidth+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_c_broken_wcwidth=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$locale_prog +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_c_broken_wcwidth=yes +else + zsh_cv_c_broken_wcwidth=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_c_broken_wcwidth" >&5 +$as_echo "$zsh_cv_c_broken_wcwidth" >&6; } + if test x$zsh_cv_c_broken_wcwidth = xyes; then + $as_echo "#define ENABLE_UNICODE9 1" >>confdefs.h + + fi + + locale_prog='char *my_locales[] = { + "en_US.UTF-8", "en_GB.UTF-8", "en.UTF-8", ' + locale_prog="$locale_prog"`locale -a 2>/dev/null | \ + sed -e 's/utf8/UTF-8/' | grep UTF-8 | \ + while read line; do echo " \"$line\","; done;` + locale_prog="$locale_prog 0 }; + #include + #include + + int main() { + char **localep; + for (localep = my_locales; *localep; localep++) + if (setlocale(LC_ALL, *localep) && isprint(0xa0)) + return 0; + return 1; + } + " + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if the isprint() function is broken" >&5 +$as_echo_n "checking if the isprint() function is broken... " >&6; } +if ${zsh_cv_c_broken_isprint+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_c_broken_isprint=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +$locale_prog +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_c_broken_isprint=yes +else + zsh_cv_c_broken_isprint=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_c_broken_isprint" >&5 +$as_echo "$zsh_cv_c_broken_isprint" >&6; } + if test x$zsh_cv_c_broken_isprint = xyes; then + $as_echo "#define BROKEN_ISPRINT 1" >>confdefs.h + + fi +fi + + +# Check whether --enable-libc-musl was given. +if test "${enable_libc_musl+set}" = set; then : + enableval=$enable_libc_musl; if test x$enableval = xyes; then + $as_echo "#define LIBC_MUSL 1" >>confdefs.h + +fi +fi + + +# Check whether --enable-dynamic-nss was given. +if test "${enable_dynamic_nss+set}" = set; then : + enableval=$enable_dynamic_nss; zsh_cv_c_dynamic_nss=$enableval +fi + + + +if test x$zsh_cv_c_dynamic_nss = xno; then + $as_echo "#define DISABLE_DYNAMIC_NSS 1" >>confdefs.h + +fi + + +L=N +INSTLIB="install.bin-\$(L)" +UNINSTLIB="uninstall.bin-\$(L)" +LINKMODS=NOLINKMODS +MOD_EXPORT= +MOD_IMPORT_VARIABLE= +MOD_IMPORT_FUNCTION= +aixdynamic=no +hpuxdynamic=no +if test "$ac_cv_func_load" = yes && + test "$ac_cv_func_unload" = yes && + test "$ac_cv_func_loadbind" = yes && + test "$ac_cv_func_loadquery" = yes; then + if test "x$dynamic" = xyes; then + aixdynamic=yes + fi +elif test "$ac_cv_func_dlopen" != yes || + test "$ac_cv_func_dlsym" != yes || + test "$ac_cv_func_dlerror" != yes; then + if test "$ac_cv_func_shl_load" != yes || + test "$ac_cv_func_shl_unload" != yes || + test "$ac_cv_func_shl_findsym" != yes; then + dynamic=no + elif test "x$dynamic" = xyes; then + hpuxdynamic=yes + DL_EXT="${DL_EXT=sl}" + $as_echo "#define HPUX10DYNAMIC 1" >>confdefs.h + fi +fi + +test -n "$GCC" && LDARG=-Wl, + + + +if test "x$aixdynamic" = xyes; then + DL_EXT="${DL_EXT=so}" + DLLD="${DLLD=$CC}" + zsh_cv_func_dlsym_needs_underscore=no + if test -n "$GCC"; then + DLLDFLAGS=${DLLDFLAGS=-shared} + else + DLLDFLAGS=${DLLDFLAGS=-bM:SRE} + fi + DLLDFLAGS=${DLLDFLAGS=} + EXTRA_LDFLAGS=${EXTRA_LDFLAGS=} + EXPOPT=${LDARG}-bE: + IMPOPT=${LDARG}-bI: + zsh_cv_sys_dynamic_clash_ok="${zsh_cv_sys_dynamic_clash_ok=yes}" + zsh_cv_sys_dynamic_rtld_global="${zsh_cv_sys_dynamic_rtld_global=yes}" + zsh_cv_sys_dynamic_execsyms="${zsh_cv_sys_dynamic_execsyms=yes}" + zsh_cv_sys_dynamic_strip_exe="${zsh_cv_sys_dynamic_strip_exe=yes}" + zsh_cv_sys_dynamic_strip_lib="${zsh_cv_sys_dynamic_strip_lib=yes}" + zsh_cv_shared_environ="${zsh_cv_shared_environ=yes}" +elif test "$host_os" = cygwin; then + DL_EXT="${DL_EXT=dll}" +##DLLD="${DLLD=dllwrap}" + DLLD="${DLLD=$CC}" +##DLLDFLAGS="${DLLDFLAGS=--export-all-symbols}" + DLLDFLAGS=${DLLDFLAGS=-shared -Wl,--export-all-symbols} + zsh_cv_func_dlsym_needs_underscore=no + DLLDFLAGS=${DLLDFLAGS=} + EXTRA_LDFLAGS=${EXTRA_LDFLAGS=} + zsh_cv_sys_dynamic_clash_ok="${zsh_cv_sys_dynamic_clash_ok=no}" + zsh_cv_sys_dynamic_rtld_global="${zsh_cv_sys_dynamic_rtld_global=yes}" + zsh_cv_sys_dynamic_execsyms="${zsh_cv_sys_dynamic_execsyms=no}" + zsh_cv_sys_dynamic_strip_exe="${zsh_cv_sys_dynamic_strip_exe=yes}" + zsh_cv_sys_dynamic_strip_lib="${zsh_cv_sys_dynamic_strip_lib=yes}" + # + # THAT SUCKS! and must be changed + # + zsh_cv_shared_environ="${zsh_cv_shared_environ=yes}" + LINKMODS=LINKMODS + MOD_EXPORT="__attribute__((__dllexport__))" + MOD_IMPORT_VARIABLE="__attribute__((__dllimport__))" + MOD_IMPORT_FUNCTION= +elif test "x$dynamic" = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if your system uses ELF binaries" >&5 +$as_echo_n "checking if your system uses ELF binaries... " >&6; } +if ${zsh_cv_sys_elf+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$cross_compiling" = yes; then : + zsh_cv_sys_elf=yes +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ +/* Test for whether ELF binaries are produced */ +#include +#include +main(argc, argv) +int argc; +char *argv[]; +{ + char b[4]; + int i = open(argv[0],O_RDONLY); + if(i == -1) + exit(1); /* fail */ + if(read(i,b,4)==4 && b[0]==127 && b[1]=='E' && b[2]=='L' && b[3]=='F') + exit(0); /* succeed (yes, it's ELF) */ + else + exit(1); /* fail */ +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_sys_elf=yes +else + zsh_cv_sys_elf=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_elf" >&5 +$as_echo "$zsh_cv_sys_elf" >&6; } + + # We use [0-9]* in case statements, so need to change quoting + + + DL_EXT="${DL_EXT=so}" + if test x$zsh_cv_sys_elf = xyes; then + case "$host" in + mips-sni-sysv4*) + # Forcibly set ld to native compiler to avoid obscure GCC problems + DLLD="${DLLD=/usr/ccs/bin/cc}" + DLLDARG="${LDARG}" + ;; + * ) + DLLD="${DLLD=$CC}" + DLLDARG="${LDARG}" + ;; + esac + else + case "$host" in + *openbsd*) + case "$host_os" in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + DLLD="${DLLD=ld}" + ;; + *) + DLLD="${DLLD=$CC}" + ;; + esac + DLLDARG="${LDARG}" + ;; + *darwin*) + DLLD="${DLLD=$CC}" + DLLDARG="" + ;; + *interix*) + DLLD="${DLLD=$CC}" + DLLDARG="" + ;; + * ) + DLLD="${DLLD=ld}" + DLLDARG="" + ;; + esac + fi + if test -n "$GCC"; then + case "$host_os" in + hpux*) DLLDFLAGS="${DLLDFLAGS=-shared}" ;; + darwin*) DLCFLAGS="${DLCFLAGS=-fno-common}" ;; + interix*) DLCFLAGS="${DLCFLAGS=}" ;; + *) DLCFLAGS="${DLCFLAGS=-fPIC}" ;; + esac + else + case "$host_os" in + hpux*) + DLCFLAGS="${DLCFLAGS=+z}" + DLLDFLAGS="${DLLDFLAGS=-b}" + ;; + sunos*) DLCFLAGS="${DLCFLAGS=-pic}" ;; + solaris*|sysv4*|esix*) DLCFLAGS="${DLCFLAGS=-KPIC}" ;; + esac + fi + case "$host_os" in + osf*) DLLDFLAGS="${DLLDFLAGS=-shared -expect_unresolved '*'}" ;; + *freebsd*|*netbsd*|linux*|irix*|gnu*|interix*|dragonfly*) DLLDFLAGS="${DLLDFLAGS=-shared}" ;; + sunos*) DLLDFLAGS="${DLLDFLAGS=-assert nodefinitions}" ;; + sysv4*|esix*) DLLDFLAGS="${DLLDFLAGS=-G $ldflags}" ;; + aix*) DLLDFLAGS="${DLLDFLAGS=-G -bexpall -lc}" ;; + solaris*|sysv4*|esix*) DLLDFLAGS="${DLLDFLAGS=-G}" ;; + darwin*) DLLDFLAGS="${DLLDFLAGS=-bundle -flat_namespace -undefined suppress}" ;; + beos*|haiku*) DLLDFLAGS="${DLLDFLAGS=-nostart}" ;; + openbsd*) + if test x$zsh_cv_sys_elf = xyes; then + DLLDFLAGS="${DLLDFLAGS=-shared -fPIC}" + else + case "$host_os" in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + DLLDFLAGS="${DLLDFLAGS=-Bshareable}" + ;; + *) + DLLDFLAGS="${DLLDFLAGS=-shared -fPIC}" + ;; + esac + fi + ;; + esac + case "$host" in + *-hpux*) EXTRA_LDFLAGS="${EXTRA_LDFLAGS=-Wl,-E}" ;; + *openbsd*) + if test x$zsh_cv_sys_elf = xyes; then + EXTRA_LDFLAGS="${EXTRA_LDFLAGS=-Wl,-E}" + fi + ;; + mips-sni-sysv4) + # + # unfortunately, we have different compilers + # that need different flags + # + if test -n "$GCC"; then + sni_cc_version=GCC + else + sni_cc_version=`$CC -V 2>&1 | head -1` + fi + case "$sni_cc_version" in + *CDS*|GCC ) + EXTRA_LDFLAGS="${EXTRA_LDFLAGS=-Wl,-Blargedynsym}" + ;; + * ) + EXTRA_LDFLAGS="${EXTRA_LDFLAGS=-LD-Blargedynsym}" + ;; + esac + ;; + *-beos*) + # gcc on BeOS doesn't like -rdynamic... + EXTRA_LDFLAGS="${EXTRA_LDFLAGS= }" + # also, dlopen() at least in Zeta respects $LIBRARY_PATH, so needs %A added to it. + export LIBRARY_PATH="$LIBRARY_PATH:%A/" + ;; + *-haiku*) + # + ;; + esac + + # Done with our shell code, so restore autotools quoting + + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking if we can use -rdynamic" >&5 +$as_echo_n "checking if we can use -rdynamic... " >&6; } +if ${zsh_cv_rdynamic_available+:} false; then : + $as_echo_n "(cached) " >&6 +else + old_LDFLAGS="$LDFLAGS" +LDFLAGS="$LDFLAGS -rdynamic" +cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +int +main () +{ + + ; + return 0; +} +_ACEOF +if ac_fn_c_try_link "$LINENO"; then : + zsh_cv_rdynamic_available=yes +EXTRA_LDFLAGS="${EXTRA_LDFLAGS=-rdynamic}" +else + zsh_cvs_rdynamic_available=no +fi +rm -f core conftest.err conftest.$ac_objext \ + conftest$ac_exeext conftest.$ac_ext +LDFLAGS="$old_LDFLAGS" +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_rdynamic_available" >&5 +$as_echo "$zsh_cv_rdynamic_available" >&6; } + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if your dlsym() needs a leading underscore" >&5 +$as_echo_n "checking if your dlsym() needs a leading underscore... " >&6; } +if ${zsh_cv_func_dlsym_needs_underscore+:} false; then : + $as_echo_n "(cached) " >&6 +else + echo failed >conftestval && cat >conftest.c <&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && + { ac_try='$DLLD $LDFLAGS $DLLDFLAGS -o conftest.$DL_EXT conftest.o 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && + if test "$cross_compiling" = yes; then : + zsh_cv_func_dlsym_needs_underscore=no +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#include +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif + +extern int fred() ; + +main() +{ + void * handle ; + void * symbol ; + FILE *f=fopen("conftestval", "w"); + if (!f) exit(1); + handle = dlopen("./conftest.$DL_EXT", RTLD_LAZY) ; + if (handle == NULL) { + fprintf (f, "dlopen failed") ; + exit(1); + } + symbol = dlsym(handle, "fred") ; + if (symbol == NULL) { + /* try putting a leading underscore */ + symbol = dlsym(handle, "_fred") ; + if (symbol == NULL) { + fprintf (f, "dlsym failed") ; + exit(1); + } + fprintf (f, "yes") ; + } + else + fprintf (f, "no") ; + exit(0); +} +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_func_dlsym_needs_underscore=`cat conftestval` +else + zsh_cv_func_dlsym_needs_underscore=failed + dynamic=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_func_dlsym_needs_underscore" >&5 +$as_echo "$zsh_cv_func_dlsym_needs_underscore" >&6; } + if test "x$zsh_cv_func_dlsym_needs_underscore" = xyes; then + $as_echo "#define DLSYM_NEEDS_UNDERSCORE 1" >>confdefs.h + + elif test "x$zsh_cv_func_dlsym_needs_underscore" != xno; then + unset zsh_cv_func_dlsym_needs_underscore + fi +fi + +if test "x$dynamic" = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if environ is available in shared libraries" >&5 +$as_echo_n "checking if environ is available in shared libraries... " >&6; } +if ${zsh_cv_shared_environ+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ +else + us= +fi +echo ' +void *zsh_getaddr1() +{ +#ifdef __CYGWIN__ + __attribute__((__dllimport__)) +#endif + extern char ** environ; + return &environ; +}; +' > conftest1.c +sed 's/zsh_getaddr1/zsh_getaddr2/' < conftest1.c > conftest2.c +if { ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest2.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$DLLD -o conftest2.$DL_EXT $LDFLAGS $DLLDFLAGS conftest2.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + if test "$cross_compiling" = yes; then : + zsh_cv_shared_environ=no + +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +main() +{ + void *handle1, *handle2; + void *(*zsh_getaddr1)(), *(*zsh_getaddr2)(); + void *sym1, *sym2; + handle1 = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle1) exit(1); + handle2 = dlopen("./conftest2.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle2) exit(1); + zsh_getaddr1 = (void *(*)()) dlsym(handle1, "${us}zsh_getaddr1"); + zsh_getaddr2 = (void *(*)()) dlsym(handle2, "${us}zsh_getaddr2"); + sym1 = zsh_getaddr1(); + sym2 = zsh_getaddr2(); + if(!sym1 || !sym2) exit(1); + if(sym1 != sym2) exit(1); + dlclose(handle1); + handle1 = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle1) exit(1); + zsh_getaddr1 = (void *(*)()) dlsym(handle1, "${us}zsh_getaddr1"); + sym1 = zsh_getaddr1(); + if(!sym1) exit(1); + if(sym1 != sym2) exit(1); + exit(0); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_shared_environ=yes +else + zsh_cv_shared_environ=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +else + zsh_cv_shared_environ=no +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_shared_environ" >&5 +$as_echo "$zsh_cv_shared_environ" >&6; } + + test "$zsh_cv_shared_environ" = yes || dynamic=no + if test "$ac_cv_func_tgetent" = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if tgetent is available in shared libraries" >&5 +$as_echo_n "checking if tgetent is available in shared libraries... " >&6; } +if ${zsh_cv_shared_tgetent+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ +else + us= +fi +echo ' +void *zsh_getaddr1() +{ +#ifdef __CYGWIN__ + __attribute__((__dllimport__)) +#endif + extern int tgetent ( ); + return tgetent; +}; +' > conftest1.c +sed 's/zsh_getaddr1/zsh_getaddr2/' < conftest1.c > conftest2.c +if { ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest2.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$DLLD -o conftest2.$DL_EXT $LDFLAGS $DLLDFLAGS conftest2.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + if test "$cross_compiling" = yes; then : + zsh_cv_shared_tgetent=no + +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +main() +{ + void *handle1, *handle2; + void *(*zsh_getaddr1)(), *(*zsh_getaddr2)(); + void *sym1, *sym2; + handle1 = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle1) exit(1); + handle2 = dlopen("./conftest2.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle2) exit(1); + zsh_getaddr1 = (void *(*)()) dlsym(handle1, "${us}zsh_getaddr1"); + zsh_getaddr2 = (void *(*)()) dlsym(handle2, "${us}zsh_getaddr2"); + sym1 = zsh_getaddr1(); + sym2 = zsh_getaddr2(); + if(!sym1 || !sym2) exit(1); + if(sym1 != sym2) exit(1); + dlclose(handle1); + handle1 = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle1) exit(1); + zsh_getaddr1 = (void *(*)()) dlsym(handle1, "${us}zsh_getaddr1"); + sym1 = zsh_getaddr1(); + if(!sym1) exit(1); + if(sym1 != sym2) exit(1); + exit(0); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_shared_tgetent=yes +else + zsh_cv_shared_tgetent=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +else + zsh_cv_shared_tgetent=no +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_shared_tgetent" >&5 +$as_echo "$zsh_cv_shared_tgetent" >&6; } + + fi + if test "$ac_cv_func_tigetstr" = yes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if tigetstr is available in shared libraries" >&5 +$as_echo_n "checking if tigetstr is available in shared libraries... " >&6; } +if ${zsh_cv_shared_tigetstr+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ +else + us= +fi +echo ' +void *zsh_getaddr1() +{ +#ifdef __CYGWIN__ + __attribute__((__dllimport__)) +#endif + extern int tigetstr ( ); + return tigetstr; +}; +' > conftest1.c +sed 's/zsh_getaddr1/zsh_getaddr2/' < conftest1.c > conftest2.c +if { ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest2.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$DLLD -o conftest2.$DL_EXT $LDFLAGS $DLLDFLAGS conftest2.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + if test "$cross_compiling" = yes; then : + zsh_cv_shared_tigetstr=no + +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +main() +{ + void *handle1, *handle2; + void *(*zsh_getaddr1)(), *(*zsh_getaddr2)(); + void *sym1, *sym2; + handle1 = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle1) exit(1); + handle2 = dlopen("./conftest2.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle2) exit(1); + zsh_getaddr1 = (void *(*)()) dlsym(handle1, "${us}zsh_getaddr1"); + zsh_getaddr2 = (void *(*)()) dlsym(handle2, "${us}zsh_getaddr2"); + sym1 = zsh_getaddr1(); + sym2 = zsh_getaddr2(); + if(!sym1 || !sym2) exit(1); + if(sym1 != sym2) exit(1); + dlclose(handle1); + handle1 = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle1) exit(1); + zsh_getaddr1 = (void *(*)()) dlsym(handle1, "${us}zsh_getaddr1"); + sym1 = zsh_getaddr1(); + if(!sym1) exit(1); + if(sym1 != sym2) exit(1); + exit(0); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_shared_tigetstr=yes +else + zsh_cv_shared_tigetstr=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +else + zsh_cv_shared_tigetstr=no +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_shared_tigetstr" >&5 +$as_echo "$zsh_cv_shared_tigetstr" >&6; } + + fi +fi + +if test "x$dynamic" = xyes; then + { $as_echo "$as_me:${as_lineno-$LINENO}: checking if name clashes in shared objects are OK" >&5 +$as_echo_n "checking if name clashes in shared objects are OK... " >&6; } +if ${zsh_cv_sys_dynamic_clash_ok+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ +else + us= +fi +echo 'int fred () { return 42; }' > conftest1.c +echo 'int fred () { return 69; }' > conftest2.c +if { ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest2.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$DLLD -o conftest2.$DL_EXT $LDFLAGS $DLLDFLAGS conftest2.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + if test "$cross_compiling" = yes; then : + zsh_cv_sys_dynamic_clash_ok=no + +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + + +main() +{ + void *handle1, *handle2; + int (*fred1)(), (*fred2)(); + handle1 = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle1) exit(1); + handle2 = dlopen("./conftest2.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle2) exit(1); + fred1 = (int (*)()) dlsym(handle1, "${us}fred"); + fred2 = (int (*)()) dlsym(handle2, "${us}fred"); + if(!fred1 || !fred2) exit(1); + exit((*fred1)() != 42 || (*fred2)() != 69); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_sys_dynamic_clash_ok=yes +else + zsh_cv_sys_dynamic_clash_ok=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +else + zsh_cv_sys_dynamic_clash_ok=no +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_dynamic_clash_ok" >&5 +$as_echo "$zsh_cv_sys_dynamic_clash_ok" >&6; } +if test "$zsh_cv_sys_dynamic_clash_ok" = yes; then + $as_echo "#define DYNAMIC_NAME_CLASH_OK 1" >>confdefs.h + +fi + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking for working RTLD_GLOBAL" >&5 +$as_echo_n "checking for working RTLD_GLOBAL... " >&6; } +if ${zsh_cv_sys_dynamic_rtld_global+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ +else + us= +fi +echo 'int fred () { return 42; }' > conftest1.c +echo 'extern int fred(); int barney () { return fred() + 27; }' > conftest2.c +if { ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest2.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$DLLD -o conftest2.$DL_EXT $LDFLAGS $DLLDFLAGS conftest2.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + if test "$cross_compiling" = yes; then : + zsh_cv_sys_dynamic_rtld_global=no + +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +main() +{ + void *handle; + int (*barneysym)(); + handle = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle) exit(1); + handle = dlopen("./conftest2.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle) exit(1); + barneysym = (int (*)()) dlsym(handle, "${us}barney"); + if(!barneysym) exit(1); + exit((*barneysym)() != 69); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_sys_dynamic_rtld_global=yes +else + zsh_cv_sys_dynamic_rtld_global=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +else + zsh_cv_sys_dynamic_rtld_global=no +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_dynamic_rtld_global" >&5 +$as_echo "$zsh_cv_sys_dynamic_rtld_global" >&6; } + + RTLD_GLOBAL_OK=$zsh_cv_sys_dynamic_rtld_global + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether symbols in the executable are available" >&5 +$as_echo_n "checking whether symbols in the executable are available... " >&6; } +if ${zsh_cv_sys_dynamic_execsyms+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ +else + us= +fi +echo 'extern int fred(); int barney () { return fred() + 27; }' > conftest1.c +if { ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + save_ldflags=$LDFLAGS + LDFLAGS="$LDFLAGS $EXTRA_LDFLAGS" + if test "$cross_compiling" = yes; then : + zsh_cv_sys_dynamic_execsyms=no + +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +main() +{ + void *handle; + int (*barneysym)(); + handle = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle) exit(1); + barneysym = (int (*)()) dlsym(handle, "${us}barney"); + if(!barneysym) exit(1); + exit((*barneysym)() != 69); +} + +int fred () { return 42; } + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_sys_dynamic_execsyms=yes +else + zsh_cv_sys_dynamic_execsyms=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LDFLAGS=$save_ldflags +else + zsh_cv_sys_dynamic_execsyms=no +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_dynamic_execsyms" >&5 +$as_echo "$zsh_cv_sys_dynamic_execsyms" >&6; } + + if test "$zsh_cv_sys_dynamic_execsyms" != yes; then + L=L + fi + +{ $as_echo "$as_me:${as_lineno-$LINENO}: checking whether executables can be stripped" >&5 +$as_echo_n "checking whether executables can be stripped... " >&6; } +if ${zsh_cv_sys_dynamic_strip_exe+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$zsh_cv_sys_dynamic_execsyms" != yes; then + zsh_cv_sys_dynamic_strip_exe=yes +elif + if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ + else + us= + fi + echo 'extern int fred(); int barney() { return fred() + 27; }' > conftest1.c + { ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && + { ac_try='$DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS conftest1.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + save_ldflags=$LDFLAGS + LDFLAGS="$LDFLAGS $EXTRA_LDFLAGS -s" + if test "$cross_compiling" = yes; then : + zsh_cv_sys_dynamic_strip_exe=no + +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +main() +{ + void *handle; + int (*barneysym)(); + handle = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle) exit(1); + barneysym = (int (*)()) dlsym(handle, "${us}barney"); + if(!barneysym) exit(1); + exit((*barneysym)() != 69); +} + +int fred () { return 42; } + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_sys_dynamic_strip_exe=yes +else + zsh_cv_sys_dynamic_strip_exe=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + + LDFLAGS=$save_ldflags +else + zsh_cv_sys_dynamic_strip_exe=no +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_dynamic_strip_exe" >&5 +$as_echo "$zsh_cv_sys_dynamic_strip_exe" >&6; } + + { $as_echo "$as_me:${as_lineno-$LINENO}: checking whether libraries can be stripped" >&5 +$as_echo_n "checking whether libraries can be stripped... " >&6; } +if ${zsh_cv_sys_dynamic_strip_lib+:} false; then : + $as_echo_n "(cached) " >&6 +else + if test "$zsh_cv_func_dlsym_needs_underscore" = yes; then + us=_ +else + us= +fi +echo 'int fred () { return 42; }' > conftest1.c +if { ac_try='$CC -c $CFLAGS $CPPFLAGS $DLCFLAGS conftest1.c 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; } && +{ ac_try='$DLLD -o conftest1.$DL_EXT $LDFLAGS $DLLDFLAGS -s conftest1.o $LIBS 1>&5' + { { eval echo "\"\$as_me\":${as_lineno-$LINENO}: \"$ac_try\""; } >&5 + (eval $ac_try) 2>&5 + ac_status=$? + $as_echo "$as_me:${as_lineno-$LINENO}: \$? = $ac_status" >&5 + test $ac_status = 0; }; }; then + if test "$cross_compiling" = yes; then : + zsh_cv_sys_dynamic_strip_lib=no + +else + cat confdefs.h - <<_ACEOF >conftest.$ac_ext +/* end confdefs.h. */ + +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif +#ifndef RTLD_GLOBAL +#define RTLD_GLOBAL 0 +#endif + +main() +{ + void *handle; + int (*fredsym)(); + handle = dlopen("./conftest1.$DL_EXT", RTLD_LAZY | RTLD_GLOBAL); + if(!handle) exit(1); + fredsym = (int (*)()) dlsym(handle, "${us}fred"); + if(!fredsym) exit(1); + exit((*fredsym)() != 42); +} + +_ACEOF +if ac_fn_c_try_run "$LINENO"; then : + zsh_cv_sys_dynamic_strip_lib=yes +else + zsh_cv_sys_dynamic_strip_lib=no +fi +rm -f core *.core core.conftest.* gmon.out bb.out conftest$ac_exeext \ + conftest.$ac_objext conftest.beam conftest.$ac_ext +fi + +else + zsh_cv_sys_dynamic_strip_lib=no +fi + +fi +{ $as_echo "$as_me:${as_lineno-$LINENO}: result: $zsh_cv_sys_dynamic_strip_lib" >&5 +$as_echo "$zsh_cv_sys_dynamic_strip_lib" >&6; } + + if $strip_exeldflags && test "$zsh_cv_sys_dynamic_strip_exe" = yes; then + EXELDFLAGS="$EXELDFLAGS -s" + fi + if $strip_libldflags && test "$zsh_cv_sys_dynamic_strip_lib" = yes; then + LIBLDFLAGS="$LIBLDFLAGS -s" + fi + if test "$host_os" = cygwin; then + INSTLIB="install.cygwin-lib" + UNINSTLIB="uninstall.cygwin-lib" + fi +else + $strip_exeldflags && EXELDFLAGS="$EXELDFLAGS -s" + $strip_libldflags && LIBLDFLAGS="$LIBLDFLAGS -s" + RTLD_GLOBAL_OK=no +fi + + +if test "x$dynamic" = xyes; then + D=D + $as_echo "#define DYNAMIC 1" >>confdefs.h +else + D=N +fi + + +if test "x$aixdynamic" = xyes; then + E=E + $as_echo "#define AIXDYNAMIC 1" >>confdefs.h +else + E=N +fi + +if test "x$zsh_cv_sys_dynamic_clash_ok" = xyes; then + SHORTBOOTNAMES=yes +else + SHORTBOOTNAMES=no +fi + + + +if test "$host_os" = cygwin; then + EXTRAZSHOBJS="$EXTRAZSHOBJS zsh.res.o" +fi + + +cat >>confdefs.h <<_ACEOF +#define DL_EXT "$DL_EXT" +_ACEOF + +# Generate config.modules. We look for *.mdd files in first and second +# level subdirectories. Any existing line not containing 'auto=y' will be +# retained, provided the .mdd file itself was found. +CONFIG_MODULES=./config.modules +cat < ${CONFIG_MODULES}.sh +srcdir="$srcdir" +dynamic="$dynamic" +CONFIG_MODULES="${CONFIG_MODULES}" +EOM +cat <<\EOM >> ${CONFIG_MODULES}.sh +echo "creating ${CONFIG_MODULES}" +userlist=" " +if test -f ${CONFIG_MODULES}; then + userlist="`sed -e '/^#/d' -e '/auto=y/d' -e 's/ .*/ /' -e 's/^name=/ /' \ + ${CONFIG_MODULES}`" + mv ${CONFIG_MODULES} ${CONFIG_MODULES}.old +else + # Save testing for existence each time. + echo > ${CONFIG_MODULES}.old +fi +(echo "# Edit this file to change the way modules are loaded." +echo "# The format is strict; do not break lines or add extra spaces." +echo "# Run \`make prep' if you change anything here after compiling" +echo "# (there is no need if you change this just after the first time" +echo "# you run \`configure')." +echo "#" +echo "# Values of \`link' are \`static', \`dynamic' or \`no' to compile the" +echo "# module into the shell, link it in at run time, or not use it at all." +echo "# In the final case, no attempt will be made to compile it." +echo "# Use \`static' or \`no' if you do not have dynamic loading." +echo "#" +echo "# Values of \`load' are \`yes' or \`no'; if yes, any builtins etc." +echo "# provided by the module will be autoloaded by the main shell" +echo "# (so long as \`link' is not set to \`no')." +echo "#" +echo "# Values of \`auto' are \`yes' or \`no'. configure sets the value to" +echo "# \`yes'. If you set it by hand to \`no', the line will be retained" +echo "# when the file is regenerated in future." +echo "#" +echo "# Note that the \`functions' entry extends to the end of the line." +echo "# It should not be quoted; it is used verbatim to find files to install." +echo "#" +echo "# You will need to run \`config.status --recheck' if you add a new" +echo "# module." +echo "#" +echo "# You should not change the values for the pseudo-module zsh/main," +echo "# which is the main shell (apart from the functions entry)." +EOM +for modfile in `cd ${srcdir}; echo */*.mdd */*/*.mdd`; do + name= + link= + load= + functions= + result= + . ${srcdir}/$modfile + if test x$name != x && test x"$link" != x; then + case "$link" in + *\ *) eval "link=\`$link\`" + ;; + esac + case "${load}" in + y*) load=" load=yes" + ;; + *) load=" load=no" + ;; + esac + if test "x$functions" != x; then + # N.B. no additional quotes + f=" functions=$functions" + else + f= + fi + case "$link" in + static) result="name=$name modfile=$modfile link=static auto=yes${load}$f" + ;; + dynamic) if test x$dynamic != xno; then + result="name=$name modfile=$modfile link=dynamic\ + auto=yes${load}$f" + else + result="name=$name modfile=$modfile link=no\ + auto=yes load=no$f" + fi + ;; + either) if test x$dynamic != xno; then + result="name=$name modfile=$modfile link=dynamic\ + auto=yes${load}$f" + else + result="name=$name modfile=$modfile link=static\ + auto=yes${load}$f" + fi + ;; + *) result="name=$name modfile=$modfile link=no auto=yes load=no$f" + ;; + esac +cat <> ${CONFIG_MODULES}.sh +case "\$userlist" in + *" $name "*) grep "^name=$name " \${CONFIG_MODULES}.old;; + *) echo "$result";; +esac +EOM + fi +done +cat <<\EOM >> ${CONFIG_MODULES}.sh +) >${CONFIG_MODULES} +rm -f ${CONFIG_MODULES}.old +EOM + + + +CLEAN_MK="${srcdir}/Config/clean.mk" +CONFIG_MK="${srcdir}/Config/config.mk" +DEFS_MK="Config/defs.mk" +VERSION_MK="${srcdir}/Config/version.mk" + + +ac_config_files="$ac_config_files Config/defs.mk Makefile Src/Makefile Test/Makefile" + +ac_config_commands="$ac_config_commands config.modules" + +ac_config_commands="$ac_config_commands stamp-h" + + +cat >confcache <<\_ACEOF +# This file is a shell script that caches the results of configure +# tests run on this system so they can be shared between configure +# scripts and configure runs, see configure's option --config-cache. +# It is not useful on other systems. If it contains results you don't +# want to keep, you may remove or edit it. +# +# config.status only pays attention to the cache file if you give it +# the --recheck option to rerun configure. +# +# `ac_cv_env_foo' variables (set or unset) will be overridden when +# loading this file, other *unset* `ac_cv_foo' will be assigned the +# following values. + +_ACEOF + +# The following way of writing the cache mishandles newlines in values, +# but we know of no workaround that is simple, portable, and efficient. +# So, we kill variables containing newlines. +# Ultrix sh set writes to stderr and can't be redirected directly, +# and sets the high bit in the cache file unless we assign to the vars. +( + for ac_var in `(set) 2>&1 | sed -n 's/^\([a-zA-Z_][a-zA-Z0-9_]*\)=.*/\1/p'`; do + eval ac_val=\$$ac_var + case $ac_val in #( + *${as_nl}*) + case $ac_var in #( + *_cv_*) { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: cache variable $ac_var contains a newline" >&5 +$as_echo "$as_me: WARNING: cache variable $ac_var contains a newline" >&2;} ;; + esac + case $ac_var in #( + _ | IFS | as_nl) ;; #( + BASH_ARGV | BASH_SOURCE) eval $ac_var= ;; #( + *) { eval $ac_var=; unset $ac_var;} ;; + esac ;; + esac + done + + (set) 2>&1 | + case $as_nl`(ac_space=' '; set) 2>&1` in #( + *${as_nl}ac_space=\ *) + # `set' does not quote correctly, so add quotes: double-quote + # substitution turns \\\\ into \\, and sed turns \\ into \. + sed -n \ + "s/'/'\\\\''/g; + s/^\\([_$as_cr_alnum]*_cv_[_$as_cr_alnum]*\\)=\\(.*\\)/\\1='\\2'/p" + ;; #( + *) + # `set' quotes correctly as required by POSIX, so do not add quotes. + sed -n "/^[_$as_cr_alnum]*_cv_[_$as_cr_alnum]*=/p" + ;; + esac | + sort +) | + sed ' + /^ac_cv_env_/b end + t clear + :clear + s/^\([^=]*\)=\(.*[{}].*\)$/test "${\1+set}" = set || &/ + t end + s/^\([^=]*\)=\(.*\)$/\1=${\1=\2}/ + :end' >>confcache +if diff "$cache_file" confcache >/dev/null 2>&1; then :; else + if test -w "$cache_file"; then + if test "x$cache_file" != "x/dev/null"; then + { $as_echo "$as_me:${as_lineno-$LINENO}: updating cache $cache_file" >&5 +$as_echo "$as_me: updating cache $cache_file" >&6;} + if test ! -f "$cache_file" || test -h "$cache_file"; then + cat confcache >"$cache_file" + else + case $cache_file in #( + */* | ?:*) + mv -f confcache "$cache_file"$$ && + mv -f "$cache_file"$$ "$cache_file" ;; #( + *) + mv -f confcache "$cache_file" ;; + esac + fi + fi + else + { $as_echo "$as_me:${as_lineno-$LINENO}: not updating unwritable cache $cache_file" >&5 +$as_echo "$as_me: not updating unwritable cache $cache_file" >&6;} + fi +fi +rm -f confcache + +test "x$prefix" = xNONE && prefix=$ac_default_prefix +# Let make expand exec_prefix. +test "x$exec_prefix" = xNONE && exec_prefix='${prefix}' + +DEFS=-DHAVE_CONFIG_H + +ac_libobjs= +ac_ltlibobjs= +U= +for ac_i in : $LIBOBJS; do test "x$ac_i" = x: && continue + # 1. Remove the extension, and $U if already installed. + ac_script='s/\$U\././;s/\.o$//;s/\.obj$//' + ac_i=`$as_echo "$ac_i" | sed "$ac_script"` + # 2. Prepend LIBOBJDIR. When used with automake>=1.10 LIBOBJDIR + # will be set to the directory where LIBOBJS objects are built. + as_fn_append ac_libobjs " \${LIBOBJDIR}$ac_i\$U.$ac_objext" + as_fn_append ac_ltlibobjs " \${LIBOBJDIR}$ac_i"'$U.lo' +done +LIBOBJS=$ac_libobjs + +LTLIBOBJS=$ac_ltlibobjs + + + +: "${CONFIG_STATUS=./config.status}" +ac_write_fail=0 +ac_clean_files_save=$ac_clean_files +ac_clean_files="$ac_clean_files $CONFIG_STATUS" +{ $as_echo "$as_me:${as_lineno-$LINENO}: creating $CONFIG_STATUS" >&5 +$as_echo "$as_me: creating $CONFIG_STATUS" >&6;} +as_write_fail=0 +cat >$CONFIG_STATUS <<_ASEOF || as_write_fail=1 +#! $SHELL +# Generated by $as_me. +# Run this file to recreate the current configuration. +# Compiler output produced by configure, useful for debugging +# configure, is in config.log if it exists. + +debug=false +ac_cs_recheck=false +ac_cs_silent=false + +SHELL=\${CONFIG_SHELL-$SHELL} +export SHELL +_ASEOF +cat >>$CONFIG_STATUS <<\_ASEOF || as_write_fail=1 +## -------------------- ## +## M4sh Initialization. ## +## -------------------- ## + +# Be more Bourne compatible +DUALCASE=1; export DUALCASE # for MKS sh +if test -n "${ZSH_VERSION+set}" && (emulate sh) >/dev/null 2>&1; then : + emulate sh + NULLCMD=: + # Pre-4.2 versions of Zsh do word splitting on ${1+"$@"}, which + # is contrary to our usage. Disable this feature. + alias -g '${1+"$@"}'='"$@"' + setopt NO_GLOB_SUBST +else + case `(set -o) 2>/dev/null` in #( + *posix*) : + set -o posix ;; #( + *) : + ;; +esac +fi + + +as_nl=' +' +export as_nl +# Printing a long string crashes Solaris 7 /usr/bin/printf. +as_echo='\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\' +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo +as_echo=$as_echo$as_echo$as_echo$as_echo$as_echo$as_echo +# Prefer a ksh shell builtin over an external printf program on Solaris, +# but without wasting forks for bash or zsh. +if test -z "$BASH_VERSION$ZSH_VERSION" \ + && (test "X`print -r -- $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='print -r --' + as_echo_n='print -rn --' +elif (test "X`printf %s $as_echo`" = "X$as_echo") 2>/dev/null; then + as_echo='printf %s\n' + as_echo_n='printf %s' +else + if test "X`(/usr/ucb/echo -n -n $as_echo) 2>/dev/null`" = "X-n $as_echo"; then + as_echo_body='eval /usr/ucb/echo -n "$1$as_nl"' + as_echo_n='/usr/ucb/echo -n' + else + as_echo_body='eval expr "X$1" : "X\\(.*\\)"' + as_echo_n_body='eval + arg=$1; + case $arg in #( + *"$as_nl"*) + expr "X$arg" : "X\\(.*\\)$as_nl"; + arg=`expr "X$arg" : ".*$as_nl\\(.*\\)"`;; + esac; + expr "X$arg" : "X\\(.*\\)" | tr -d "$as_nl" + ' + export as_echo_n_body + as_echo_n='sh -c $as_echo_n_body as_echo' + fi + export as_echo_body + as_echo='sh -c $as_echo_body as_echo' +fi + +# The user is always right. +if test "${PATH_SEPARATOR+set}" != set; then + PATH_SEPARATOR=: + (PATH='/bin;/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 && { + (PATH='/bin:/bin'; FPATH=$PATH; sh -c :) >/dev/null 2>&1 || + PATH_SEPARATOR=';' + } +fi + + +# IFS +# We need space, tab and new line, in precisely that order. Quoting is +# there to prevent editors from complaining about space-tab. +# (If _AS_PATH_WALK were called with IFS unset, it would disable word +# splitting by setting IFS to empty value.) +IFS=" "" $as_nl" + +# Find who we are. Look in the path if we contain no directory separator. +as_myself= +case $0 in #(( + *[\\/]* ) as_myself=$0 ;; + *) as_save_IFS=$IFS; IFS=$PATH_SEPARATOR +for as_dir in $PATH +do + IFS=$as_save_IFS + test -z "$as_dir" && as_dir=. + test -r "$as_dir/$0" && as_myself=$as_dir/$0 && break + done +IFS=$as_save_IFS + + ;; +esac +# We did not find ourselves, most probably we were run as `sh COMMAND' +# in which case we are not to be found in the path. +if test "x$as_myself" = x; then + as_myself=$0 +fi +if test ! -f "$as_myself"; then + $as_echo "$as_myself: error: cannot find myself; rerun with an absolute file name" >&2 + exit 1 +fi + +# Unset variables that we do not need and which cause bugs (e.g. in +# pre-3.0 UWIN ksh). But do not cause bugs in bash 2.01; the "|| exit 1" +# suppresses any "Segmentation fault" message there. '((' could +# trigger a bug in pdksh 5.2.14. +for as_var in BASH_ENV ENV MAIL MAILPATH +do eval test x\${$as_var+set} = xset \ + && ( (unset $as_var) || exit 1) >/dev/null 2>&1 && unset $as_var || : +done +PS1='$ ' +PS2='> ' +PS4='+ ' + +# NLS nuisances. +LC_ALL=C +export LC_ALL +LANGUAGE=C +export LANGUAGE + +# CDPATH. +(unset CDPATH) >/dev/null 2>&1 && unset CDPATH + + +# as_fn_error STATUS ERROR [LINENO LOG_FD] +# ---------------------------------------- +# Output "`basename $0`: error: ERROR" to stderr. If LINENO and LOG_FD are +# provided, also output the error to LOG_FD, referencing LINENO. Then exit the +# script with STATUS, using 1 if that was 0. +as_fn_error () +{ + as_status=$1; test $as_status -eq 0 && as_status=1 + if test "$4"; then + as_lineno=${as_lineno-"$3"} as_lineno_stack=as_lineno_stack=$as_lineno_stack + $as_echo "$as_me:${as_lineno-$LINENO}: error: $2" >&$4 + fi + $as_echo "$as_me: error: $2" >&2 + as_fn_exit $as_status +} # as_fn_error + + +# as_fn_set_status STATUS +# ----------------------- +# Set $? to STATUS, without forking. +as_fn_set_status () +{ + return $1 +} # as_fn_set_status + +# as_fn_exit STATUS +# ----------------- +# Exit the shell with STATUS, even in a "trap 0" or "set -e" context. +as_fn_exit () +{ + set +e + as_fn_set_status $1 + exit $1 +} # as_fn_exit + +# as_fn_unset VAR +# --------------- +# Portably unset VAR. +as_fn_unset () +{ + { eval $1=; unset $1;} +} +as_unset=as_fn_unset +# as_fn_append VAR VALUE +# ---------------------- +# Append the text in VALUE to the end of the definition contained in VAR. Take +# advantage of any shell optimizations that allow amortized linear growth over +# repeated appends, instead of the typical quadratic growth present in naive +# implementations. +if (eval "as_var=1; as_var+=2; test x\$as_var = x12") 2>/dev/null; then : + eval 'as_fn_append () + { + eval $1+=\$2 + }' +else + as_fn_append () + { + eval $1=\$$1\$2 + } +fi # as_fn_append + +# as_fn_arith ARG... +# ------------------ +# Perform arithmetic evaluation on the ARGs, and store the result in the +# global $as_val. Take advantage of shells that can avoid forks. The arguments +# must be portable across $(()) and expr. +if (eval "test \$(( 1 + 1 )) = 2") 2>/dev/null; then : + eval 'as_fn_arith () + { + as_val=$(( $* )) + }' +else + as_fn_arith () + { + as_val=`expr "$@" || test $? -eq 1` + } +fi # as_fn_arith + + +if expr a : '\(a\)' >/dev/null 2>&1 && + test "X`expr 00001 : '.*\(...\)'`" = X001; then + as_expr=expr +else + as_expr=false +fi + +if (basename -- /) >/dev/null 2>&1 && test "X`basename -- / 2>&1`" = "X/"; then + as_basename=basename +else + as_basename=false +fi + +if (as_dir=`dirname -- /` && test "X$as_dir" = X/) >/dev/null 2>&1; then + as_dirname=dirname +else + as_dirname=false +fi + +as_me=`$as_basename -- "$0" || +$as_expr X/"$0" : '.*/\([^/][^/]*\)/*$' \| \ + X"$0" : 'X\(//\)$' \| \ + X"$0" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X/"$0" | + sed '/^.*\/\([^/][^/]*\)\/*$/{ + s//\1/ + q + } + /^X\/\(\/\/\)$/{ + s//\1/ + q + } + /^X\/\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + +# Avoid depending upon Character Ranges. +as_cr_letters='abcdefghijklmnopqrstuvwxyz' +as_cr_LETTERS='ABCDEFGHIJKLMNOPQRSTUVWXYZ' +as_cr_Letters=$as_cr_letters$as_cr_LETTERS +as_cr_digits='0123456789' +as_cr_alnum=$as_cr_Letters$as_cr_digits + +ECHO_C= ECHO_N= ECHO_T= +case `echo -n x` in #((((( +-n*) + case `echo 'xy\c'` in + *c*) ECHO_T=' ';; # ECHO_T is single tab character. + xy) ECHO_C='\c';; + *) echo `echo ksh88 bug on AIX 6.1` > /dev/null + ECHO_T=' ';; + esac;; +*) + ECHO_N='-n';; +esac + +rm -f conf$$ conf$$.exe conf$$.file +if test -d conf$$.dir; then + rm -f conf$$.dir/conf$$.file +else + rm -f conf$$.dir + mkdir conf$$.dir 2>/dev/null +fi +if (echo >conf$$.file) 2>/dev/null; then + if ln -s conf$$.file conf$$ 2>/dev/null; then + as_ln_s='ln -s' + # ... but there are two gotchas: + # 1) On MSYS, both `ln -s file dir' and `ln file dir' fail. + # 2) DJGPP < 2.04 has no symlinks; `ln -s' creates a wrapper executable. + # In both cases, we have to default to `cp -pR'. + ln -s conf$$.file conf$$.dir 2>/dev/null && test ! -f conf$$.exe || + as_ln_s='cp -pR' + elif ln conf$$.file conf$$ 2>/dev/null; then + as_ln_s=ln + else + as_ln_s='cp -pR' + fi +else + as_ln_s='cp -pR' +fi +rm -f conf$$ conf$$.exe conf$$.dir/conf$$.file conf$$.file +rmdir conf$$.dir 2>/dev/null + + +# as_fn_mkdir_p +# ------------- +# Create "$as_dir" as a directory, including parents if necessary. +as_fn_mkdir_p () +{ + + case $as_dir in #( + -*) as_dir=./$as_dir;; + esac + test -d "$as_dir" || eval $as_mkdir_p || { + as_dirs= + while :; do + case $as_dir in #( + *\'*) as_qdir=`$as_echo "$as_dir" | sed "s/'/'\\\\\\\\''/g"`;; #'( + *) as_qdir=$as_dir;; + esac + as_dirs="'$as_qdir' $as_dirs" + as_dir=`$as_dirname -- "$as_dir" || +$as_expr X"$as_dir" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$as_dir" : 'X\(//\)[^/]' \| \ + X"$as_dir" : 'X\(//\)$' \| \ + X"$as_dir" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$as_dir" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + test -d "$as_dir" && break + done + test -z "$as_dirs" || eval "mkdir $as_dirs" + } || test -d "$as_dir" || as_fn_error $? "cannot create directory $as_dir" + + +} # as_fn_mkdir_p +if mkdir -p . 2>/dev/null; then + as_mkdir_p='mkdir -p "$as_dir"' +else + test -d ./-p && rmdir ./-p + as_mkdir_p=false +fi + + +# as_fn_executable_p FILE +# ----------------------- +# Test if FILE is an executable regular file. +as_fn_executable_p () +{ + test -f "$1" && test -x "$1" +} # as_fn_executable_p +as_test_x='test -x' +as_executable_p=as_fn_executable_p + +# Sed expression to map a string onto a valid CPP name. +as_tr_cpp="eval sed 'y%*$as_cr_letters%P$as_cr_LETTERS%;s%[^_$as_cr_alnum]%_%g'" + +# Sed expression to map a string onto a valid variable name. +as_tr_sh="eval sed 'y%*+%pp%;s%[^_$as_cr_alnum]%_%g'" + + +exec 6>&1 +## ----------------------------------- ## +## Main body of $CONFIG_STATUS script. ## +## ----------------------------------- ## +_ASEOF +test $as_write_fail = 0 && chmod +x $CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# Save the log message, to keep $0 and so on meaningful, and to +# report actual input values of CONFIG_FILES etc. instead of their +# values after options handling. +ac_log=" +This file was extended by $as_me, which was +generated by GNU Autoconf 2.69. Invocation command line was + + CONFIG_FILES = $CONFIG_FILES + CONFIG_HEADERS = $CONFIG_HEADERS + CONFIG_LINKS = $CONFIG_LINKS + CONFIG_COMMANDS = $CONFIG_COMMANDS + $ $0 $@ + +on `(hostname || uname -n) 2>/dev/null | sed 1q` +" + +_ACEOF + +case $ac_config_files in *" +"*) set x $ac_config_files; shift; ac_config_files=$*;; +esac + +case $ac_config_headers in *" +"*) set x $ac_config_headers; shift; ac_config_headers=$*;; +esac + + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +# Files that config.status was made for. +config_files="$ac_config_files" +config_headers="$ac_config_headers" +config_commands="$ac_config_commands" + +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +ac_cs_usage="\ +\`$as_me' instantiates files and other configuration actions +from templates according to the current configuration. Unless the files +and actions are specified as TAGs, all are instantiated by default. + +Usage: $0 [OPTION]... [TAG]... + + -h, --help print this help, then exit + -V, --version print version number and configuration settings, then exit + --config print configuration, then exit + -q, --quiet, --silent + do not print progress messages + -d, --debug don't remove temporary files + --recheck update $as_me by reconfiguring in the same conditions + --file=FILE[:TEMPLATE] + instantiate the configuration file FILE + --header=FILE[:TEMPLATE] + instantiate the configuration header FILE + +Configuration files: +$config_files + +Configuration headers: +$config_headers + +Configuration commands: +$config_commands + +Report bugs to the package provider." + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_cs_config="`$as_echo "$ac_configure_args" | sed 's/^ //; s/[\\""\`\$]/\\\\&/g'`" +ac_cs_version="\\ +config.status +configured by $0, generated by GNU Autoconf 2.69, + with options \\"\$ac_cs_config\\" + +Copyright (C) 2012 Free Software Foundation, Inc. +This config.status script is free software; the Free Software Foundation +gives unlimited permission to copy, distribute and modify it." + +ac_pwd='$ac_pwd' +srcdir='$srcdir' +INSTALL='$INSTALL' +AWK='$AWK' +test -n "\$AWK" || AWK=awk +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# The default lists apply if the user does not specify any file. +ac_need_defaults=: +while test $# != 0 +do + case $1 in + --*=?*) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg=`expr "X$1" : 'X[^=]*=\(.*\)'` + ac_shift=: + ;; + --*=) + ac_option=`expr "X$1" : 'X\([^=]*\)='` + ac_optarg= + ac_shift=: + ;; + *) + ac_option=$1 + ac_optarg=$2 + ac_shift=shift + ;; + esac + + case $ac_option in + # Handling of the options. + -recheck | --recheck | --rechec | --reche | --rech | --rec | --re | --r) + ac_cs_recheck=: ;; + --version | --versio | --versi | --vers | --ver | --ve | --v | -V ) + $as_echo "$ac_cs_version"; exit ;; + --config | --confi | --conf | --con | --co | --c ) + $as_echo "$ac_cs_config"; exit ;; + --debug | --debu | --deb | --de | --d | -d ) + debug=: ;; + --file | --fil | --fi | --f ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + '') as_fn_error $? "missing file argument" ;; + esac + as_fn_append CONFIG_FILES " '$ac_optarg'" + ac_need_defaults=false;; + --header | --heade | --head | --hea ) + $ac_shift + case $ac_optarg in + *\'*) ac_optarg=`$as_echo "$ac_optarg" | sed "s/'/'\\\\\\\\''/g"` ;; + esac + as_fn_append CONFIG_HEADERS " '$ac_optarg'" + ac_need_defaults=false;; + --he | --h) + # Conflict between --help and --header + as_fn_error $? "ambiguous option: \`$1' +Try \`$0 --help' for more information.";; + --help | --hel | -h ) + $as_echo "$ac_cs_usage"; exit ;; + -q | -quiet | --quiet | --quie | --qui | --qu | --q \ + | -silent | --silent | --silen | --sile | --sil | --si | --s) + ac_cs_silent=: ;; + + # This is an error. + -*) as_fn_error $? "unrecognized option: \`$1' +Try \`$0 --help' for more information." ;; + + *) as_fn_append ac_config_targets " $1" + ac_need_defaults=false ;; + + esac + shift +done + +ac_configure_extra_args= + +if $ac_cs_silent; then + exec 6>/dev/null + ac_configure_extra_args="$ac_configure_extra_args --silent" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +if \$ac_cs_recheck; then + set X $SHELL '$0' $ac_configure_args \$ac_configure_extra_args --no-create --no-recursion + shift + \$as_echo "running CONFIG_SHELL=$SHELL \$*" >&6 + CONFIG_SHELL='$SHELL' + export CONFIG_SHELL + exec "\$@" +fi + +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +exec 5>>config.log +{ + echo + sed 'h;s/./-/g;s/^.../## /;s/...$/ ##/;p;x;p;x' <<_ASBOX +## Running $as_me. ## +_ASBOX + $as_echo "$ac_log" +} >&5 + +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + +# Handling of arguments. +for ac_config_target in $ac_config_targets +do + case $ac_config_target in + "config.h") CONFIG_HEADERS="$CONFIG_HEADERS config.h" ;; + "Config/defs.mk") CONFIG_FILES="$CONFIG_FILES Config/defs.mk" ;; + "Makefile") CONFIG_FILES="$CONFIG_FILES Makefile" ;; + "Src/Makefile") CONFIG_FILES="$CONFIG_FILES Src/Makefile" ;; + "Test/Makefile") CONFIG_FILES="$CONFIG_FILES Test/Makefile" ;; + "config.modules") CONFIG_COMMANDS="$CONFIG_COMMANDS config.modules" ;; + "stamp-h") CONFIG_COMMANDS="$CONFIG_COMMANDS stamp-h" ;; + + *) as_fn_error $? "invalid argument: \`$ac_config_target'" "$LINENO" 5;; + esac +done + + +# If the user did not use the arguments to specify the items to instantiate, +# then the envvar interface is used. Set only those that are not. +# We use the long form for the default assignment because of an extremely +# bizarre bug on SunOS 4.1.3. +if $ac_need_defaults; then + test "${CONFIG_FILES+set}" = set || CONFIG_FILES=$config_files + test "${CONFIG_HEADERS+set}" = set || CONFIG_HEADERS=$config_headers + test "${CONFIG_COMMANDS+set}" = set || CONFIG_COMMANDS=$config_commands +fi + +# Have a temporary directory for convenience. Make it in the build tree +# simply because there is no reason against having it here, and in addition, +# creating and moving files from /tmp can sometimes cause problems. +# Hook for its removal unless debugging. +# Note that there is a small window in which the directory will not be cleaned: +# after its creation but before its name has been assigned to `$tmp'. +$debug || +{ + tmp= ac_tmp= + trap 'exit_status=$? + : "${ac_tmp:=$tmp}" + { test ! -d "$ac_tmp" || rm -fr "$ac_tmp"; } && exit $exit_status +' 0 + trap 'as_fn_exit 1' 1 2 13 15 +} +# Create a (secure) tmp directory for tmp files. + +{ + tmp=`(umask 077 && mktemp -d "./confXXXXXX") 2>/dev/null` && + test -d "$tmp" +} || +{ + tmp=./conf$$-$RANDOM + (umask 077 && mkdir "$tmp") +} || as_fn_error $? "cannot create a temporary directory in ." "$LINENO" 5 +ac_tmp=$tmp + +# Set up the scripts for CONFIG_FILES section. +# No need to generate them if there are no CONFIG_FILES. +# This happens for instance with `./config.status config.h'. +if test -n "$CONFIG_FILES"; then + +if $AWK 'BEGIN { getline <"/dev/null" }' /dev/null; then + ac_cs_awk_getline=: + ac_cs_awk_pipe_init= + ac_cs_awk_read_file=' + while ((getline aline < (F[key])) > 0) + print(aline) + close(F[key])' + ac_cs_awk_pipe_fini= +else + ac_cs_awk_getline=false + ac_cs_awk_pipe_init="print \"cat <<'|#_!!_#|' &&\"" + ac_cs_awk_read_file=' + print "|#_!!_#|" + print "cat " F[key] " &&" + '$ac_cs_awk_pipe_init + # The final `:' finishes the AND list. + ac_cs_awk_pipe_fini='END { print "|#_!!_#|"; print ":" }' +fi +ac_cr=`echo X | tr X '\015'` +# On cygwin, bash can eat \r inside `` if the user requested igncr. +# But we know of no other shell where ac_cr would be empty at this +# point, so we can use a bashism as a fallback. +if test "x$ac_cr" = x; then + eval ac_cr=\$\'\\r\' +fi +ac_cs_awk_cr=`$AWK 'BEGIN { print "a\rb" }' /dev/null` +if test "$ac_cs_awk_cr" = "a${ac_cr}b"; then + ac_cs_awk_cr='\\r' +else + ac_cs_awk_cr=$ac_cr +fi + +echo 'BEGIN {' >"$ac_tmp/subs1.awk" && +_ACEOF + +# Create commands to substitute file output variables. +{ + echo "cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1" && + echo 'cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK &&' && + echo "$ac_subst_files" | sed 's/.*/F["&"]="$&"/' && + echo "_ACAWK" && + echo "_ACEOF" +} >conf$$files.sh && +. ./conf$$files.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 +rm -f conf$$files.sh + +{ + echo "cat >conf$$subs.awk <<_ACEOF" && + echo "$ac_subst_vars" | sed 's/.*/&!$&$ac_delim/' && + echo "_ACEOF" +} >conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 +ac_delim_num=`echo "$ac_subst_vars" | grep -c '^'` +ac_delim='%!_!# ' +for ac_last_try in false false false false false :; do + . ./conf$$subs.sh || + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + + ac_delim_n=`sed -n "s/.*$ac_delim\$/X/p" conf$$subs.awk | grep -c X` + if test $ac_delim_n = $ac_delim_num; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_STATUS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done +rm -f conf$$subs.sh + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +cat >>"\$ac_tmp/subs1.awk" <<\\_ACAWK && +_ACEOF +sed -n ' +h +s/^/S["/; s/!.*/"]=/ +p +g +s/^[^!]*!// +:repl +t repl +s/'"$ac_delim"'$// +t delim +:nl +h +s/\(.\{148\}\)..*/\1/ +t more1 +s/["\\]/\\&/g; s/^/"/; s/$/\\n"\\/ +p +n +b repl +:more1 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t nl +:delim +h +s/\(.\{148\}\)..*/\1/ +t more2 +s/["\\]/\\&/g; s/^/"/; s/$/"/ +p +b +:more2 +s/["\\]/\\&/g; s/^/"/; s/$/"\\/ +p +g +s/.\{148\}// +t delim +' >$CONFIG_STATUS || ac_write_fail=1 +rm -f conf$$subs.awk +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +_ACAWK +cat >>"\$ac_tmp/subs1.awk" <<_ACAWK && + for (key in S) S_is_set[key] = 1 + FS = "" + \$ac_cs_awk_pipe_init +} +{ + line = $ 0 + nfields = split(line, field, "@") + substed = 0 + len = length(field[1]) + for (i = 2; i < nfields; i++) { + key = field[i] + keylen = length(key) + if (S_is_set[key]) { + value = S[key] + line = substr(line, 1, len) "" value "" substr(line, len + keylen + 3) + len += length(value) + length(field[++i]) + substed = 1 + } else + len += 1 + keylen + } + if (nfields == 3 && !substed) { + key = field[2] + if (F[key] != "" && line ~ /^[ ]*@.*@[ ]*$/) { + \$ac_cs_awk_read_file + next + } + } + print line +} +\$ac_cs_awk_pipe_fini +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +if sed "s/$ac_cr//" < /dev/null > /dev/null 2>&1; then + sed "s/$ac_cr\$//; s/$ac_cr/$ac_cs_awk_cr/g" +else + cat +fi < "$ac_tmp/subs1.awk" > "$ac_tmp/subs.awk" \ + || as_fn_error $? "could not setup config files machinery" "$LINENO" 5 +_ACEOF + +# VPATH may cause trouble with some makes, so we remove sole $(srcdir), +# ${srcdir} and @srcdir@ entries from VPATH if srcdir is ".", strip leading and +# trailing colons and then remove the whole line if VPATH becomes empty +# (actually we leave an empty line to preserve line numbers). +if test "x$srcdir" = x.; then + ac_vpsub='/^[ ]*VPATH[ ]*=[ ]*/{ +h +s/// +s/^/:/ +s/[ ]*$/:/ +s/:\$(srcdir):/:/g +s/:\${srcdir}:/:/g +s/:@srcdir@:/:/g +s/^:*// +s/:*$// +x +s/\(=[ ]*\).*/\1/ +G +s/\n// +s/^[^=]*=[ ]*$// +}' +fi + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +fi # test -n "$CONFIG_FILES" + +# Set up the scripts for CONFIG_HEADERS section. +# No need to generate them if there are no CONFIG_HEADERS. +# This happens for instance with `./config.status Makefile'. +if test -n "$CONFIG_HEADERS"; then +cat >"$ac_tmp/defines.awk" <<\_ACAWK || +BEGIN { +_ACEOF + +# Transform confdefs.h into an awk script `defines.awk', embedded as +# here-document in config.status, that substitutes the proper values into +# config.h.in to produce config.h. + +# Create a delimiter string that does not exist in confdefs.h, to ease +# handling of long lines. +ac_delim='%!_!# ' +for ac_last_try in false false :; do + ac_tt=`sed -n "/$ac_delim/p" confdefs.h` + if test -z "$ac_tt"; then + break + elif $ac_last_try; then + as_fn_error $? "could not make $CONFIG_HEADERS" "$LINENO" 5 + else + ac_delim="$ac_delim!$ac_delim _$ac_delim!! " + fi +done + +# For the awk script, D is an array of macro values keyed by name, +# likewise P contains macro parameters if any. Preserve backslash +# newline sequences. + +ac_word_re=[_$as_cr_Letters][_$as_cr_alnum]* +sed -n ' +s/.\{148\}/&'"$ac_delim"'/g +t rset +:rset +s/^[ ]*#[ ]*define[ ][ ]*/ / +t def +d +:def +s/\\$// +t bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3"/p +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2"/p +d +:bsnl +s/["\\]/\\&/g +s/^ \('"$ac_word_re"'\)\(([^()]*)\)[ ]*\(.*\)/P["\1"]="\2"\ +D["\1"]=" \3\\\\\\n"\\/p +t cont +s/^ \('"$ac_word_re"'\)[ ]*\(.*\)/D["\1"]=" \2\\\\\\n"\\/p +t cont +d +:cont +n +s/.\{148\}/&'"$ac_delim"'/g +t clear +:clear +s/\\$// +t bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/"/p +d +:bsnlc +s/["\\]/\\&/g; s/^/"/; s/$/\\\\\\n"\\/p +b cont +' >$CONFIG_STATUS || ac_write_fail=1 + +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + for (key in D) D_is_set[key] = 1 + FS = "" +} +/^[\t ]*#[\t ]*(define|undef)[\t ]+$ac_word_re([\t (]|\$)/ { + line = \$ 0 + split(line, arg, " ") + if (arg[1] == "#") { + defundef = arg[2] + mac1 = arg[3] + } else { + defundef = substr(arg[1], 2) + mac1 = arg[2] + } + split(mac1, mac2, "(") #) + macro = mac2[1] + prefix = substr(line, 1, index(line, defundef) - 1) + if (D_is_set[macro]) { + # Preserve the white space surrounding the "#". + print prefix "define", macro P[macro] D[macro] + next + } else { + # Replace #undef with comments. This is necessary, for example, + # in the case of _POSIX_SOURCE, which is predefined and required + # on some systems where configure will not decide to define it. + if (defundef == "undef") { + print "/*", prefix defundef, macro, "*/" + next + } + } +} +{ print } +_ACAWK +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 + as_fn_error $? "could not setup config headers machinery" "$LINENO" 5 +fi # test -n "$CONFIG_HEADERS" + + +eval set X " :F $CONFIG_FILES :H $CONFIG_HEADERS :C $CONFIG_COMMANDS" +shift +for ac_tag +do + case $ac_tag in + :[FHLC]) ac_mode=$ac_tag; continue;; + esac + case $ac_mode$ac_tag in + :[FHL]*:*);; + :L* | :C*:*) as_fn_error $? "invalid tag \`$ac_tag'" "$LINENO" 5;; + :[FH]-) ac_tag=-:-;; + :[FH]*) ac_tag=$ac_tag:$ac_tag.in;; + esac + ac_save_IFS=$IFS + IFS=: + set x $ac_tag + IFS=$ac_save_IFS + shift + ac_file=$1 + shift + + case $ac_mode in + :L) ac_source=$1;; + :[FH]) + ac_file_inputs= + for ac_f + do + case $ac_f in + -) ac_f="$ac_tmp/stdin";; + *) # Look for the file first in the build tree, then in the source tree + # (if the path is not absolute). The absolute path cannot be DOS-style, + # because $ac_f cannot contain `:'. + test -f "$ac_f" || + case $ac_f in + [\\/$]*) false;; + *) test -f "$srcdir/$ac_f" && ac_f="$srcdir/$ac_f";; + esac || + as_fn_error 1 "cannot find input file: \`$ac_f'" "$LINENO" 5;; + esac + case $ac_f in *\'*) ac_f=`$as_echo "$ac_f" | sed "s/'/'\\\\\\\\''/g"`;; esac + as_fn_append ac_file_inputs " '$ac_f'" + done + + # Let's still pretend it is `configure' which instantiates (i.e., don't + # use $as_me), people would be surprised to read: + # /* config.h. Generated by config.status. */ + configure_input='Generated from '` + $as_echo "$*" | sed 's|^[^:]*/||;s|:[^:]*/|, |g' + `' by configure.' + if test x"$ac_file" != x-; then + configure_input="$ac_file. $configure_input" + { $as_echo "$as_me:${as_lineno-$LINENO}: creating $ac_file" >&5 +$as_echo "$as_me: creating $ac_file" >&6;} + fi + # Neutralize special characters interpreted by sed in replacement strings. + case $configure_input in #( + *\&* | *\|* | *\\* ) + ac_sed_conf_input=`$as_echo "$configure_input" | + sed 's/[\\\\&|]/\\\\&/g'`;; #( + *) ac_sed_conf_input=$configure_input;; + esac + + case $ac_tag in + *:-:* | *:-) cat >"$ac_tmp/stdin" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 ;; + esac + ;; + esac + + ac_dir=`$as_dirname -- "$ac_file" || +$as_expr X"$ac_file" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$ac_file" : 'X\(//\)[^/]' \| \ + X"$ac_file" : 'X\(//\)$' \| \ + X"$ac_file" : 'X\(/\)' \| . 2>/dev/null || +$as_echo X"$ac_file" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q'` + as_dir="$ac_dir"; as_fn_mkdir_p + ac_builddir=. + +case "$ac_dir" in +.) ac_dir_suffix= ac_top_builddir_sub=. ac_top_build_prefix= ;; +*) + ac_dir_suffix=/`$as_echo "$ac_dir" | sed 's|^\.[\\/]||'` + # A ".." for each directory in $ac_dir_suffix. + ac_top_builddir_sub=`$as_echo "$ac_dir_suffix" | sed 's|/[^\\/]*|/..|g;s|/||'` + case $ac_top_builddir_sub in + "") ac_top_builddir_sub=. ac_top_build_prefix= ;; + *) ac_top_build_prefix=$ac_top_builddir_sub/ ;; + esac ;; +esac +ac_abs_top_builddir=$ac_pwd +ac_abs_builddir=$ac_pwd$ac_dir_suffix +# for backward compatibility: +ac_top_builddir=$ac_top_build_prefix + +case $srcdir in + .) # We are building in place. + ac_srcdir=. + ac_top_srcdir=$ac_top_builddir_sub + ac_abs_top_srcdir=$ac_pwd ;; + [\\/]* | ?:[\\/]* ) # Absolute name. + ac_srcdir=$srcdir$ac_dir_suffix; + ac_top_srcdir=$srcdir + ac_abs_top_srcdir=$srcdir ;; + *) # Relative name. + ac_srcdir=$ac_top_build_prefix$srcdir$ac_dir_suffix + ac_top_srcdir=$ac_top_build_prefix$srcdir + ac_abs_top_srcdir=$ac_pwd/$srcdir ;; +esac +ac_abs_srcdir=$ac_abs_top_srcdir$ac_dir_suffix + + + case $ac_mode in + :F) + # + # CONFIG_FILE + # + + case $INSTALL in + [\\/$]* | ?:[\\/]* ) ac_INSTALL=$INSTALL ;; + *) ac_INSTALL=$ac_top_build_prefix$INSTALL ;; + esac +_ACEOF + +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +# If the template does not know about datarootdir, expand it. +# FIXME: This hack should be removed a few years after 2.60. +ac_datarootdir_hack=; ac_datarootdir_seen= +ac_sed_dataroot=' +/datarootdir/ { + p + q +} +/@datadir@/p +/@docdir@/p +/@infodir@/p +/@localedir@/p +/@mandir@/p' +case `eval "sed -n \"\$ac_sed_dataroot\" $ac_file_inputs"` in +*datarootdir*) ac_datarootdir_seen=yes;; +*@datadir@*|*@docdir@*|*@infodir@*|*@localedir@*|*@mandir@*) + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&5 +$as_echo "$as_me: WARNING: $ac_file_inputs seems to ignore the --datarootdir setting" >&2;} +_ACEOF +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 + ac_datarootdir_hack=' + s&@datadir@&$datadir&g + s&@docdir@&$docdir&g + s&@infodir@&$infodir&g + s&@localedir@&$localedir&g + s&@mandir@&$mandir&g + s&\\\${datarootdir}&$datarootdir&g' ;; +esac +_ACEOF + +# Neutralize VPATH when `$srcdir' = `.'. +# Shell code in configure.ac might set extrasub. +# FIXME: do we really want to maintain this feature? +cat >>$CONFIG_STATUS <<_ACEOF || ac_write_fail=1 +ac_sed_extra="$ac_vpsub +$extrasub +_ACEOF +cat >>$CONFIG_STATUS <<\_ACEOF || ac_write_fail=1 +:t +/@[a-zA-Z_][a-zA-Z_0-9]*@/!b +s|@configure_input@|$ac_sed_conf_input|;t t +s&@top_builddir@&$ac_top_builddir_sub&;t t +s&@top_build_prefix@&$ac_top_build_prefix&;t t +s&@srcdir@&$ac_srcdir&;t t +s&@abs_srcdir@&$ac_abs_srcdir&;t t +s&@top_srcdir@&$ac_top_srcdir&;t t +s&@abs_top_srcdir@&$ac_abs_top_srcdir&;t t +s&@builddir@&$ac_builddir&;t t +s&@abs_builddir@&$ac_abs_builddir&;t t +s&@abs_top_builddir@&$ac_abs_top_builddir&;t t +s&@INSTALL@&$ac_INSTALL&;t t +$ac_datarootdir_hack +" +eval sed \"\$ac_sed_extra\" "$ac_file_inputs" | +if $ac_cs_awk_getline; then + $AWK -f "$ac_tmp/subs.awk" +else + $AWK -f "$ac_tmp/subs.awk" | $SHELL +fi \ + >$ac_tmp/out || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + +test -z "$ac_datarootdir_hack$ac_datarootdir_seen" && + { ac_out=`sed -n '/\${datarootdir}/p' "$ac_tmp/out"`; test -n "$ac_out"; } && + { ac_out=`sed -n '/^[ ]*datarootdir[ ]*:*=/p' \ + "$ac_tmp/out"`; test -z "$ac_out"; } && + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&5 +$as_echo "$as_me: WARNING: $ac_file contains a reference to the variable \`datarootdir' +which seems to be undefined. Please make sure it is defined" >&2;} + + rm -f "$ac_tmp/stdin" + case $ac_file in + -) cat "$ac_tmp/out" && rm -f "$ac_tmp/out";; + *) rm -f "$ac_file" && mv "$ac_tmp/out" "$ac_file";; + esac \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + ;; + :H) + # + # CONFIG_HEADER + # + if test x"$ac_file" != x-; then + { + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" + } >"$ac_tmp/config.h" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + if diff "$ac_file" "$ac_tmp/config.h" >/dev/null 2>&1; then + { $as_echo "$as_me:${as_lineno-$LINENO}: $ac_file is unchanged" >&5 +$as_echo "$as_me: $ac_file is unchanged" >&6;} + else + rm -f "$ac_file" + mv "$ac_tmp/config.h" "$ac_file" \ + || as_fn_error $? "could not create $ac_file" "$LINENO" 5 + fi + else + $as_echo "/* $configure_input */" \ + && eval '$AWK -f "$ac_tmp/defines.awk"' "$ac_file_inputs" \ + || as_fn_error $? "could not create -" "$LINENO" 5 + fi + ;; + + :C) { $as_echo "$as_me:${as_lineno-$LINENO}: executing $ac_file commands" >&5 +$as_echo "$as_me: executing $ac_file commands" >&6;} + ;; + esac + + + case $ac_file$ac_mode in + "config.modules":C) . ./config.modules.sh ;; + "stamp-h":C) echo >stamp-h ;; + + esac +done # for ac_tag + + +as_fn_exit 0 +_ACEOF +ac_clean_files=$ac_clean_files_save + +test $ac_write_fail = 0 || + as_fn_error $? "write failure creating $CONFIG_STATUS" "$LINENO" 5 + + +# configure is writing to config.log, and then calls config.status. +# config.status does its own redirection, appending to config.log. +# Unfortunately, on DOS this fails, as config.log is still kept open +# by configure, so config.status won't be able to write to it; its +# output is simply discarded. So we exec the FD to /dev/null, +# effectively closing config.log, so it can be properly (re)opened and +# appended to by config.status. When coming back to configure, we +# need to make the FD available again. +if test "$no_create" != yes; then + ac_cs_success=: + ac_config_status_args= + test "$silent" = yes && + ac_config_status_args="$ac_config_status_args --quiet" + exec 5>/dev/null + $SHELL $CONFIG_STATUS $ac_config_status_args || ac_cs_success=false + exec 5>>config.log + # Use ||, not &&, to avoid exiting from the if with $? = 1, which + # would make configure fail if this is the last instruction. + $ac_cs_success || as_fn_exit 1 +fi +if test -n "$ac_unrecognized_opts" && test "$enable_option_checking" != no; then + { $as_echo "$as_me:${as_lineno-$LINENO}: WARNING: unrecognized options: $ac_unrecognized_opts" >&5 +$as_echo "$as_me: WARNING: unrecognized options: $ac_unrecognized_opts" >&2;} +fi + + +eval "zshbin1=${bindir}" +eval "zshbin2=${zshbin1}" +eval "zshman1=${mandir}" +eval "zshman2=${zshman1}" +eval "zshinfo1=${infodir}" +eval "zshinfo2=${zshinfo1}" +eval "zshfndir1=${fndir}" +eval "zshfndir2=${zshfndir1}" + +echo " +zsh configuration +----------------- +zsh version : ${VERSION} +host operating system : ${host_cpu}-${host_vendor}-${host_os} +source code location : ${srcdir} +compiler : ${CC} +preprocessor flags : ${CPPFLAGS} +executable compiler flags : ${CFLAGS}" +if test "x$dynamic" = xyes; then + echo "\ +module compiler flags : ${CFLAGS} ${DLCFLAGS}" +fi +echo "\ +executable linker flags : ${LDFLAGS} ${EXELDFLAGS} ${EXTRA_LDFLAGS}" +if test "x$dynamic" = xyes; then + echo "\ +module linker flags : ${LDFLAGS} ${LIBLDFLAGS} ${DLLDFLAGS}" +fi +echo "\ +library flags : ${LIBS} +installation basename : ${tzsh_name} +binary install path : ${zshbin2} +man page install path : ${zshman2} +info install path : ${zshinfo2}" +if test "$zshfndir2" != no; then + echo "functions install path : ${zshfndir2}" +fi +if test "x$additionalfpath" != x; then + echo "additional fpath entries : ${additionalfpath}" +fi +echo "See config.modules for installed modules and functions. +" + +case x$LIBS in + *-lgdbm*) + echo "WARNING: zsh will be linked against libgdbm. +This means the binary is covered by the GNU General Public License. +This does not affect the source code. +Run configure with --disable-gdbm if required." + ;; +esac + +exit 0 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/configure.ac b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/configure.ac new file mode 100644 index 00000000..4dd4ebad --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/configure.ac @@ -0,0 +1,3213 @@ +dnl +dnl configure.ac: Configure template for zsh. +dnl Process this file with autoconf to produce a configure script. +dnl +dnl Copyright (c) 1995-1997 Richard Coleman +dnl All rights reserved. +dnl +dnl Permission is hereby granted, without written agreement and without +dnl license or royalty fees, to use, copy, modify, and distribute this +dnl software and to distribute modified versions of this software for any +dnl purpose, provided that the above copyright notice and the following +dnl two paragraphs appear in all copies of this software. +dnl +dnl In no event shall Richard Coleman or the Zsh Development Group be liable +dnl to any party for direct, indirect, special, incidental, or consequential +dnl damages arising out of the use of this software and its documentation, +dnl even if Richard Coleman and the Zsh Development Group have been advised of +dnl the possibility of such damage. +dnl +dnl Richard Coleman and the Zsh Development Group specifically disclaim any +dnl warranties, including, but not limited to, the implied warranties of +dnl merchantability and fitness for a particular purpose. The software +dnl provided hereunder is on an "as is" basis, and Richard Coleman and the +dnl Zsh Development Group have no obligation to provide maintenance, +dnl support, updates, enhancements, or modifications. +dnl + +AC_INIT +AC_CONFIG_SRCDIR([Src/zsh.h]) +AC_PREREQ([2.69]) +AC_CONFIG_HEADER(config.h) + +dnl What version of zsh are we building ? +. ${srcdir}/Config/version.mk +echo "configuring for zsh $VERSION" + +dnl ---------------------------------------------- +dnl CHECK FOR MACHINE/VENDOR/OPERATING SYSTEM TYPE +dnl ---------------------------------------------- +dnl Find out machine type, vendor, and operating system +dnl What type of host is this? +AC_CANONICAL_HOST +AC_DEFINE_UNQUOTED(MACHTYPE, "$host_cpu", +[Define to be the machine type (microprocessor class or machine model).]) +AC_DEFINE_UNQUOTED(VENDOR, "$host_vendor", +[Define to be a string corresponding the vendor of the machine.]) +AC_DEFINE_UNQUOTED(OSTYPE, "$host_os", +[Define to be the name of the operating system.]) + +dnl ----------------------------- +dnl CHECKING COMMAND LINE OPTIONS +dnl ----------------------------- +dnl Handle --program-prefix, --program-suffix, etc. +zsh_ARG_PROGRAM + +dnl Handle setting of compile flags (CPPFLAGS, CFLAGS, LDFLAGS, LIBS). +zsh_COMPILE_FLAGS($CPPFLAGS, $CFLAGS, $LDFLAGS, $LIBS) + +dnl Do you want to debug zsh? +ifdef([zsh-debug],[undefine([zsh-debug])])dnl +AH_TEMPLATE([DEBUG], +[Define to 1 if you want to debug zsh.]) +AC_ARG_ENABLE(zsh-debug, +AS_HELP_STRING([--enable-zsh-debug],[compile with debug code and debugger symbols]), +[if test x$enableval = xyes; then + AC_DEFINE(DEBUG) +fi]) + +dnl Do you want zsh memory allocation routines. +ifdef([zsh-mem],[undefine([zsh-mem])])dnl +AH_TEMPLATE([ZSH_MEM], +[Define to 1 if you want to use zsh's own memory allocation routines]) +AC_ARG_ENABLE(zsh-mem, +AS_HELP_STRING([--enable-zsh-mem],[compile with zsh memory allocation routines]), +[if test x$enableval = xyes; then + AC_DEFINE(ZSH_MEM) +fi]) + +dnl Do you want to debug zsh memory allocation routines. +ifdef([zsh-mem-debug],[undefine([zsh-mem-debug])])dnl +AH_TEMPLATE([ZSH_MEM_DEBUG], +[Define to 1 if you want to debug zsh memory allocation routines.]) +AC_ARG_ENABLE(zsh-mem-debug, +AS_HELP_STRING([--enable-zsh-mem-debug],[debug zsh memory allocation routines]), +[if test x$enableval = xyes; then + AC_DEFINE(ZSH_MEM_DEBUG) +fi]) + +dnl Do you want to print warnings when errors in memory allocation. +AH_TEMPLATE([ZSH_MEM_WARNING], +[Define to 1 if you want to turn on warnings of memory allocation errors]) +ifdef([zsh-mem-warning],[undefine([zsh-mem-warning])])dnl +AC_ARG_ENABLE(zsh-mem-warning, +AS_HELP_STRING([--enable-zsh-mem-warning],[print warnings for errors in memory allocation]), +[if test x$enableval = xyes; then + AC_DEFINE(ZSH_MEM_WARNING) +fi]) + +dnl Do you want to turn on error checking for free(). +ifdef([zsh-secure-free],[undefine([zsh-secure-free])])dnl +AH_TEMPLATE([ZSH_SECURE_FREE], +[Define to 1 if you want to turn on memory checking for free().]) +AC_ARG_ENABLE(zsh-secure-free, +AS_HELP_STRING([--enable-zsh-secure-free],[turn on error checking for free()]), +[if test x$enableval = xyes; then + AC_DEFINE(ZSH_SECURE_FREE) +fi]) + +dnl Do you want to debug zsh heap allocation? +dnl Does not depend on zsh-mem. +ifdef([zsh-heap-debug],[undefine([zsh-heap-debug])])dnl +AH_TEMPLATE([ZSH_HEAP_DEBUG], +[Define to 1 if you want to turn on error checking for heap allocation.]) +AC_ARG_ENABLE(zsh-heap-debug, +AS_HELP_STRING([--enable-zsh-heap-debug],[turn on error checking for heap allocation]), +[if test x$enableval = xyes; then + AC_DEFINE(ZSH_HEAP_DEBUG) +fi]) + +dnl Do you want to allow Valgrind to debug heap allocation? +ifdef([zsh-valgrind],[undefine([zsh-valgrind])])dnl +AH_TEMPLATE([ZSH_VALGRIND], +[Define to 1 if you want to add code for valgrind to debug heap memory.]) +AC_ARG_ENABLE(zsh-valgrind, +AS_HELP_STRING([--enable-zsh-valgrind],[turn on support for valgrind debugging of heap memory]), +[if test x$enableval = xyes; then + AC_DEFINE(ZSH_VALGRIND) +fi]) + +dnl Do you want debugging information on internal hash tables. +dnl This turns on the `hashinfo' builtin command. +ifdef([zsh-hash-debug],[undefine([zsh-hash-debug])])dnl +AH_TEMPLATE([ZSH_HASH_DEBUG], +[Define to 1 if you want to get debugging information on internal + hash tables. This turns on the `hashinfo' builtin.]) +AC_ARG_ENABLE(zsh-hash-debug, +AS_HELP_STRING([--enable-zsh-hash-debug],[turn on debugging of internal hash tables]), +[if test x$enableval = xyes; then + AC_DEFINE(ZSH_HASH_DEBUG) +fi]) + +dnl Do you want to dynamically allocate memory on the stack where possible? +ifdef([stack-allocation],[undefine([stack-allocation])])dnl +AH_TEMPLATE([USE_STACK_ALLOCATION], +[Define to 1 if you want to allocate stack memory e.g. with `alloca'.]) +AC_ARG_ENABLE(stack-allocation, +AS_HELP_STRING([--enable-stack-allocation],[allocate stack memory e.g. with `alloca']), +[if test x$enableval = xyes; then + AC_DEFINE(USE_STACK_ALLOCATION) +fi]) + +dnl Pathnames for global zsh scripts +ifdef([etcdir],[undefine([etcdir])])dnl +AC_ARG_ENABLE(etcdir, +AS_HELP_STRING([--enable-etcdir=DIR],[the default directory for global zsh scripts]), +[etcdir="$enableval"], [etcdir=/etc]) + +ifdef([zshenv],[undefine([zshenv])])dnl +AC_ARG_ENABLE(zshenv, +AS_HELP_STRING([--enable-zshenv=FILE],[the full pathname of the global zshenv script]), +[zshenv="$enableval"], +[if test "x$etcdir" = xno; then + zshenv=no +else + zshenv="$etcdir/zshenv" +fi]) +AH_TEMPLATE([GLOBAL_ZSHENV], +[The global file to source absolutely first whenever zsh is run; + if undefined, don't source anything.]) +if test "x$zshenv" != xno; then + AC_DEFINE_UNQUOTED(GLOBAL_ZSHENV, "$zshenv") +fi + +ifdef([zshrc],[undefine([zshrc])])dnl +AC_ARG_ENABLE(zshrc, +AS_HELP_STRING([--enable-zshrc=FILE],[the full pathname of the global zshrc script]), +[zshrc="$enableval"], +[if test "x$etcdir" = xno; then + zshrc=no +else + zshrc="$etcdir/zshrc" +fi]) +AH_TEMPLATE([GLOBAL_ZSHRC], +[The global file to source whenever zsh is run; + if undefined, don't source anything]) +if test "x$zshrc" != xno; then + AC_DEFINE_UNQUOTED(GLOBAL_ZSHRC, "$zshrc") +fi + +ifdef([zprofile],[undefine([zprofile])])dnl +AC_ARG_ENABLE(zprofile, +AS_HELP_STRING([--enable-zprofile=FILE],[the full pathname of the global zprofile script]), +[zprofile="$enableval"], +[if test "x$etcdir" = xno; then + zprofile=no +else + zprofile="$etcdir/zprofile" +fi]) +AH_TEMPLATE([GLOBAL_ZPROFILE], +[The global file to source whenever zsh is run as a login shell, + before zshrc is read; if undefined, don't source anything.]) +if test "x$zprofile" != xno; then + AC_DEFINE_UNQUOTED(GLOBAL_ZPROFILE, "$zprofile") +fi + +ifdef([zlogin],[undefine([zlogin])])dnl +AC_ARG_ENABLE(zlogin, +AS_HELP_STRING([--enable-zlogin=FILE],[the full pathname of the global zlogin script]), +[zlogin="$enableval"], +[if test "x$etcdir" = xno; then + zlogin=no +else + zlogin="$etcdir/zlogin" +fi]) +AH_TEMPLATE([GLOBAL_ZLOGIN], +[The global file to source whenever zsh is run as a login shell; + if undefined, don't source anything]) +if test "x$zlogin" != xno; then + AC_DEFINE_UNQUOTED(GLOBAL_ZLOGIN, "$zlogin") +fi + +ifdef([zlogout],[undefine([zlogout])])dnl +AC_ARG_ENABLE(zlogout, +AS_HELP_STRING([--enable-zlogout=FILE],[the full pathname of the global zlogout script]), +[zlogout="$enableval"], +[if test "x$etcdir" = xno; then + zlogout=no +else + zlogout="$etcdir/zlogout" +fi]) +AH_TEMPLATE([GLOBAL_ZLOGOUT], +[The global file to source whenever zsh was run as a login shell. + This is sourced right before exiting. If undefined, don't source + anything.]) +if test "x$zlogout" != xno; then + AC_DEFINE_UNQUOTED(GLOBAL_ZLOGOUT, "$zlogout") +fi + +AC_SUBST(zshenv)dnl +AC_SUBST(zshrc)dnl +AC_SUBST(zprofile)dnl +AC_SUBST(zlogin)dnl +AC_SUBST(zlogout)dnl + +dnl Do you want dynamically loaded binary modules. +ifdef([dynamic],[undefine([dynamic])])dnl +AC_ARG_ENABLE(dynamic, +AS_HELP_STRING([--disable-dynamic],[turn off dynamically loaded binary modules]), +[dynamic="$enableval"], [dynamic=yes]) + +dnl Do you want to disable restricted on r* commands +ifdef([restricted-r],[undefine([restricted-r])])dnl +AH_TEMPLATE([RESTRICTED_R], +[Undefine this if you don't want to get a restricted shell + when zsh is exec'd with basename that starts with r. + By default this is defined.]) +AC_ARG_ENABLE(restricted-r, +AS_HELP_STRING([--disable-restricted-r],[turn off r* invocation for restricted shell]), +[if test x$enableval = xyes; then + AC_DEFINE(RESTRICTED_R) +fi], +AC_DEFINE(RESTRICTED_R) +) + +dnl Do you want to disable use of locale functions +AH_TEMPLATE([CONFIG_LOCALE], +[Undefine if you don't want local features. By default this is defined.]) +AC_ARG_ENABLE([locale], +AS_HELP_STRING([--disable-locale],[turn off locale features]), +[if test x$enableval = xyes; then + AC_DEFINE(CONFIG_LOCALE) +fi], +AC_DEFINE(CONFIG_LOCALE) +) + +dnl Do you want to compile as K&R C. +AC_ARG_ENABLE(ansi2knr, +AS_HELP_STRING([--enable-ansi2knr],[translate source to K&R C before compiling]), +[ansi2knr="$enableval"], [ansi2knr=default]) + +ifdef([runhelpdir],[undefine([runhelpdir])])dnl +AC_ARG_ENABLE(runhelpdir, +AS_HELP_STRING([--enable-runhelpdir=DIR],[the directory in which to install run-help files]), +[if test x"$enableval" = xno; then + runhelpdir= +else + runhelpdir="$enableval" +fi], [runhelpdir=yes]) +if test x"$runhelpdir" = xyes; then + runhelpdir=${datadir}/${tzsh_name}/'${VERSION}'/help +fi +if test x"$runhelpdir" = x; then + runhelp= +else + runhelp=runhelp +fi + +ifdef([fndir],[undefine([fndir])])dnl +AC_ARG_ENABLE(fndir, +AS_HELP_STRING([--enable-fndir=DIR],[the directory in which to install functions]), +dnl ${VERSION} to be determined at compile time. +[if test x$enableval = xyes; then + fndir=${datadir}/${tzsh_name}/'${VERSION}'/functions +else + fndir="$enableval" +fi], [fndir=${datadir}/${tzsh_name}/'${VERSION}'/functions]) + +ifdef([sitefndir],[undefine([sitefndir])])dnl +AC_ARG_ENABLE(site-fndir, +AS_HELP_STRING([--enable-site-fndir=DIR],[same for site functions (not version specific)]), +[if test x$enableval = xyes; then + sitefndir=${datadir}/${tzsh_name}/site-functions +else + sitefndir="$enableval" +fi], [sitefndir=${datadir}/${tzsh_name}/site-functions]) + +dnl Add /usr/local/share/zsh/site-functions if not yet present +dnl owing to $sitefndir, whether or not explicitly given. +dnl If not explicitly given, it hasn't been expanded yet. +if test X$sitefndir = X/usr/local/share/zsh/site-functions || \ + test X$sitefndir = Xno +then fixed_sitefndir='' +elif test X$prefix != X/usr/local; then + if test X$prefix = XNONE && test X$ac_default_prefix = X/usr/local; then + if test X$tzsh_name != Xzsh + then fixed_sitefndir=/usr/local/share/zsh/site-functions + else fixed_sitefndir='' + fi + else fixed_sitefndir=/usr/local/share/zsh/site-functions + fi +elif test X$tzsh_name != Xzsh +then fixed_sitefndir=/usr/local/share/zsh/site-functions +else fixed_sitefndir='' +fi + +ifdef([function_subdirs],[undefine([function_subdirs])]) +AC_ARG_ENABLE(function-subdirs, +AS_HELP_STRING([--enable-function-subdirs],[install functions in subdirectories])) + +if test "x${enable_function_subdirs}" != x && + test "x${enable_function_subdirs}" != xno; then + FUNCTIONS_SUBDIRS=yes +else + FUNCTIONS_SUBDIRS=no +fi + +ifdef([additionalfpath],[undefine([additionalfpath])])dnl +AC_ARG_ENABLE(additional-fpath, +AS_HELP_STRING([--enable-additional-fpath=DIR],[add directories to default function path]), +[if test x$enableval = xyes; then + additionalfpath="" +else + additionalfpath="${enableval}" +fi], [additionalfpath=""]) + +AC_SUBST(runhelpdir)dnl +AC_SUBST(runhelp)dnl +AC_SUBST(additionalfpath)dnl +AC_SUBST(fndir)dnl +AC_SUBST(sitefndir)dnl +AC_SUBST(fixed_sitefndir)dnl +AC_SUBST(FUNCTIONS_SUBDIRS)dnl + +dnl Directories for scripts such as newuser. + +ifdef([scriptdir],[undefine([scriptdir])])dnl +AC_ARG_ENABLE(scriptdir, +AS_HELP_STRING([--enable-scriptdir=DIR],[the directory in which to install scripts]), +dnl ${VERSION} to be determined at compile time. +[if test x$enableval = xyes; then + scriptdir=${datadir}/${tzsh_name}/'${VERSION}'/scripts +else + scriptdir="$enableval" +fi], [scriptdir=${datadir}/${tzsh_name}/'${VERSION}'/scripts]) + +ifdef([sitescriptdir],[undefine([sitescriptdir])])dnl +AC_ARG_ENABLE(site-scriptdir, +AS_HELP_STRING([--enable-site-scriptdir=DIR],[same for site scripts (not version specific)]), +[if test x$enableval = xyes; then + sitescriptdir=${datadir}/${tzsh_name}/scripts +else + sitescriptdir="$enableval" +fi], [sitescriptdir=${datadir}/${tzsh_name}/scripts]) + +AC_SUBST(scriptdir)dnl +AC_SUBST(sitescriptdir)dnl + +dnl htmldir is already handled, but if it wasn't set, use +dnl the standard zsh default. +if test x$htmldir = x'${docdir}' || test x$htmldir = x; then + htmldir='$(datadir)/$(tzsh)/htmldoc' +fi + +AH_TEMPLATE([CUSTOM_PATCHLEVEL], +[Define to a custom value for the ZSH_PATCHLEVEL parameter]) +AC_ARG_ENABLE(custom-patchlevel, +AS_HELP_STRING([--enable-custom-patchlevel],[set a custom ZSH_PATCHLEVEL value]), +[if test x$enableval != x && test x$enableval != xno; then + AC_DEFINE_UNQUOTED([CUSTOM_PATCHLEVEL], ["$enableval"]) +fi]) + +dnl Do you want maildir support? +ifdef([maildir_support],[undefine([maildir_support])])dnl +AH_TEMPLATE([MAILDIR_SUPPORT], +[Define for Maildir support]) +AC_ARG_ENABLE(maildir-support, +AS_HELP_STRING([--enable-maildir-support],[enable maildir support in MAIL and MAILPATH]), +[if test x$enableval = xyes; then + AC_DEFINE(MAILDIR_SUPPORT) +fi]) + +dnl Do you want to set a maximum function depth? +ifdef([max_function_depth],[undefine([max_function_depth])])dnl +AH_TEMPLATE([MAX_FUNCTION_DEPTH], +[Define for function depth limits]) +AC_ARG_ENABLE(max-function-depth, +AS_HELP_STRING([--enable-max-function-depth=MAX],[limit function depth to MAX, default 500]), +[if test x$enableval = xyes; then + AC_DEFINE(MAX_FUNCTION_DEPTH, 500) +elif test x$enableval != xno; then + AC_DEFINE_UNQUOTED(MAX_FUNCTION_DEPTH, $enableval) +fi], +[AC_DEFINE(MAX_FUNCTION_DEPTH, 500)] +) + +ifdef([default_readnullcmd],[undefine([default_readnullcmd])])dnl +AH_TEMPLATE([DEFAULT_READNULLCMD], +[Define default pager used by readnullcmd]) +AC_ARG_ENABLE(readnullcmd, +AS_HELP_STRING([--enable-readnullcmd=PAGER],[pager used when READNULLCMD is not set]), +[if test x$enableval = xyes; then + AC_DEFINE(DEFAULT_READNULLCMD,"more") +elif test x$enableval != xno; then + AC_DEFINE_UNQUOTED(DEFAULT_READNULLCMD,"$enableval") +fi], +[AC_DEFINE(DEFAULT_READNULLCMD,"more")] +) + +dnl Do you want to look for capability support? +AC_ARG_ENABLE(cap, +AS_HELP_STRING([--enable-cap],[enable the search for POSIX capabilities (may require additional headers to be added by hand)])) + +AC_ARG_ENABLE(gdbm, +AS_HELP_STRING([--disable-gdbm],[turn off search for gdbm library]), +[gdbm="$enableval"], [gdbm=yes]) + +dnl ------------------ +dnl CHECK THE COMPILER +dnl ------------------ +dnl We want these before the checks, so the checks can modify their values. +test -z "${CFLAGS+set}" && CFLAGS= auto_cflags=1 +test -z "${LDFLAGS+set}" && LDFLAGS= auto_ldflags=1 + +AC_PROG_CC + +dnl Check for large file support. + +dnl Gross hack for ReliantUNIX - GCC does not understand getconf options +dnl For now just disable LFS in this case +dnl Any takers? +if test "$host" = mips-sni-sysv4 && test -n "$GCC"; then + : +else + AC_SYS_LARGEFILE +fi + +dnl if the user hasn't specified CFLAGS, then +dnl if compiler is gcc, then use -O2 and some warning flags +dnl else use -O +if test -n "$auto_cflags" && test ."$ansi2knr" != .yes; then + if test "${enable_zsh_debug}" = yes; then + if test -n "$GCC"; then + CFLAGS="$CFLAGS -Wall -Wmissing-prototypes -ggdb" + else + CFLAGS="$CFLAGS -g" + fi + else + if test -n "$GCC"; then + CFLAGS="$CFLAGS -Wall -Wmissing-prototypes -O2" + else + CFLAGS="$CFLAGS -O" + fi + fi +fi +if test -n "$auto_ldflags"; then + case "${enable_zsh_debug}$host_os" in + yesaix*|yeshpux*|yesnetbsd*|yesopenbsd*) ;; # "ld -g" is not valid on these systems + darwin*) LDFLAGS=-Wl,-x ;; + yes*) LDFLAGS=-g ;; + *) LDFLAGS=-s ;; + esac +fi + +dnl ---------- +dnl SCO KLUDGE +dnl ---------- +dnl Sco doesn't define any useful compiler symbol, +dnl so we will check for sco and define __sco if +dnl found. +case "$host_os" in + sco*) CFLAGS="-D__sco $CFLAGS" ;; +esac + +sed=':1 + s/ -s / /g + t1 + s/^ *// + s/ *$//' + +case " $LDFLAGS " in + *" -s "*) strip_exeldflags=true strip_libldflags=true + LDFLAGS=`echo " $LDFLAGS " | sed "$sed"` ;; + *) strip_exeldflags=false strip_libldflags=false ;; +esac + +case " ${EXELDFLAGS+$EXELDFLAGS }" in + " ") ;; + *" -s "*) strip_exeldflags=true + EXELDFLAGS=`echo " $EXELDFLAGS " | sed "$sed"` ;; + *) strip_exeldflags=false ;; +esac + +case " ${LIBLDFLAGS+$LIBLDFLAGS }" in + " ") ;; + *" -s "*) strip_libldflags=true + LIBLDFLAGS=`echo " $LIBLDFLAGS " | sed "$sed"` ;; + *) strip_libldflags=false ;; +esac + +AC_SUBST(CFLAGS)dnl +AC_SUBST(LDFLAGS)dnl +AC_SUBST(EXELDFLAGS)dnl +AC_SUBST(LIBLDFLAGS)dnl + +AC_PROG_CPP dnl Figure out how to run C preprocessor. +AC_C_CONST dnl Does compiler support `const'. + +dnl Default preprocessing on Mac OS X produces warnings +dnl Mac OS X 10.6 (darwin10.x.x) does not need this. +case "$host_os" in + darwin[[0-9]].*) CPP="$CPP -traditional-cpp" ;; +esac + +fp_PROG_CC_STDC +AC_MSG_CHECKING([whether to use prototypes]) +if test ."$ansi2knr" = .yes || test ."$ansi2knr" = .no; then + msg="(overridden) " +else + msg= + if test ."$fp_cv_prog_cc_stdc" = .no; then + ansi2knr=yes + else + ansi2knr=no + fi +fi +AH_TEMPLATE([PROTOTYPES], +[Define to 1 if ANSI function prototypes are usable.]) +if test "$ansi2knr" = yes; then + AC_MSG_RESULT(${msg}no) + U=_ +else + AC_MSG_RESULT(${msg}yes) + AC_DEFINE(PROTOTYPES) + U= +fi +AC_SUBST(U) + +AC_FUNC_ALLOCA dnl Check how to get `alloca'. + +dnl If the compiler supports union initialisation +AC_CACHE_CHECK(if the compiler supports union initialisation, +zsh_cv_c_have_union_init, +[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[union{void *p;long l;}u={0};]], [[u.l=1;]])],[zsh_cv_c_have_union_init=yes],[zsh_cv_c_have_union_init=no])]) +AH_TEMPLATE([HAVE_UNION_INIT], +[Define to 1 if the compiler can initialise a union.]) +if test x$zsh_cv_c_have_union_init = xyes; then + AC_DEFINE(HAVE_UNION_INIT) +fi + +dnl Checking if compiler correctly cast signed to unsigned. +AC_CACHE_CHECK(if signed to unsigned casting is broken, +zsh_cv_c_broken_signed_to_unsigned_casting, +[AC_RUN_IFELSE([AC_LANG_SOURCE([[main(){return((int)(unsigned char)((char) -1) == 255);}]])],[zsh_cv_c_broken_signed_to_unsigned_casting=yes],[zsh_cv_c_broken_signed_to_unsigned_casting=no],[zsh_cv_c_broken_signed_to_unsigned_casting=no])]) +AH_TEMPLATE([BROKEN_SIGNED_TO_UNSIGNED_CASTING], +[Define to 1 if compiler incorrectly cast signed to unsigned.]) +if test x$zsh_cv_c_broken_signed_to_unsigned_casting = xyes; then + AC_DEFINE(BROKEN_SIGNED_TO_UNSIGNED_CASTING) +fi + +dnl Checking if the compiler supports variable-length arrays +AC_CACHE_CHECK(if the compiler supports variable-length arrays, +zsh_cv_c_variable_length_arrays, +[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[int foo(), n;]], [[int i[foo()], a[n+1];]])],[zsh_cv_c_variable_length_arrays=yes],[zsh_cv_c_variable_length_arrays=no])]) +AH_TEMPLATE([HAVE_VARIABLE_LENGTH_ARRAYS], +[Define to 1 if compiler supports variable-length arrays]) +if test x$zsh_cv_c_variable_length_arrays = xyes; then + AC_DEFINE(HAVE_VARIABLE_LENGTH_ARRAYS) +fi + +dnl ------------------ +dnl CHECK FOR PROGRAMS +dnl ------------------ +AC_PROG_MAKE_SET dnl Does make define $MAKE +AC_PROG_INSTALL dnl Check for BSD compatible `install' +AC_PROG_AWK dnl Check for mawk,gawk,nawk, then awk. +AC_PROG_LN dnl Check for working ln, for "make install" +AC_PROG_LN_S dnl Use ln -s/ln/cp for "make install.runhelp" +AC_PROG_EGREP dnl sets $EGREP to grep -E or egrep +AC_CHECK_PROGS([YODL], [yodl], [: yodl]) + +YODL_OPTIONS='' +if test "x$ac_cv_prog_YODL" = xyodl; then + case `yodl --version` in + *"version 2."*) YODL_OPTIONS='-k' ;; + *"version 3."*) YODL_OPTIONS='-k -L' ;; + *"version 4."*) YODL_OPTIONS='-k -L' ;; + esac +fi +AC_SUBST(YODL_OPTIONS) + +AC_CHECK_PROGS([TEXI2DVI], [texi2dvi], [: texi2dvi]) +AC_CHECK_PROGS([TEXI2PDF], [texi2pdf], [: texi2pdf]) +AC_CHECK_PROGS([TEXI2HTML], [texi2any texi2html], [: texi2html]) + +if test x"$TEXI2PDF" != xtexi2pdf && test x"$TEXI2DVI" = xtexi2dvi; then + TEXI2PDF='texi2dvi --pdf' +fi + +if test x"$TEXI2HTML" = xtexi2any; then + TEXI2HTML='texi2any -c TEXI2HTML=1' +fi + +case "$LC_PAPER" in + ??_US*) PAPERSIZE=us ;; + *) PAPERSIZE=a4 ;; +esac +AC_SUBST(PAPERSIZE) + +AC_CHECK_PROGS([ANSI2KNR], [ansi2knr], [: ansi2knr]) + +if test x"$ansi2knr" = xyes && test x"$ANSI2KNR" = x": ansi2knr"; then + echo "----------" + echo "configure fatal error:" + echo "ansi2knr was specified (--enable-ansi2knr) but the program could not be found." + echo "Either remove the configure option if it is not required or build the ansi2knr" + echo "program before reconfiguring Zsh. The source code for ansi2knr is also" + echo "available in the GPL directory on Zsh distribution sites." + exit 1 +fi + +dnl ------------------ +dnl CHECK HEADER FILES +dnl ------------------ +AC_HEADER_DIRENT +AC_HEADER_STDC +AC_HEADER_TIME +AC_HEADER_STAT +AC_HEADER_SYS_WAIT + +oldcflags="$CFLAGS" + +AC_CHECK_HEADERS(sys/time.h sys/times.h sys/select.h termcap.h termio.h \ + termios.h sys/param.h sys/filio.h string.h memory.h \ + limits.h fcntl.h libc.h sys/utsname.h sys/resource.h \ + locale.h errno.h stdio.h stdarg.h varargs.h stdlib.h \ + unistd.h sys/capability.h \ + utmp.h utmpx.h sys/types.h pwd.h grp.h poll.h sys/mman.h \ + netinet/in_systm.h langinfo.h wchar.h stddef.h \ + sys/stropts.h iconv.h ncurses.h ncursesw/ncurses.h \ + ncurses/ncurses.h) +if test x$dynamic = xyes; then + AC_CHECK_HEADERS(dlfcn.h) + AC_CHECK_HEADERS(dl.h) +fi + +dnl Some SCO systems cannot include both sys/time.h and sys/select.h +AH_TEMPLATE([TIME_H_SELECT_H_CONFLICTS], +[Define if sys/time.h and sys/select.h cannot be both included.]) +if test x$ac_cv_header_sys_time_h = xyes && test x$ac_cv_header_sys_select_h = xyes; then + AC_CACHE_CHECK(for conflicts in sys/time.h and sys/select.h, + zsh_cv_header_time_h_select_h_conflicts, + [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include +#include ]], [[int i;]])],[zsh_cv_header_time_h_select_h_conflicts=no],[zsh_cv_header_time_h_select_h_conflicts=yes])]) + if test x$zsh_cv_header_time_h_select_h_conflicts = xyes; then + AC_DEFINE(TIME_H_SELECT_H_CONFLICTS) + fi +fi + +AH_TEMPLATE([GWINSZ_IN_SYS_IOCTL], +[Define if TIOCGWINSZ is defined in sys/ioctl.h but not in termios.h.]) +if test x$ac_cv_header_termios_h = xyes; then + AC_CACHE_CHECK(TIOCGWINSZ in termios.h, + zsh_cv_header_termios_h_tiocgwinsz, + [AC_LINK_IFELSE([AC_LANG_PROGRAM([[ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include ]], [[int x = TIOCGWINSZ;]])],[zsh_cv_header_termios_h_tiocgwinsz=yes],[zsh_cv_header_termios_h_tiocgwinsz=no])]) +else + zsh_cv_header_termios_h_tiocgwinsz=no +fi +if test x$zsh_cv_header_termios_h_tiocgwinsz = xno; then + AC_CACHE_CHECK(TIOCGWINSZ in sys/ioctl.h, + zsh_cv_header_sys_ioctl_h_tiocgwinsz, + [AC_LINK_IFELSE([AC_LANG_PROGRAM([[ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include ]], [[int x = TIOCGWINSZ;]])],[zsh_cv_header_sys_ioctl_h_tiocgwinsz=yes],[zsh_cv_header_sys_ioctl_h_tiocgwinsz=no])]) + if test x$zsh_cv_header_sys_ioctl_h_tiocgwinsz = xyes; then + AC_DEFINE(GWINSZ_IN_SYS_IOCTL) + fi +fi + +AH_TEMPLATE([WINSIZE_IN_PTEM], +[Define if your should include sys/stream.h and sys/ptem.h.]) +AC_CACHE_CHECK(for streams headers including struct winsize, +ac_cv_winsize_in_ptem, +[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include +#include ]], [[struct winsize wsz]])],[ac_cv_winsize_in_ptem=yes],[ac_cv_winsize_in_ptem=no])]) +if test x$ac_cv_winsize_in_ptem = xyes; then + AC_DEFINE(WINSIZE_IN_PTEM) +fi + +dnl ------------------- +dnl CHECK FOR LIBRARIES +dnl ------------------- + +dnl On some systems, modules need to be linked against libc explicitly, +dnl in case they require objects that exist only in the static version +dnl and might not be compiled into the zsh executable. +dnl On ReliantUNIX -lc better be the last library, else funny things +dnl may happen. +AC_CHECK_LIB(c, printf, [LIBS="$LIBS -lc"]) + +AC_CHECK_LIB(m, pow) + +AC_CHECK_LIB(rt, clock_gettime) + +dnl Various features of ncurses depend on having the right header +dnl (the system's own curses.h may well not be good enough). +dnl So don't search for ncurses unless we found the header. +if test x$ac_cv_header_ncurses_h = xyes || test x$ac_cv_header_ncurses_ncurses_h = xyes || test x$ac_cv_header_ncursesw_ncurses_h = xyes; then + ncursesw_test=ncursesw + ncurses_test=ncurses +else + ncursesw_test= + ncurses_test= +fi + +dnl Prefer BSD termcap library to SysV curses library, except on certain +dnl SYSV-derived systems. However, if we find terminfo and termcap +dnl stuff in the same library we will use that; typically this +dnl is ncurses or curses. +dnl On pre-11.11 HPUX, Hcurses is reported to work better than curses. +dnl Prefer ncurses to curses on all systems. tinfo isn't very common now. +AC_ARG_WITH(term-lib, +AS_HELP_STRING([--with-term-lib=LIBS],[search space-separated LIBS for terminal handling]), +[if test "x$withval" != xno && test "x$withval" != x ; then + termcap_curses_order="$withval" + AC_SEARCH_LIBS(tigetstr, [$termcap_curses_order]) +else + termcap_curses_order="$ncursesw_test tinfo termcap $ncurses_test curses" +fi], +[case "$host_os" in + solaris*) + termcap_curses_order="$ncursesw_test $ncurses_test curses termcap" ;; + hpux10.*|hpux11.*) + DL_EXT="${DL_EXT=sl}" + termcap_curses_order="Hcurses $ncursesw_test $ncurses_test curses termcap" ;; + *) + termcap_curses_order="$ncursesw_test tinfo termcap $ncurses_test curses" ;; +esac])dnl + +AH_TEMPLATE([ZSH_NO_XOPEN], +[Define if _XOPEN_SOURCE_EXTENDED should not be defined to avoid clashes]) +AC_CACHE_CHECK(if _XOPEN_SOURCE_EXTENDED should not be defined, +zsh_cv_no_xopen, +[[case "$host_os" in + *freebsd5*|*freebsd6.[012]*|*aix*) + zsh_cv_no_xopen=yes + ;; + *) + zsh_cv_no_xopen=no + ;; +esac]]) +if test x$zsh_cv_no_xopen = xyes; then + AC_DEFINE(ZSH_NO_XOPEN) +fi + +dnl Check for tigetflag (terminfo) before tgetent (termcap). +dnl That's so that on systems where termcap and [n]curses are +dnl both available and both contain termcap functions, while +dnl only [n]curses contains terminfo functions, we only link against +dnl [n]curses. +AC_SEARCH_LIBS(tigetflag, [$termcap_curses_order]) +AC_SEARCH_LIBS(tgetent, [$termcap_curses_order], + true, + AC_MSG_FAILURE(["No terminal handling library was found on your system. +This is probably a library called 'curses' or 'ncurses'. You may +need to install a package called 'curses-devel' or 'ncurses-devel' on your +system."], 255)) +AC_CHECK_HEADERS(curses.h, [], +[AC_CACHE_CHECK(for Solaris 8 curses.h mistake, ac_cv_header_curses_solaris, +AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[]])],[ac_cv_header_curses_h=yes +ac_cv_header_curses_solaris=yes],[ac_cv_header_curses_h=no +ac_cv_header_curses_solaris=no])) +if test x$ac_cv_header_curses_solaris = xyes; then +AC_DEFINE(HAVE_CURSES_H) +fi]) + +dnl If our terminal library is not ncurses, don't try including +dnl any ncurses headers. +AC_CACHE_CHECK(if we need to ignore ncurses, zsh_cv_ignore_ncurses, +[case $LIBS in + *-lncurses*) + zsh_cv_ignore_ncurses=no + ;; + *) + zsh_cv_ignore_ncurses=yes + ;; +esac]) + +AC_SEARCH_LIBS(getpwnam, nsl) + +dnl I am told that told that unicos reqire these for nis_list +if test `echo $host_os | sed 's/^\(unicos\).*/\1/'` = unicos; then + LIBS="-lcraylm -lkrb -lnisdb -lnsl -lrpcsvc $LIBS" +fi + +if test "x$dynamic" = xyes; then + AC_CHECK_LIB(dl, dlopen) +fi + +if test x$enable_cap = xyes; then + AC_CHECK_LIB(cap, cap_get_proc) +fi + +AC_CHECK_LIB(socket, socket) +AC_SEARCH_LIBS(gethostbyname2, bind) + +case $LIBS in + *-lbind*) + AC_CHECK_HEADERS(bind/netdb.h) + ;; +esac + +dnl --------------- +dnl CHECK FOR ICONV +dnl --------------- + +dnl Find iconv. It may be in libiconv and may be iconv() or libiconv() +if test "x$ac_cv_header_iconv_h" = "xyes"; then + AC_CHECK_FUNC(iconv, ac_found_iconv=yes, ac_found_iconv=no) + if test "x$ac_found_iconv" = "xno"; then + AC_CHECK_LIB(iconv, iconv, ac_found_iconv=yes) + if test "x$ac_found_iconv" = "xno"; then + AC_CHECK_LIB(iconv, libiconv, ac_found_iconv=yes) + fi + if test "x$ac_found_iconv" != "xno"; then + LIBS="-liconv $LIBS" + fi + else + dnl Handle case where there is a native iconv but iconv.h is from libiconv + AC_CHECK_DECL(_libiconv_version, + [ AC_CHECK_LIB(iconv, libiconv, LIBS="-liconv $LIBS") ],, + [ #include ]) + fi +fi +AH_TEMPLATE([ICONV_FROM_LIBICONV], +[Define to 1 if iconv() is linked from libiconv]) +if test "x$ac_found_iconv" = xyes; then + AC_DEFINE(HAVE_ICONV, 1, [Define if you have the iconv() function.]) + AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include ]], [[int myversion = _libiconv_version]])],[AC_DEFINE(ICONV_FROM_LIBICONV)],[]) +fi + +dnl Check if iconv uses const in prototype declaration +if test "x$ac_found_iconv" = "xyes"; then + AC_CACHE_CHECK(for iconv declaration, ac_cv_iconv_const, + [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include + #include ]], + [[#ifdef __cplusplus + "C" + #endif + #if defined(__STDC__) || defined(__cplusplus) + size_t iconv (iconv_t cd, char * *inbuf, size_t *inbytesleft, char * *outbuf, size_t *outbytesleft); + #else + size_t iconv(); + #endif]])], + [ac_cv_iconv_const=], + [ac_cv_iconv_const=const])]) + AC_DEFINE_UNQUOTED([ICONV_CONST], $ac_cv_iconv_const, + [Define as const if the declaration of iconv() needs const.]) +fi + +dnl --------------------- +dnl CHECK TERMCAP LIBRARY +dnl --------------------- +dnl Checks for external variable ospeed in the termcap library. +AC_CACHE_CHECK(if an include file defines ospeed, +zsh_cv_decl_ospeed_include_defines, +[AC_LINK_IFELSE([AC_LANG_PROGRAM([[#include +#if HAVE_TERMIOS_H +#include +#endif +#if HAVE_TERMCAP_H +#include +#endif]], [[ospeed = 0;]])],[zsh_cv_decl_ospeed_include_defines=yes],[zsh_cv_decl_ospeed_include_defines=no])]) + +if test x$zsh_cv_decl_ospeed_include_defines = xno; then + AC_CACHE_CHECK(if you must define ospeed, + zsh_cv_decl_ospeed_must_define, + [AC_LINK_IFELSE([AC_LANG_PROGRAM([[]], [[extern short ospeed; ospeed = 0;]])],[zsh_cv_decl_ospeed_must_define=yes],[zsh_cv_decl_ospeed_must_define=no])]) +fi + +AH_TEMPLATE([HAVE_OSPEED], +[Define to 1 if your termcap library has the ospeed variable]) +AH_TEMPLATE([MUST_DEFINE_OSPEED], +[Define to 1 if you have ospeed, but it is not defined in termcap.h]) +if test x$zsh_cv_decl_ospeed_include_defines = xyes; then + AC_DEFINE(HAVE_OSPEED) +elif test x$zsh_cv_decl_ospeed_must_define = xyes; then + AC_DEFINE(HAVE_OSPEED) + AC_DEFINE(MUST_DEFINE_OSPEED) +fi + +if test x$gdbm != xno; then + AC_CHECK_HEADERS(gdbm.h) + AC_CHECK_LIB(gdbm, gdbm_open) +fi + +AC_CHECK_HEADERS(sys/xattr.h) + +dnl -------------- +dnl CHECK TYPEDEFS +dnl -------------- + +AC_TYPE_PID_T +AC_TYPE_OFF_T +AC_CHECK_TYPE(ino_t, unsigned long) +AC_TYPE_MODE_T +AC_TYPE_UID_T +AC_TYPE_SIZE_T + +dnl ------------------------------------------------ +dnl Check size of long and try to find a 64-bit type +dnl ------------------------------------------------ +dnl AC_CHECK_SIZEOF is no good, because we need the result here, +dnl and that doesn't seem to define a shell parameter. +AC_CACHE_CHECK(if long is 64 bits, zsh_cv_long_is_64_bit, +[AC_RUN_IFELSE([AC_LANG_SOURCE([[int main() { return sizeof(long) < 8; }]])],[zsh_cv_long_is_64_bit=yes],[zsh_cv_long_is_64_bit=no],[zsh_cv_long_is_64_bit=no])]) + +AH_TEMPLATE([ino_t], +[Define to `unsigned long' if doesn't define.]) +AH_TEMPLATE([LONG_IS_64_BIT], +[Definitions used when a long is less than eight byte, to try to + provide some support for eight byte operations. + + Note that ZSH_64_BIT_TYPE, OFF_T_IS_64_BIT, INO_T_IS_64_BIT do *not* get + defined if long is already 64 bits, since in that case no special handling + is required. + + Define to 1 if long is 64 bits]) +AH_TEMPLATE([ZSH_64_BIT_TYPE], +[Define to a 64 bit integer type if there is one, but long is shorter.]) +AH_TEMPLATE([ZSH_64_BIT_UTYPE], +[Define to an unsigned variant of ZSH_64_BIT_TYPE if that is defined.]) +AH_TEMPLATE([OFF_T_IS_64_BIT], +[Define to 1 if off_t is 64 bit (for large file support)]) +AH_TEMPLATE([INO_T_IS_64_BIT], +[Define to 1 if ino_t is 64 bit (for large file support).]) +if test x$zsh_cv_long_is_64_bit = xyes; then + AC_DEFINE(LONG_IS_64_BIT) +else + AC_CACHE_CHECK(if off_t is 64 bit, zsh_cv_off_t_is_64_bit, + [AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include + +main() { return sizeof(off_t) < 8; } +]])],[zsh_cv_off_t_is_64_bit=yes],[zsh_cv_off_t_is_64_bit=no],[zsh_cv_off_t_is_64_bit=no])]) + if test x$zsh_cv_off_t_is_64_bit = xyes; then + AC_DEFINE(OFF_T_IS_64_BIT) + fi + + AC_CACHE_CHECK(if ino_t is 64 bit, zsh_cv_ino_t_is_64_bit, + [AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include + +main() { return sizeof(ino_t) < 8; } +]])],[zsh_cv_ino_t_is_64_bit=yes],[zsh_cv_ino_t_is_64_bit=no],[zsh_cv_ino_t_is_64_bit=no])]) + if test x$zsh_cv_ino_t_is_64_bit = xyes; then + AC_DEFINE(INO_T_IS_64_BIT) + fi + + if test x$enable_largefile != xno -o x$zsh_cv_off_t_is_64_bit = xyes \ + -o $zsh_cv_ino_t_is_64_bit = yes; then + AC_CACHE_CHECK(if compiler has a 64 bit type, zsh_cv_64_bit_type, + [zsh_64_BIT_TYPE(long long, zsh_cv_64_bit_type) + if test "$zsh_cv_64_bit_type" = no; then + zsh_64_BIT_TYPE(quad_t, zsh_cv_64_bit_type) + fi + if test "$zsh_cv_64_bit_type" = no; then + zsh_64_BIT_TYPE(__int64_t, zsh_cv_64_bit_type) + fi + dnl As a last resort, if we know off_t has 64 bits, use that as + dnl the 64-bit integer type. I don't dare try ino_t since there's + dnl probably nothing to stop that being unsigned. + if test "$zsh_cv_64_bit_type" = no && + test "$zsh_cv_off_t_is_64_bit" = yes; then + zsh_64_BIT_TYPE(off_t, zsh_cv_64_bit_type) + fi]) + if test "$zsh_cv_64_bit_type" != no; then + AC_DEFINE_UNQUOTED(ZSH_64_BIT_TYPE, $zsh_cv_64_bit_type) + + dnl Handle cases where unsigned type cannot be simply + dnl `unsigned ZSH_64_BIT_TYPE'. More tests may be required. + AC_CACHE_CHECK(for a corresponding unsigned 64 bit type, + zsh_cv_64_bit_utype, + [zsh_64_BIT_TYPE(unsigned $zsh_cv_64_bit_type, zsh_cv_64_bit_utype, + force) + if test "$zsh_cv_64_bit_utype" = no; then + zsh_64_BIT_TYPE(__uint64_t, zsh_cv_64_bit_utype) + fi]) + if test "$zsh_cv_64_bit_utype" != no; then + AC_DEFINE_UNQUOTED(ZSH_64_BIT_UTYPE, $zsh_cv_64_bit_utype) + fi + fi + fi +fi +AH_TEMPLATE([ZLONG_IS_LONG_LONG], +[Define to 1 if the zlong type uses long long int.]) +AH_TEMPLATE([ZLONG_IS_LONG_64], +[Define to 1 if the zlong type uses 64-bit long int.]) +if test "$zsh_cv_64_bit_type" = "long long"; then + dnl Remember this so we can get (s)printf output right. + AC_DEFINE(ZLONG_IS_LONG_LONG) +else + if test "$zsh_cv_64_bit_type" = "long"; then + AC_DEFINE(ZLONG_IS_LONG_64) + fi +fi + +dnl We'll blithely assume (f)printf supports the same types as sprintf. +AC_CACHE_CHECK(for %lld printf support, zsh_cv_printf_has_lld, +[AC_RUN_IFELSE([AC_LANG_SOURCE([[#include +#include +int main(int argc, char **argv) +{ + long long foo = ((long long)0xdead << 40) | 0xf00d; + char buf[80]; + sprintf(buf, "before%lldafter", foo); + if (!strcmp(buf, "before62677660341432333after")) { + return 0; + } + return 1; +} +]])],[zsh_cv_printf_has_lld=yes],[zsh_cv_printf_has_lld=no],[zsh_cv_printf_has_lld=no])]) +AH_TEMPLATE(PRINTF_HAS_LLD, +[Define to 1 if printf and sprintf support %lld for long long.]) +if test x$zsh_cv_printf_has_lld = xyes; then + AC_DEFINE(PRINTF_HAS_LLD) +fi + +dnl Check for sigset_t. Currently I'm looking in +dnl and . Others might need +dnl to be added. +AC_CACHE_CHECK(for sigset_t, zsh_cv_type_sigset_t, +[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#define _POSIX_C_SOURCE 200809L +#include +#include ]], [[sigset_t tempsigset;]])],[zsh_cv_type_sigset_t=yes],[zsh_cv_type_sigset_t=no])]) +AH_TEMPLATE([sigset_t], +[Define to `unsigned int' if or doesn't define]) +if test x$zsh_cv_type_sigset_t = xno; then + AC_DEFINE(sigset_t, unsigned int) +fi + +dnl check structures for high resolution timestamps +AC_CHECK_MEMBERS([struct stat.st_atim.tv_nsec, + struct stat.st_atimespec.tv_nsec, + struct stat.st_atimensec, + struct stat.st_mtim.tv_nsec, + struct stat.st_mtimespec.tv_nsec, + struct stat.st_mtimensec, + struct stat.st_ctim.tv_nsec, + struct stat.st_ctimespec.tv_nsec, + struct stat.st_ctimensec]) + +dnl Check for struct timezone since some old SCO versions do not define it +zsh_TYPE_EXISTS([ +#define _GNU_SOURCE 1 +#ifdef HAVE_SYS_TIME_H +# include +#endif +], struct timezone) + +dnl Check for struct timespec since POSIX only gained it in 2008 +zsh_TYPE_EXISTS([ +#define _GNU_SOURCE 1 +#ifdef HAVE_SYS_TIME_H +# include +#endif +], struct timespec) + +dnl Check for utmp structures, for watch +zsh_TYPE_EXISTS([ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UTMP_H +# include +#endif +], struct utmp) +zsh_TYPE_EXISTS([ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UTMPX_H +# include +#endif +], struct utmpx) + +dnl Check contents of utmp structures +zsh_STRUCT_MEMBER([ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UTMP_H +# include +#endif +], struct utmp, ut_host) +zsh_STRUCT_MEMBER([ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UTMPX_H +# include +#endif +], struct utmpx, ut_host) +zsh_STRUCT_MEMBER([ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UTMPX_H +# include +#endif +], struct utmpx, ut_xtime) +zsh_STRUCT_MEMBER([ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_UTMPX_H +# include +#endif +], struct utmpx, ut_tv) + +dnl Check for inode numbers in directory entry structures +zsh_STRUCT_MEMBER([ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_DIRENT_H +# include +#endif +], struct dirent, d_ino) +zsh_STRUCT_MEMBER([ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_DIRENT_H +# include +#endif +], struct dirent, d_stat) +zsh_STRUCT_MEMBER([ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_NDIR_H +# include +#endif +#ifdef HAVE_SYS_DIR_H +# include +#endif +#ifdef HAVE_NDIR_H +# include +#endif +], struct direct, d_ino) +zsh_STRUCT_MEMBER([ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#ifdef HAVE_SYS_NDIR_H +# include +#endif +#ifdef HAVE_SYS_DIR_H +# include +#endif +#ifdef HAVE_NDIR_H +# include +#endif +], struct direct, d_stat) + +dnl Check IPv6 socket address structure type +zsh_STRUCT_MEMBER([ +#ifdef HAVE_SYS_TYPES_H +# include +#endif +#include +], struct sockaddr_in6, sin6_scope_id) + +dnl Check for h_errno external variable +AH_TEMPLATE([USE_LOCAL_H_ERRNO], +[Define to 1 if h_errno is not defined by the system.]) +AC_CACHE_CHECK(if we need our own h_errno, + zsh_cv_decl_h_errno_use_local, + [AC_LINK_IFELSE([AC_LANG_PROGRAM([[]], [[extern int h_errno; h_errno = 0;]])],[zsh_cv_decl_h_errno_use_local=no],[zsh_cv_decl_h_errno_use_local=yes])]) + +if test x$zsh_cv_decl_h_errno_use_local = xyes; then + AC_DEFINE(USE_LOCAL_H_ERRNO) +fi + +dnl --------------- +dnl CHECK FUNCTIONS +dnl --------------- + +dnl need to integrate this function +dnl AC_FUNC_STRFTIME + +AC_CHECK_FUNCS(strftime strptime mktime timelocal \ + difftime gettimeofday clock_gettime \ + select poll \ + readlink faccessx fchdir ftruncate \ + fstat lstat lchown fchown fchmod \ + fseeko ftello \ + mkfifo _mktemp mkstemp \ + waitpid wait3 \ + sigaction sigblock sighold sigrelse sigsetmask sigprocmask \ + killpg setpgid setpgrp tcsetpgrp tcgetattr nice \ + gethostname gethostbyname2 getipnodebyname \ + inet_aton inet_pton inet_ntop \ + getlogin getpwent getpwnam getpwuid getgrgid getgrnam \ + initgroups nis_list \ + setuid seteuid setreuid setresuid setsid \ + memcpy memmove strstr strerror strtoul \ + getrlimit getrusage \ + setlocale \ + isblank iswblank \ + uname \ + signgam tgamma \ + log2 \ + scalbn \ + putenv getenv setenv unsetenv xw\ + brk sbrk \ + pathconf sysconf \ + tgetent tigetflag tigetnum tigetstr setupterm initscr resize_term \ + getcchar setcchar waddwstr wget_wch win_wch use_default_colors \ + nl_langinfo \ + erand48 open_memstream \ + posix_openpt \ + wctomb iconv \ + isinf isnan \ + grantpt unlockpt ptsname \ + htons ntohs \ + regcomp regexec regerror regfree \ + gdbm_open getxattr \ + realpath canonicalize_file_name \ + symlink getcwd \ + cygwin_conv_path \ + nanosleep \ + srand_deterministic \ + setutxent getutxent endutxent getutent \ + getline) +AC_FUNC_STRCOLL + +AH_TEMPLATE([REALPATH_ACCEPTS_NULL], +[Define if realpath() accepts NULL as its second argument.]) +AC_CACHE_CHECK([if realpath accepts NULL], +zsh_cv_func_realpath_accepts_null, +[AC_RUN_IFELSE([AC_LANG_PROGRAM([ +#include +#include +],[ +exit(!realpath("/", (char*)0)); +])], +[zsh_cv_func_realpath_accepts_null=yes], +[zsh_cv_func_realpath_accepts_null=no], +[zsh_cv_func_realpath_accepts_null=$ac_cv_func_canonicalize_file_name])]) +if test x$zsh_cv_func_realpath_accepts_null = xyes; then + AC_DEFINE(REALPATH_ACCEPTS_NULL) +fi + +if test x$enable_cap = xyes; then + AC_CHECK_FUNCS(cap_get_proc) +fi + +dnl Check if tgetent accepts NULL (and will allocate its own termcap buffer) +dnl Some termcaps reportedly accept a zero buffer, but then dump core +dnl in tgetstr(). +dnl Under Cygwin test program crashes but exit code is still 0. So, +dnl we test for a file that porgram should create +AH_TEMPLATE([TGETENT_ACCEPTS_NULL], +[Define to 1 if tgetent() accepts NULL as a buffer.]) +AC_CACHE_CHECK(if tgetent accepts NULL, +zsh_cv_func_tgetent_accepts_null, +[AC_RUN_IFELSE([AC_LANG_SOURCE([[ +main() +{ + char buf[4096]; + int r1 = tgetent(buf, "vt100"); + int r2 = tgetent((char*)0,"vt100"); + if (r1 >= 0 && r1 == r2) { + char tbuf[1024], *u; + u = tbuf; + tgetstr("cl", &u); + creat("conftest.tgetent", 0640); + } + exit((r1 != r2) || r2 == -1); +} +]])],[if test -f conftest.tgetent; then + zsh_cv_func_tgetent_accepts_null=yes + else + zsh_cv_func_tgetent_accepts_null=no + fi],[zsh_cv_func_tgetent_accepts_null=no],[zsh_cv_func_tgetent_accepts_null=no])]) +if test x$zsh_cv_func_tgetent_accepts_null = xyes; then + AC_DEFINE(TGETENT_ACCEPTS_NULL) +fi +AC_CACHE_CHECK(if tgetent returns 0 on success, +zsh_cv_func_tgetent_zero_success, +[AC_RUN_IFELSE([AC_LANG_SOURCE([[ +main() +{ + char buf[4096]; + int r1 = tgetent(buf, "!@#$%^&*"); + int r2 = tgetent(buf, "vt100"); + if (r1 < 0 && r2 == 0) { + char tbuf[1024], *u; + u = tbuf; + tgetstr("cl", &u); + creat("conftest.tgetent0", 0640); + } + exit(r1 == r2); +} +]])],[if test -f conftest.tgetent0; then + zsh_cv_func_tgetent_zero_success=yes + else + zsh_cv_func_tgetent_zero_success=no + fi],[zsh_cv_func_tgetent_zero_success=no],[zsh_cv_func_tgetent_zero_success=no])]) +AH_TEMPLATE([TGETENT_SUCCESS], +[Define to what tgetent() returns on success (0 on HP-UX X/Open curses).]) +if test x$zsh_cv_func_tgetent_zero_success = xyes; then + AC_DEFINE(TGETENT_SUCCESS, 0) +else + AC_DEFINE(TGETENT_SUCCESS, 1) +fi + +AC_FUNC_MMAP +if test x$ac_cv_func_mmap_fixed_mapped = xyes; then + AC_CHECK_FUNCS(munmap msync) +fi + +if test x$ac_cv_func_setpgrp = xyes; then + AC_FUNC_GETPGRP +else + dnl If there is no setpgrp, the test for getpgrp(void) will fail + dnl because the program will not compile. However, in that case + dnl we can be reasonably confident we are not dealing with a + dnl Berkeleyesque system, so assume getpgrp does take void. + ac_cv_func_getpgrp_void=yes + AC_DEFINE(GETPGRP_VOID) +fi + +if test x$dynamic = xyes; then + AC_CHECK_FUNCS(dlopen dlerror dlsym dlclose load loadquery loadbind unload \ + shl_load shl_unload shl_findsym) +fi + +AH_TEMPLATE([XATTR_EXTRA_ARGS], +Define if getxattr() etc. require additional MacOS-style arguments) +if test x$ac_cv_func_getxattr = xyes && test x$ac_cv_header_sys_xattr_h = xyes +then + AC_CACHE_CHECK(if getxattr etc. are Linux-like, + zsh_cv_getxattr_linux, + [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include +#include ]], + [[ + (void)listxattr("", 0, 0); + (void)getxattr("", "", 0, 0); + (void)setxattr("", "", "", 0, 0); + (void)removexattr("", ""); + ]])], + [zsh_cv_getxattr_linux=yes], + [zsh_cv_getxattr_linux=no])]) + + if test x$zsh_cv_getxattr_linux != xyes; then + AC_CACHE_CHECK(if getxattr etc. are MAC-like, + zsh_cv_getxattr_mac, + [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include +#include ]], + [[(void)listxattr("", 0, 0, 0); + (void)getxattr("", "", 0, 0, 0, 0); + (void)setxattr("", "", "", 0, 0, 0); + (void)removexattr("", "", 0);]])], + [zsh_cv_getxattr_mac=yes], + [zsh_cv_getxattr_mac=no])]) + + if test x$zsh_cv_getxattr_mac = xyes; then + AC_DEFINE(XATTR_EXTRA_ARGS) + fi + fi +fi + +AC_CACHE_CHECK(if getxattr etc. are usable, +zsh_cv_use_xattr, +[if test x$zsh_cv_getxattr_linux = xyes || test x$zsh_cv_getxattr_mac = xyes +then +zsh_cv_use_xattr=yes +else +zsh_cv_use_xattr=no +fi]) + +dnl ------------- +dnl CHECK SIGNALS +dnl ------------- +dnl What style of signal do you have (POSIX, BSD, or SYSV)? +AH_TEMPLATE([POSIX_SIGNALS], +[Define to 1 if you use POSIX style signal handling.]) +AH_TEMPLATE([BSD_SIGNALS], +[Define to 1 if you use BSD style signal handling (and can block signals).]) +AH_TEMPLATE([SYSV_SIGNALS], +[Define to 1 if you use SYS style signal handling (and can block signals).]) +AH_TEMPLATE([NO_SIGNAL_BLOCKING], +[Define to 1 if you have no signal blocking at all (bummer).]) +AC_MSG_CHECKING(what style of signals to use) +if test x$ac_cv_func_sigaction = xyes && test x$ac_cv_func_sigprocmask = xyes; then + signals_style=POSIX_SIGNALS + AC_DEFINE(POSIX_SIGNALS) +elif test x$ac_cv_func_sigblock = xyes && test x$ac_cv_func_sigsetmask = xyes; then + signals_style=BSD_SIGNALS + AC_DEFINE(BSD_SIGNALS) +elif test x$ac_cv_func_sighold = xyes && test x$ac_cv_func_sigrelse = xyes; then + signals_style=SYSV_SIGNALS + AC_DEFINE(SYSV_SIGNALS) +else + signals_style=NO_SIGNAL_BLOCKING + AC_DEFINE(NO_SIGNAL_BLOCKING) +fi +AC_DEFINE_UNQUOTED($signals_style) +AC_MSG_RESULT($signals_style) + +dnl Where is located? Needed as input for signals.awk +AC_CACHE_CHECK(where signal.h is located, zsh_cv_path_signal_h, +[dnl Look at the output from the preprocessor. +dnl We should get lines of the form `# 1 "/usr/include/signal.h"' +dnl The following assumes the real definitions are in a file which +dnl contains the name `sig'; we could relax this if necessary, +dnl but then you can get a rather long list of files to test. +dnl The backslash substitution is to persuade cygwin to cough up +dnl slashes rather than doubled backslashes in the path. +echo "#include " > nametmp.c +sigfile_list="`$CPP $CPPFLAGS nametmp.c | +sed -n -e 's/^#line[ ].*\"\(.*\)\"/\1/p' \ + -e 's/^#[ ].*\"\(.*\)\"/\1/p' | +sed 's/\\\\\\\\/\//g' | +$AWK '{ if ($1 ~ /sig/) files[[$1]] = $1 } + END { for (var in files) print var }'`" +rm -f nametmp.c +if test -z "$sigfile_list"; then + dnl In case we don't get the stuff from the preprocesor, use the old + dnl list of standard places. + sigfile_list="/usr/include/sys/iso/signal_iso.h +/usr/include/bsd/sys/signal.h +/usr/include/signum.h +/usr/include/asm/signum.h +/usr/include/asm/signal.h +/usr/include/linux/signal.h +/usr/include/sys/signal.h +/usr/include/bits/signum.h +/dev/null" +fi +for SIGNAL_TRY_H in $sigfile_list +do + dnl Try to make sure it doesn't get confused by files that don't + dnl have real signal definitions in, but do #define SIG* by counting + dnl the number of signals. Maybe we could even check for e.g. SIGHUP? + nsigs=`test -f $SIGNAL_TRY_H && \ + grep '#[ ]*define[ ][ ]*SIG[0-9A-Z]*[ ]*[0-9][0-9]*' $SIGNAL_TRY_H | \ + wc -l | sed 's/[ ]//g'` + if test "x$nsigs" != x && test "$nsigs" -ge 7 + then + SIGNAL_H="$SIGNAL_H $SIGNAL_TRY_H" + fi +done +if test "x$SIGNAL_H" = x; then + AC_MSG_ERROR(SIGNAL MACROS NOT FOUND: please report to developers) +fi +zsh_cv_path_signal_h="$SIGNAL_H" +]) +SIGNAL_H="$zsh_cv_path_signal_h" +AC_SUBST(SIGNAL_H)dnl + +dnl Where are error names located? Needed as input for errnames1.awk +AC_CACHE_CHECK(where error names are located, zsh_cv_path_errno_h, +[dnl Look at the output from the preprocessor. +dnl We should get lines of the form `# 1 "/usr/include/errno.h"' +dnl The following assumes the real definitions are in a file which +dnl contains the name `err'; we could relax this if necessary, +dnl but then you can get a rather long list of files to test. +dnl The backslash substitution is to persuade cygwin to cough up +dnl slashes rather than doubled backslashes in the path. +echo "#include " > nametmp.c +errfile_list="`$CPP $CPPFLAGS nametmp.c | +sed -n -e 's/^#line[ ].*\"\(.*\)\"/\1/p' \ + -e 's/^#[ 0-9].*\"\(.*\)\"/\1/p' | +sed 's/\\\\\\\\/\//g' | +$AWK '{ if ($1 ~ /err/) files[[$1]] = $1 } + END { for (var in files) print var }'`" +rm -f nametmp.c +for ERRNO_TRY_H in $errfile_list /dev/null +do + dnl Try to make sure it doesn't get confused by files that don't + dnl have real error definitions in. Count definitions to make sure. + dnl Definitions of error numbers have become more and more general, so + dnl make a list of files containing any definitions in and keep them all. + dnl Careful with cut and paste in the pattern: the square brackets + dnl must contain a space and a tab. + nerrs=`test -f $ERRNO_TRY_H && \ + $EGREP '#[ ]*define[ ][ ]*E[0-9A-Z]*[ ]*(_HURD_ERRNO )?\(?[_A-Z0-9]' $ERRNO_TRY_H | \ + wc -l | sed 's/[ ]//g'` + if test "x$nerrs" != x && test "$nerrs" -ge 1 + then + ERRNO_H="$ERRNO_H $ERRNO_TRY_H" + fi +done +if test x"$ERRNO_H" = x; then + AC_MSG_ERROR(ERROR MACROS NOT FOUND: please report to developers) +fi +zsh_cv_path_errno_h="$ERRNO_H" +]) +ERRNO_H="$zsh_cv_path_errno_h" +AC_SUBST(ERRNO_H)dnl + +AC_CACHE_CHECK(location of curses header, zsh_cv_path_curses_header, +[if test x$zsh_cv_ignore_ncurses = xyes; then + if test x$ac_cv_header_curses_h = xyes; then + zsh_cv_path_curses_header=curses.h + else + zsh_cv_path_curses_header=none + fi +elif test x$ac_cv_header_ncursesw_ncurses_h = xyes; then + zsh_cv_path_curses_header=ncursesw/ncurses.h +elif test x$ac_cv_header_ncurses_ncurses_h = xyes; then + zsh_cv_path_curses_header=ncurses/ncurses.h +elif test x$ac_cv_header_ncurses_h = xyes; then + zsh_cv_path_curses_header=ncurses.h +elif test x$ac_cv_header_curses_h = xyes; then + zsh_cv_path_curses_header=curses.h +else + zsh_cv_path_curses_header=none +fi]) +AH_TEMPLATE([ZSH_HAVE_CURSES_H], +[Define to 1 if some variant of a curses header can be included]) +if test x$zsh_cv_path_curses_header != xnone; then + AC_DEFINE(ZSH_HAVE_CURSES_H) + ZSH_CURSES_H=$zsh_cv_path_curses_header +else + ZSH_CURSES_H= +fi +AC_SUBST(ZSH_CURSES_H) + +dnl Where are curses key definitions located? Need for keypad() mode. +AC_CACHE_CHECK(where curses key definitions are located, zsh_cv_path_curses_keys_h, +[dnl This is an identical trick to errno.h, except we use ncurses.h +dnl if we can. +if test x$zsh_cv_path_curses_header = xnone; then + echo >nametmp.c +else + echo "#include <$zsh_cv_path_curses_header>" >nametmp.c +fi + +curses_list="`$CPP $CPPFLAGS nametmp.c | +sed -n -e 's/^#line[ ].*\"\(.*\)\"/\1/p' \ + -e 's/^#[ 0-9].*\"\(.*\)\"/\1/p' | +sed 's/\\\\\\\\/\//g' | +$AWK '{ if ($1 ~ /\.h/) files[[$1]] = $1 } + END { for (var in files) print var }'`" +rm -f nametmp.c +for CURSES_TRY_H in $curses_list /dev/null +do + nkeys=`test -f $CURSES_TRY_H && \ + $EGREP '#[ ]*define[ ][ ]*KEY_' $CURSES_TRY_H | \ + wc -l | sed 's/[ ]//g'` + if test "x$nkeys" != x && test "$nkeys" -ge 10 + then + CURSES_KEYS_H=$CURSES_TRY_H + break + fi +done +zsh_cv_path_curses_keys_h="$CURSES_KEYS_H" +]) +CURSES_KEYS_H="$zsh_cv_path_curses_keys_h" +AC_SUBST(CURSES_KEYS_H)dnl + +dnl See if there are variants of term.h. For testing each one +dnl we include the most likely variant of the curses header. +AC_CHECK_HEADERS(ncursesw/term.h, +true, true, +[#include ]) +AC_CHECK_HEADERS(ncurses/term.h, +true, true, +[#include ]) +AC_CHECK_HEADERS(term.h, +true, true, +[#include ]) + +dnl See if term.h is bundled along with the curses library we +dnl are using. If this isn't the default system curses, compilation +dnl could barf unless we include from the right subdirectory. +AC_CACHE_CHECK(where term.h is located, zsh_cv_path_term_header, +[case x$zsh_cv_path_curses_header in + xncursesw/*) + if test x$ac_cv_header_ncursesw_term_h = xyes; then + zsh_cv_path_term_header=ncursesw/term.h + fi + ;; + xncurses/*) + if test x$ac_cv_header_ncurses_term_h = xyes; then + zsh_cv_path_term_header=ncurses/term.h + fi + ;; +esac +if test x$zsh_cv_path_term_header = x; then + if test x$ac_cv_header_term_h = xyes; then + zsh_cv_path_term_header=term.h + else + zsh_cv_path_term_header=none + fi +fi]) + +AH_TEMPLATE([ZSH_HAVE_TERM_H], +[Define to 1 if some variant of term.h can be included]) +AH_TEMPLATE([HAVE_BOOLCODES], +[Define if you have the termcap boolcodes symbol.]) +AH_TEMPLATE([HAVE_NUMCODES], +[Define if you have the termcap numcodes symbol.]) +AH_TEMPLATE([HAVE_STRCODES], +[Define if you have the termcap strcodes symbol.]) +AH_TEMPLATE([HAVE_BOOLNAMES], +[Define if you have the terminfo boolnames symbol.]) +AH_TEMPLATE([HAVE_NUMNAMES], +[Define if you have the terminfo numnames symbol.]) +AH_TEMPLATE([HAVE_STRNAMES], +[Define if you have the terminfo strnames symbol.]) +AH_TEMPLATE([TGOTO_PROTO_MISSING], +[Define if there is no prototype for the tgoto() terminal function.]) + +if test x$zsh_cv_path_term_header != xnone; then + AC_DEFINE(ZSH_HAVE_TERM_H) + ZSH_TERM_H=$zsh_cv_path_term_header + if test x$zsh_cv_path_curses_header != xnone; then + term_includes="#include <$zsh_cv_path_curses_header> +#include <$zsh_cv_path_term_header>" + else + term_includes="#include <$zsh_cv_path_term_header>" + fi + + AC_MSG_CHECKING(if boolcodes is available) + AC_LINK_IFELSE([AC_LANG_PROGRAM([[$term_includes]], [[char **test = boolcodes; puts(*test);]])],[AC_DEFINE(HAVE_BOOLCODES) boolcodes=yes],[boolcodes=no]) + AC_MSG_RESULT($boolcodes) + + AC_MSG_CHECKING(if numcodes is available) + AC_LINK_IFELSE([AC_LANG_PROGRAM([[$term_includes]], [[char **test = numcodes; puts(*test);]])],[AC_DEFINE(HAVE_NUMCODES) numcodes=yes],[numcodes=no]) + AC_MSG_RESULT($numcodes) + + AC_MSG_CHECKING(if strcodes is available) + AC_LINK_IFELSE([AC_LANG_PROGRAM([[$term_includes]], [[char **test = strcodes; puts(*test);]])],[AC_DEFINE(HAVE_STRCODES) strcodes=yes],[strcodes=no]) + AC_MSG_RESULT($strcodes) + + AC_MSG_CHECKING(if boolnames is available) + AC_LINK_IFELSE([AC_LANG_PROGRAM([[$term_includes]], [[char **test = boolnames; puts(*test);]])],[AC_DEFINE(HAVE_BOOLNAMES) boolnames=yes],[boolnames=no]) + AC_MSG_RESULT($boolnames) + + AC_MSG_CHECKING(if numnames is available) + AC_LINK_IFELSE([AC_LANG_PROGRAM([[$term_includes]], [[char **test = numnames; puts(*test);]])],[AC_DEFINE(HAVE_NUMNAMES) numnames=yes],[numnames=no]) + AC_MSG_RESULT($numnames) + + AC_MSG_CHECKING(if strnames is available) + AC_LINK_IFELSE([AC_LANG_PROGRAM([[$term_includes]], [[char **test = strnames; puts(*test);]])],[AC_DEFINE(HAVE_STRNAMES) strnames=yes],[strnames=no]) + AC_MSG_RESULT($strnames) + + dnl There are apparently defective terminal library headers on some + dnl versions of Solaris before 11. + AC_MSG_CHECKING(if tgoto prototype is missing) + tgoto_includes="$term_includes +/* guaranteed to clash with any valid tgoto prototype */ +extern void tgoto(int **stuff, float **more_stuff);" + AC_LINK_IFELSE([AC_LANG_PROGRAM([[$tgoto_includes]], [[int *stuff; float *more_stuff; tgoto(&stuff, &more_stuff);]])],[AC_DEFINE(TGOTO_PROTO_MISSING) tgotoprotomissing=yes],[tgotoprotomissing=no]) + AC_MSG_RESULT($tgotoprotomissing) +else + ZSH_TERM_H= +fi +AC_SUBST(ZSH_TERM_H) + + +dnl ----------------------------------------------------- +dnl Look for the file containing the RLIMIT_* definitions +dnl ----------------------------------------------------- +dnl CALL FOR MORE (FEWER?) LOCATIONS: I've just copied the signal checking. +AC_CACHE_CHECK(where the RLIMIT macros are located,zsh_cv_path_rlimit_h, +[dnl Look at the output from the preprocessor. +dnl Copied from the search for the signal names above. +echo "#include " >restmp.c +resourcefile_list="`$CPP $CPPFLAGS restmp.c | +sed -n -e 's/^#line[ ].*\"\(.*\)\"/\1/p' \ + -e 's/^#[ ].*\"\(.*\)\"/\1/p' | +sed 's/\\\\\\\\/\//g' | +$AWK '{ if ($1 ~ /resource/) files[[$1]] = $1 } + END { for (var in files) print var }'`" +rm -f restmp.c +if test -z "$resourcefile_list"; then + dnl No list: look at standard places. + resourcefile_list="/usr/include/bsd/sys/resource.h +/usr/include/asm/resource.h +/usr/include/linux/resource.h +/usr/include/sys/resource.h +/usr/include/bits/resource.h +/usr/include/resourcebits.h" +fi +for RESOURCE_H in $resourcefile_list /dev/null; +do + test -f $RESOURCE_H && \ + grep '#[ ]*define[ ][ ]*RLIMIT_[A-Z]*[ ]*[0-9A-Z][0-9]*' $RESOURCE_H > /dev/null && \ + break +done +zsh_cv_path_rlimit_h=$RESOURCE_H +if test x$RESOURCE_H = x"/dev/null" && test x$ac_cv_func_getrlimit = xyes; then + AC_MSG_WARN(RLIMIT MACROS NOT FOUND: please report to developers) +fi]) +RLIMITS_INC_H=$zsh_cv_path_rlimit_h +if test "$RLIMITS_INC_H" = "/dev/null"; then + RLIMITS_INC_H='' +fi +dnl rlimits.h only appears in dependencies if we are actually using it. +dnl We are using it any time we have getrlimit, though if the macros were +dnl not found we simply awk through /dev/null and fail to find them. +dnl Thus, limit won't work, but at least the shell will compile. +AC_SUBST(RLIMITS_INC_H)dnl + +dnl ------------------ +dnl rlimit type checks +dnl ------------------ +AH_TEMPLATE([RLIM_T_IS_QUAD_T], +[Define to 1 if struct rlimit uses quad_t.]) +AH_TEMPLATE([RLIM_T_IS_LONG_LONG], +[Define to 1 if struct rlimit uses long long]) +AH_TEMPLATE([RLIM_T_IS_UNSIGNED], +[Define to 1 if struct rlimit uses unsigned.]) +AH_TEMPLATE([rlim_t], +[Define to the type used in struct rlimit.]) +DEFAULT_RLIM_T=long +AC_CACHE_CHECK(if rlim_t is longer than a long, +zsh_cv_rlim_t_is_longer, +[AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +main(){struct rlimit r;exit(sizeof(r.rlim_cur) <= sizeof(long));}]])],[zsh_cv_rlim_t_is_longer=yes],[zsh_cv_rlim_t_is_longer=no],[zsh_cv_rlim_t_is_longer=yes])]) +if test x$zsh_cv_rlim_t_is_longer = xyes; then + AC_CACHE_CHECK(if rlim_t is a quad, + zsh_cv_rlim_t_is_quad_t, + [AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +#include +main() { + struct rlimit r; + char buf[20]; + r.rlim_cur = 0; + sprintf(buf, "%qd", r.rlim_cur); + exit(strcmp(buf, "0")); +}]])],[zsh_cv_rlim_t_is_quad_t=yes],[zsh_cv_rlim_t_is_quad_t=no],[zsh_cv_rlim_t_is_quad_t=no])]) + if test x$zsh_cv_rlim_t_is_quad_t = xyes; then + AC_DEFINE(RLIM_T_IS_QUAD_T) + DEFAULT_RLIM_T=quad_t + else + AC_DEFINE(RLIM_T_IS_LONG_LONG) + DEFAULT_RLIM_T='long long' + fi +else + AC_CACHE_CHECK(if the rlim_t is unsigned, + zsh_cv_type_rlim_t_is_unsigned, + [AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include + main(){struct rlimit r;r.rlim_cur=-1;exit(r.rlim_cur<0);}]])],[zsh_cv_type_rlim_t_is_unsigned=yes],[zsh_cv_type_rlim_t_is_unsigned=no],[zsh_cv_type_rlim_t_is_unsigned=no])]) + if test x$zsh_cv_type_rlim_t_is_unsigned = xyes; then + AC_DEFINE(RLIM_T_IS_UNSIGNED) + DEFAULT_RLIM_T="unsigned $DEFAULT_RLIM_T" + fi +fi + +AC_CACHE_CHECK(for rlim_t, zsh_cv_type_rlim_t, +[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include ]], [[rlim_t l;]])],[zsh_cv_type_rlim_t=yes],[zsh_cv_type_rlim_t=no])]) +if test x$zsh_cv_type_rlim_t = xno; then + AC_DEFINE_UNQUOTED(rlim_t, $DEFAULT_RLIM_T) +fi + + +dnl On some systems the RLIMIT_* don't evaluate to integers at compile time +dnl (they may be enums). In this case we are not able to do preprocessor +dnl comparisons and need our tests to determine what values exist and +dnl if there are clashing definitions. + +zsh_LIMIT_PRESENT(RLIMIT_AIO_MEM) +zsh_LIMIT_PRESENT(RLIMIT_AIO_OPS) +zsh_LIMIT_PRESENT(RLIMIT_AS) +zsh_LIMIT_PRESENT(RLIMIT_LOCKS) +zsh_LIMIT_PRESENT(RLIMIT_MEMLOCK) +zsh_LIMIT_PRESENT(RLIMIT_NPROC) +zsh_LIMIT_PRESENT(RLIMIT_NTHR) +zsh_LIMIT_PRESENT(RLIMIT_NOFILE) +zsh_LIMIT_PRESENT(RLIMIT_PTHREAD) +zsh_LIMIT_PRESENT(RLIMIT_RSS) +zsh_LIMIT_PRESENT(RLIMIT_SBSIZE) +zsh_LIMIT_PRESENT(RLIMIT_TCACHE) +zsh_LIMIT_PRESENT(RLIMIT_VMEM) +zsh_LIMIT_PRESENT(RLIMIT_SIGPENDING) +zsh_LIMIT_PRESENT(RLIMIT_MSGQUEUE) +zsh_LIMIT_PRESENT(RLIMIT_NICE) +zsh_LIMIT_PRESENT(RLIMIT_RTPRIO) +zsh_LIMIT_PRESENT(RLIMIT_POSIXLOCKS) +zsh_LIMIT_PRESENT(RLIMIT_NPTS) +zsh_LIMIT_PRESENT(RLIMIT_SWAP) +zsh_LIMIT_PRESENT(RLIMIT_KQUEUES) + +AH_TEMPLATE([RLIMIT_VMEM_IS_RSS], +[Define to 1 if RLIMIT_VMEM and RLIMIT_RSS both exist and are equal.]) +AC_CACHE_CHECK(if RLIMIT_VMEM and RLIMIT_RSS are the same, +zsh_cv_rlimit_vmem_is_rss, +[AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int main() +{ +int ret = 1; +#if defined(HAVE_RLIMIT_VMEM) && defined(HAVE_RLIMIT_RSS) +if (RLIMIT_RSS == RLIMIT_VMEM) ret = 0; +#endif +return ret; +}]])],[zsh_cv_rlimit_vmem_is_rss=yes],[zsh_cv_rlimit_vmem_is_rss=no],[zsh_cv_rlimit_vmem_is_rss=no])]) + +if test x$zsh_cv_rlimit_vmem_is_rss = xyes; then + AC_DEFINE(RLIMIT_VMEM_IS_RSS) +fi + + +AH_TEMPLATE([RLIMIT_VMEM_IS_AS], +[Define to 1 if RLIMIT_VMEM and RLIMIT_AS both exist and are equal.]) +AC_CACHE_CHECK(if RLIMIT_VMEM and RLIMIT_AS are the same, +zsh_cv_rlimit_vmem_is_as, +[AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int main() +{ +int ret = 1; +#if defined(HAVE_RLIMIT_VMEM) && defined(HAVE_RLIMIT_AS) +if (RLIMIT_AS == RLIMIT_VMEM) ret = 0; +#endif +return ret; +}]])],[zsh_cv_rlimit_vmem_is_as=yes],[zsh_cv_rlimit_vmem_is_as=no],[zsh_cv_rlimit_vmem_is_as=no])]) + +if test x$zsh_cv_rlimit_vmem_is_as = xyes; then + AC_DEFINE(RLIMIT_VMEM_IS_AS) +fi + + +AH_TEMPLATE([RLIMIT_RSS_IS_AS], +[Define to 1 if RLIMIT_RSS and RLIMIT_AS both exist and are equal.]) +AC_CACHE_CHECK(if RLIMIT_RSS and RLIMIT_AS are the same, +zsh_cv_rlimit_rss_is_as, +[AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include +int main() +{ +int ret = 1; +#if defined(HAVE_RLIMIT_RSS) && defined(HAVE_RLIMIT_AS) +if (RLIMIT_AS == RLIMIT_RSS) ret = 0; +#endif +return ret; +}]])],[zsh_cv_rlimit_rss_is_as=yes],[zsh_cv_rlimit_rss_is_as=no],[zsh_cv_rlimit_rss_is_as=no])]) + +if test x$zsh_cv_rlimit_rss_is_as = xyes; then + AC_DEFINE(RLIMIT_RSS_IS_AS) +fi + + +dnl -------------------------------------------- +dnl Check for members of struct rusage +dnl -------------------------------------------- +if test x$ac_cv_func_getrusage = xyes; then + AC_CHECK_MEMBERS([struct rusage.ru_maxrss, + struct rusage.ru_ixrss, + struct rusage.ru_idrss, + struct rusage.ru_isrss, + struct rusage.ru_minflt, + struct rusage.ru_majflt, + struct rusage.ru_nswap, + struct rusage.ru_inblock, + struct rusage.ru_oublock, + struct rusage.ru_msgsnd, + struct rusage.ru_msgrcv, + struct rusage.ru_nsignals, + struct rusage.ru_nvcsw, + struct rusage.ru_nivcsw],,, +[#include +#ifdef HAVE_SYS_TIME_H +#include +#endif +#include ]) +fi + + +dnl -------------------------------------------- +dnl CHECK FOR DEFAULT PATH (used for command -p) +dnl -------------------------------------------- +AC_CACHE_VAL(zsh_cv_cs_path, +[if getconf _CS_PATH >/dev/null 2>&1; then + zsh_cv_cs_path=`getconf _CS_PATH` +elif getconf CS_PATH >/dev/null 2>&1; then + zsh_cv_cs_path=`getconf CS_PATH` +elif getconf PATH >/dev/null 2>&1; then + zsh_cv_cs_path=`getconf PATH` +else + zsh_cv_cs_path="/bin:/usr/bin" +fi]) +AC_DEFINE_UNQUOTED(DEFAULT_PATH, "$zsh_cv_cs_path", +[The default path; used when running commands with command -p]) + + +dnl ---------------------------- +dnl CHECK FOR /dev/fd FILESYSTEM +dnl ---------------------------- +dnl FreeBSD 5 only supports /dev/fd/0 to /dev/fd/2 without mounting +dnl a special file system. As zsh needs arbitrary /dev/fd (typically +dnl >10) for its own use, we need to make sure higher fd's are available. +dnl Since we're using the shell, we're restricted to 0 to 9 but 3 should +dnl be good enough. +AH_TEMPLATE([PATH_DEV_FD], +[Define to the path of the /dev/fd filesystem.]) +AC_CACHE_CHECK(for /dev/fd filesystem, zsh_cv_sys_path_dev_fd, +[if test "$host_os" = cygwin; then +dnl In current (2008/12/01) versions of Cygwin these are present but don't +dnl seem to work smoothly for process substitution; no great surprise +dnl since getting processes to work at all on Cygwin is a big challenge. +dnl We'll rely on FIFOs, since they do what we need. +zsh_cv_sys_path_dev_fd=no +else +[for zsh_cv_sys_path_dev_fd in /proc/self/fd /dev/fd no; do + test x`echo ok|(exec 3<&0; cat $zsh_cv_sys_path_dev_fd/3 2>/dev/null;)` = xok && break + done] +fi]) +if test x$zsh_cv_sys_path_dev_fd != xno; then + AC_DEFINE_UNQUOTED(PATH_DEV_FD, "$zsh_cv_sys_path_dev_fd") +fi + +dnl --------------------------------- +dnl CHECK FOR RFS SUPERROOT DIRECTORY +dnl --------------------------------- +AC_CACHE_CHECK(for RFS superroot directory, zsh_cv_sys_superroot, +[test -d /../.LOCALROOT && zsh_cv_sys_superroot=yes || zsh_cv_sys_superroot=no]) +AH_TEMPLATE([HAVE_SUPERROOT], +[Define to 1 if you have RFS superroot directory.]) +if test x$zsh_cv_sys_superroot = xyes; then + AC_DEFINE(HAVE_SUPERROOT) +fi + +dnl CHECK FOR SYSTEMS REQUIRING GETCWD +AC_CACHE_CHECK(whether we should use the native getcwd, +zsh_cv_use_getcwd, +[case "${host_cpu}-${host_vendor}-${host_os}" in + *QNX*) zsh_cv_use_getcwd=yes ;; + *) zsh_cv_use_getcwd=no ;; + esac]) +AH_TEMPLATE([USE_GETCWD], +[Define to 1 if you need to use the native getcwd.]) +if test x$zsh_cv_use_getcwd = xyes; then + AC_DEFINE(USE_GETCWD) +fi + +dnl GNU getcwd() can allocate as much space as necessary for a +dnl directory name, preventing guessing games. +AH_TEMPLATE([GETCWD_CALLS_MALLOC], +[Define to 1 if getcwd() calls malloc to allocate memory.]) +if test x$ac_cv_func_getcwd = xyes; then + AC_CACHE_CHECK(whether getcwd calls malloc to allocate memory, + zsh_cv_getcwd_malloc, + [AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include +#include +int main() { + char buf[1024], *ptr1, *ptr2; + ptr1 = getcwd(buf, 1024); + ptr2 = getcwd(NULL, 0); + if (ptr1 && ptr2 && !strcmp(ptr1, ptr2)) { + return 0; + } + return 1; +} +]])],[zsh_cv_getcwd_malloc=yes],[zsh_cv_getcwd_malloc=no],[zsh_cv_getcwd_malloc=no])]) + if test x$zsh_cv_getcwd_malloc = xyes; then + AC_DEFINE(GETCWD_CALLS_MALLOC) + fi +fi + +dnl CHECK FOR setproctitle() FOR jobs -Z / ARGV0 +AH_TEMPLATE([HAVE_SETPROCTITLE], +[Define to 1 if the system supports `setproctitle' to change process name]) +AC_CHECK_FUNC(setproctitle,AC_DEFINE(HAVE_SETPROCTITLE), +AC_SEARCH_LIBS(setproctitle,util,AC_DEFINE(HAVE_SETPROCTITLE))) + +dnl ------------- +dnl CHECK FOR NIS +dnl ------------- +AH_TEMPLATE([HAVE_NIS], +[Define to 1 if you have NIS.]) +AC_CACHE_CHECK(for NIS, zsh_cv_sys_nis, +[test -f /usr/bin/ypcat && /usr/bin/ypcat passwd.byname > /dev/null 2>&1 && \ +zsh_cv_sys_nis=yes || zsh_cv_sys_nis=no]) +if test x$zsh_cv_sys_nis = xyes; then + AC_DEFINE(HAVE_NIS) +dnl Some systems (Solaris 2.x, Linux Redhat 5.x) require +dnl libnsl (Network Services Library) to find yp_all + AC_SEARCH_LIBS(yp_all, nsl) +fi + +dnl ----------------- +dnl CHECK FOR NISPLUS +dnl ----------------- +AH_TEMPLATE([HAVE_NIS_PLUS], +[Define to 1 if you have NISPLUS.]) +AC_CACHE_CHECK(for NIS+, zsh_cv_sys_nis_plus, +[test x$ac_cv_func_nis_list = xyes && test -f /usr/bin/nisls && \ + /usr/bin/nisls > /dev/null 2>&1 && \ +zsh_cv_sys_nis_plus=yes || zsh_cv_sys_nis_plus=no]) +if test x$zsh_cv_sys_nis_plus = xyes; then + AC_DEFINE(HAVE_NIS_PLUS) +fi + +dnl ---------------------------------------- +dnl CHECK FOR LOCATION OF {U,W}TMP{,X} FILES +dnl ---------------------------------------- +zsh_PATH_UTMP(utmp) +zsh_PATH_UTMP(wtmp) +zsh_PATH_UTMP(utmpx) +zsh_PATH_UTMP(wtmpx) + +dnl ------------------- +dnl brk/sbrk PROTOTYPES +dnl ------------------- +AC_CACHE_CHECK(for brk() prototype in , +zsh_cv_header_unistd_h_brk_proto, +[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include +double brk();]], [[int i;]])],[zsh_cv_header_unistd_h_brk_proto=no],[zsh_cv_header_unistd_h_brk_proto=yes])]) +AH_TEMPLATE([HAVE_BRK_PROTO], +[Define to 1 if there is a prototype defined for brk() on your system.]) +if test x$zsh_cv_header_unistd_h_brk_proto = xyes; then + AC_DEFINE(HAVE_BRK_PROTO) +fi + +AC_CACHE_CHECK(for sbrk() prototype in , +zsh_cv_header_unistd_h_sbrk_proto, +[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include +double sbrk();]], [[int i;]])],[zsh_cv_header_unistd_h_sbrk_proto=no],[zsh_cv_header_unistd_h_sbrk_proto=yes])]) +AH_TEMPLATE([HAVE_SBRK_PROTO], +[Define to 1 if there is a prototype defined for sbrk() on your system.]) +if test x$zsh_cv_header_unistd_h_sbrk_proto = xyes; then + AC_DEFINE(HAVE_SBRK_PROTO) +fi + +dnl ----------------------- +dnl mknod prototype for OSF +dnl ----------------------- +AH_TEMPLATE([HAVE_MKNOD_PROTO], +[Define to 1 if there is a prototype defined for mknod() on your system.]) +if test "$ac_cv_prog_cc_stdc" != no; then + AC_CACHE_CHECK(for mknod prototype in , + zsh_cv_header_sys_stat_h_mknod_proto, + [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include + int mknod(double x);]], [[int i;]])],[zsh_cv_header_sys_stat_h_mknod_proto=no],[zsh_cv_header_sys_stat_h_mknod_proto=yes])]) + if test x$zsh_cv_header_sys_stat_h_mknod_proto = xyes; then + AC_DEFINE(HAVE_MKNOD_PROTO) + fi +fi + +dnl ---------------------------------------- +dnl presence and location of ioctl prototype +dnl ---------------------------------------- +AC_CACHE_CHECK(for ioctl prototype in or , +zsh_cv_header_unistd_h_termios_h_ioctl_proto, +[AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[ +#ifdef HAVE_UNISTD_H +# include +#endif +#ifdef HAVE_TERMIOS_H +# include +#endif +double ioctl();]], [[int i;]])],[zsh_cv_header_unistd_h_termios_h_ioctl_proto=no],[zsh_cv_header_unistd_h_termios_h_ioctl_proto=yes])]) + +if test x$zsh_cv_header_unistd_h_termios_h_ioctl_proto = xno; then + AC_CACHE_CHECK(for ioctl prototype in , + zsh_cv_header_sys_ioctl_h_ioctl_proto, + [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include + double ioctl();]], [[int i;]])],[zsh_cv_header_sys_ioctl_h_ioctl_proto=no],[zsh_cv_header_sys_ioctl_h_ioctl_proto=yes])]) +else + zsh_cv_header_sys_ioctl_h_ioctl_proto=no +fi + +AH_TEMPLATE([HAVE_IOCTL_PROTO], +[Define to 1 if there is a prototype defined for ioctl() on your system.]) +if test x$zsh_cv_header_unistd_h_termios_h_ioctl_proto = xyes || \ + test x$zsh_cv_header_sys_ioctl_h_ioctl_proto = xyes; then + AC_DEFINE(HAVE_IOCTL_PROTO) +fi +AH_TEMPLATE([IOCTL_IN_SYS_IOCTL], +[Define to 1 if we must include to get a prototype for ioctl().]) +if test x$zsh_cv_header_sys_ioctl_h_ioctl_proto = xyes; then + AC_DEFINE(IOCTL_IN_SYS_IOCTL) +fi + +dnl ------------------- +dnl select() defined in , ie BeOS R4.51 +dnl ------------------- +AH_TEMPLATE([SELECT_IN_SYS_SOCKET_H], +[Define to 1 if select() is defined in , ie BeOS R4.51]) +if test x$ac_cv_header_sys_select_h != xyes; then + AC_CACHE_CHECK(for select() in , + zsh_cv_header_socket_h_select_proto, + [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#include ]], [[fd_set fd;]])],[zsh_cv_header_socket_h_select_proto=yes],[zsh_cv_header_socket_h_select_proto=no])]) + if test x$zsh_cv_header_socket_h_select_proto = xyes; then + AC_DEFINE(SELECT_IN_SYS_SOCKET_H) + fi +fi + +dnl ----------- +dnl named FIFOs +dnl ----------- +dnl +dnl Named FIFOs work well enough on recent versions of Cygwin +dnl to provide what we want. Simply enable them. +AC_CACHE_CHECK(if named FIFOs work, +zsh_cv_sys_fifo, +[if test "$host_os" = cygwin; then +zsh_cv_sys_fifo=yes +else +AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include +#include +main() +{ + char c; + int fd; + int pid, ret; + unlink("/tmp/fifo$$"); +#ifdef HAVE_MKFIFO + if(mkfifo("/tmp/fifo$$", 0600) < 0) +#else + if(mknod("/tmp/fifo$$", 0010600, 0) < 0) +#endif + exit(1); + pid = fork(); + if(pid < 0) + exit(1); + if(pid) { + fd = open("/tmp/fifo$$", O_RDONLY); + exit(fd < 0 || read(fd, &c, 1) != 1 || c != 'x'); + } + fd = open("/tmp/fifo$$", O_WRONLY); + ret = (fd < 0 || write(fd, "x", 1) < 1); + unlink("/tmp/fifo$$"); + exit(ret); +} +]])],[zsh_cv_sys_fifo=yes],[zsh_cv_sys_fifo=no],[zsh_cv_sys_fifo=yes]) +fi]) +AH_TEMPLATE([HAVE_FIFOS], +[Define to 1 if system has working FIFOs.]) +if test x$zsh_cv_sys_fifo = xyes; then + AC_DEFINE(HAVE_FIFOS) +fi + +dnl ----------- +dnl test for whether link() works +dnl for instance, BeOS R4.51 doesn't support hard links yet +dnl ----------- +AC_CACHE_CHECK(if link() works, +zsh_cv_sys_link, +[AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include +#include +main() +{ + int ret; + char *tmpfile, *newfile; + tmpfile="/tmp/zsh.linktest$$"; + newfile="/tmp/zsh.linktest2$$"; + unlink(tmpfile); + unlink(newfile); + if(creat(tmpfile, 0644) < 0) + exit(1); + ret = link(tmpfile, newfile); + unlink(tmpfile); + unlink(newfile); + exit(ret<0); +} +]])],[zsh_cv_sys_link=yes],[zsh_cv_sys_link=no],[zsh_cv_sys_link=yes])]) +AH_TEMPLATE([HAVE_LINK], +[Define to 1 if system has working link().]) +if test x$zsh_cv_sys_link = xyes; then + AC_DEFINE(HAVE_LINK) +fi + +dnl ----------- +dnl test for whether kill(pid, 0) where pid doesn't exit +dnl should set errno to ESRCH, but some like BeOS R4.51 set to EINVAL +dnl ----------- +AC_CACHE_CHECK(if kill(pid, 0) returns ESRCH correctly, +zsh_cv_sys_killesrch, +[AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include +#include +#include +main() +{ + int pid = (getpid() + 10000) & 0xffffff; + while (pid && (kill(pid, 0) == 0 || errno != ESRCH)) pid >>= 1; + exit(errno!=ESRCH); +} +]])],[zsh_cv_sys_killesrch=yes],[zsh_cv_sys_killesrch=no],[zsh_cv_sys_killesrch=yes])]) +AH_TEMPLATE([BROKEN_KILL_ESRCH], +[Define to 1 if kill(pid, 0) doesn't return ESRCH, ie BeOS R4.51.]) +if test x$zsh_cv_sys_killesrch = xno; then + AC_DEFINE(BROKEN_KILL_ESRCH) +fi + +dnl ----------- +dnl if POSIX, test for working sigsuspend(). +dnl for instance, BeOS R4.51 is broken. +dnl ----------- +AH_TEMPLATE([BROKEN_POSIX_SIGSUSPEND], +Define to 1 if sigsuspend() is broken, ie BeOS R4.51.]) +if test x$signals_style = xPOSIX_SIGNALS; then + AC_CACHE_CHECK(if POSIX sigsuspend() works, + zsh_cv_sys_sigsuspend, + [AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include +#include +int child=0; +void handler(sig) + int sig; +{if(sig==SIGCHLD) child=1;} +main() { + struct sigaction act; + sigset_t set; + int pid, ret; + act.sa_handler = &handler; + sigfillset(&act.sa_mask); + act.sa_flags = 0; + sigaction(SIGCHLD, &act, 0); + sigfillset(&set); + sigprocmask(SIG_SETMASK, &set, 0); + pid=fork(); + if(pid==0) return 0; + if(pid>0) { + sigemptyset(&set); + ret=sigsuspend(&set); + exit(child==0); + } +} +]])],[zsh_cv_sys_sigsuspend=yes],[zsh_cv_sys_sigsuspend=no],[zsh_cv_sys_sigsuspend=yes])]) + if test x$zsh_cv_sys_sigsuspend = xno; then + AC_DEFINE(BROKEN_POSIX_SIGSUSPEND) + fi +fi + +dnl ----------- +dnl if found tcsetpgrp, test to see if it actually works +dnl for instance, BeOS R4.51 does not support it yet +dnl ----------- +AH_TEMPLATE([BROKEN_TCSETPGRP], +[Define to 1 if tcsetpgrp() doesn't work, ie BeOS R4.51.]) +AC_ARG_WITH(tcsetpgrp, +AS_HELP_STRING([--with-tcsetpgrp],[assumes that tcsetpgrp() exists and works correctly]),[ +case "x$withval" in + xyes) zsh_working_tcsetpgrp=yes;; + xno) zsh_working_tcsetpgrp=no;; + *) AC_MSG_ERROR(please use --with-tcsetpgrp=yes or --with-tcsetpgrp=no);; +esac],[zsh_working_tcsetpgrp=check]) +if test "x$ac_cv_func_tcsetpgrp" = xyes; then +case "x$zsh_working_tcsetpgrp" in + xcheck) + trap "" TTOU > /dev/null 2>&1 || : + AC_CACHE_CHECK(if tcsetpgrp() actually works, + zsh_cv_sys_tcsetpgrp, + [AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include +#include +#include +main() { + int fd; + int ret; + fd=open("/dev/tty", O_RDWR); + if (fd < 0) exit(2); + ret=tcsetpgrp(fd, tcgetpgrp(fd)); + if (ret < 0) exit(1); + exit(0); +} +]])],[zsh_cv_sys_tcsetpgrp=yes],[ +case $? in + 1) zsh_cv_sys_tcsetpgrp=no;; + 2) zsh_cv_sys_tcsetpgrp=notty;; + *) zsh_cv_sys_tcsetpgrp=error;; +esac + ],[zsh_cv_sys_tcsetpgrp=yes])]) + case "x$zsh_cv_sys_tcsetpgrp" in + xno) AC_DEFINE(BROKEN_TCSETPGRP);; + xyes) :;; + xnotty) AC_MSG_ERROR([no controlling tty +Try running configure with --with-tcsetpgrp or --without-tcsetpgrp]);; + *) AC_MSG_ERROR([unexpected return status]);; + esac + trap - TTOU > /dev/null 2>&1 || : + ;; + xyes) :;; + xno) AC_DEFINE(BROKEN_TCSETPGRP);; + *) AC_MSG_ERROR([unexpected value zsh_working_tcsetpgrp=$zsh_working_tcsetpgrp]);; +esac +fi + +dnl ----------- +dnl test for faked getpwnam() entry, ie a single entry returned for any username +dnl for instance, BeOS R4.51 is not multiuser yet, and fakes getpwnam() +dnl test by looking up two usernames that shouldn't succeed, and compare entry +dnl ----------- +AH_TEMPLATE([GETPWNAM_FAKED], +[Define to 1 if getpwnam() is faked, ie BeOS R4.51.]) +if test x$ac_cv_func_getpwnam = xyes; then + AC_CACHE_CHECK(if getpwnam() is faked, + zsh_cv_sys_getpwnam_faked, + [AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include +main() { + struct passwd *pw1, *pw2; + char buf[1024], name[1024]; + sprintf(buf, "%d:%d", getpid(), rand()); + pw1=getpwnam(buf); + if (pw1) strcpy(name, pw1->pw_name); + sprintf(buf, "%d:%d", rand(), getpid()); + pw2=getpwnam(buf); + exit(pw1!=0 && pw2!=0 && !strcmp(name, pw2->pw_name)); +} +]])],[zsh_cv_sys_getpwnam_faked=no],[zsh_cv_sys_getpwnam_faked=yes],[zsh_cv_sys_getpwnam_faked=no])]) + if test x$zsh_cv_sys_getpwnam_faked = xyes; then + AC_DEFINE(GETPWNAM_FAKED) + fi +fi + + +dnl --------------- +dnl check for the type of third argument of accept +dnl --------------- + +zsh_CHECK_SOCKLEN_T + +dnl --------------- +dnl Check for pty multiplexer for use in pty module. +dnl We need to open it read/write, so make sure it is writeable. +dnl Yet another test which won't work when cross-compiling. +dnl --------------- +AC_CACHE_CHECK(if your system has /dev/ptmx, +ac_cv_have_dev_ptmx, +[if test -w /dev/ptmx; then + ac_cv_have_dev_ptmx=yes +else + ac_cv_have_dev_ptmx=no +fi]) + +dnl -------- +dnl Check if the ptmx functions are usable. +dnl We need to be able to find the prototypes, which may +dnl require non-POSIX source definitions. So test to see +dnl if ptsname is correctly recognised as returning a char *. +dnl We do this by making sure a program where ptsname() is declared +dnl as returning int does *not* compile. +dnl On Linux we need the XOPEN extensions. The easiest way to get +dnl these is by defining _GNU_SOURCE. +dnl ------- +AH_TEMPLATE([USE_DEV_PTMX], +[Define to 1 if all the kit for using /dev/ptmx for ptys is available.]) +if test x$ac_cv_have_dev_ptmx = xyes -o x$ac_cv_func_posix_openpt = xyes && \ + test x$ac_cv_func_grantpt = xyes && \ + test x$ac_cv_func_unlockpt = xyes && \ + test x$ac_cv_func_ptsname = xyes; then + AC_CACHE_CHECK([if /dev/ptmx is usable], + ac_cv_use_dev_ptmx, + [AC_COMPILE_IFELSE([AC_LANG_PROGRAM([[#ifdef __linux +#define _GNU_SOURCE 1 +#endif +#include +int ptsname();]], [[]])],[ac_cv_use_dev_ptmx=no],[ac_cv_use_dev_ptmx=yes])]) + if test x$ac_cv_use_dev_ptmx = xyes; then + AC_DEFINE(USE_DEV_PTMX) + fi +fi + +dnl ----------------- +dnl multibyte support +dnl ----------------- +AC_ARG_ENABLE(multibyte, +AS_HELP_STRING([--enable-multibyte],[support multibyte characters]), +[zsh_cv_c_unicode_support=$enableval], +[AC_CACHE_VAL(zsh_cv_c_unicode_support, + AC_MSG_NOTICE([checking for functions supporting multibyte characters]) + [zfuncs_absent= +dnl +dnl Note that iswblank is not included and checked separately. +dnl As iswblank() was added to C long after the others, we still +dnl want to enabled unicode support even if iswblank is not available +dnl (we then just do the SPC+TAB approximation) +dnl + for zfunc in iswalnum iswcntrl iswdigit iswgraph iswlower iswprint \ +iswpunct iswspace iswupper iswxdigit mbrlen mbrtowc towupper towlower \ +wcschr wcscpy wcslen wcsncmp wcsncpy wcrtomb wcwidth wmemchr wmemcmp \ +wmemcpy wmemmove wmemset; do + AC_CHECK_FUNC($zfunc, + [:], [zfuncs_absent="$zfuncs_absent $zfunc"]) + done + if test x"$zfuncs_absent" = x; then + AC_MSG_NOTICE([all functions found, multibyte support enabled]) + zsh_cv_c_unicode_support=yes + else + AC_MSG_NOTICE([missing functions, multibyte support disabled]) + zsh_cv_c_unicode_support=no + fi + ]) +]) +AH_TEMPLATE([MULTIBYTE_SUPPORT], +[Define to 1 if you want support for multibyte character sets.]) + +dnl +dnl unicode9 support +dnl +AH_TEMPLATE([ENABLE_UNICODE9], +[Define to 1 if you want use unicode9 character widths.]) +AC_ARG_ENABLE(unicode9, +AS_HELP_STRING([--enable-unicode9],[compile with unicode9 character widths]), +[if test x$enableval = xyes; then + AC_DEFINE(ENABLE_UNICODE9) +fi]) + +AH_TEMPLATE([BROKEN_ISPRINT], +[Define to 1 if the isprint() function is broken under UTF-8 locale.]) + +if test x$zsh_cv_c_unicode_support = xyes; then + AC_DEFINE(MULTIBYTE_SUPPORT) + + dnl Test if wcwidth() and/or iswprint() is broken for + dnl zero-width combining characters, or + dnl some characters in the Latin Extended-B. + dnl If either of the functions is broken, both functions will be replaced + dnl by the ones from wcwidth9.h by defining ENABLE_UNICODE9. We will do + dnl this only if __STDC_ISO_10646__ is defined (or if building on macOS, + dnl where __STDC_ISO_10646__ is not defined but wchar_t is UCS). + dnl For the test we use a combining acute accent (\u0301) or + dnl a LATIN SMALL LETTER L WITH CURL (\u0234). + dnl We input it as UTF-8 since that is the standard we can rely + dnl upon most: we can't rely on a wchar_t being stored as a + dnl Unicode code point on all systems. + dnl The programme returns 0 only if all the conditions for brokenness + dnl are met: + dnl - the programme compiled, linked and ran + dnl - we successfully set a UTF-8 locale + dnl - the locale we set plausibly converted the UTF-8 string + dnl into the correct wide character + dnl - but wcwidth() or iswprint() is broken for the converted wide character. + dnl locale -a is a fallback; on most systems we should find en_US.UTF-8. + [locale_prog='char *my_locales[] = { + "en_US.UTF-8", "en_GB.UTF-8", "en.UTF-8", ' + locale_prog="$locale_prog"`locale -a 2>/dev/null | \ + sed -e 's/utf8/UTF-8/' | grep UTF-8 | \ + while read line; do echo " \"$line\","; done;` + locale_prog="$locale_prog 0 }; + #define _XOPEN_SOURCE + #include + #include + #include + #include + + int main() { + char **localep; + char comb_acute_mb[] = { (char)0xcc, (char)0x81 }; + char u_0234[] = { (char)0xc8, (char)0xb4 }; + wchar_t wc; + #if !defined(__STDC_ISO_10646__) && !defined(__APPLE__) + return 1; + #endif + + for (localep = my_locales; *localep; localep++) + if (setlocale(LC_ALL, *localep)) + break; + if (!*localep) + return 1; + if (mbtowc(&wc, comb_acute_mb, 2) == 2 && (wcwidth(wc) != 0 || !iswprint(wc))) + return 0; + if (mbtowc(&wc, u_0234, 2) == 2 && (wcwidth(wc) != 1 || !iswprint(wc))) + return 0; + return 1; + } + "] + + AC_CACHE_CHECK(if the wcwidth() and/or iswprint() functions are broken, + zsh_cv_c_broken_wcwidth, + [AC_RUN_IFELSE([AC_LANG_SOURCE([[$locale_prog]])],[zsh_cv_c_broken_wcwidth=yes],[zsh_cv_c_broken_wcwidth=no],[zsh_cv_c_broken_wcwidth=no])]) + if test x$zsh_cv_c_broken_wcwidth = xyes; then + AC_DEFINE(ENABLE_UNICODE9) + fi + + dnl Check if isprint() behaves correctly under UTF-8 locale. + dnl On some platform (maybe only on Mac OS X), isprint() returns + dnl true for all characters in the range from 0xa0 to 0xff if + dnl called under UTF-8 locale. + [locale_prog='char *my_locales[] = { + "en_US.UTF-8", "en_GB.UTF-8", "en.UTF-8", ' + locale_prog="$locale_prog"`locale -a 2>/dev/null | \ + sed -e 's/utf8/UTF-8/' | grep UTF-8 | \ + while read line; do echo " \"$line\","; done;` + locale_prog="$locale_prog 0 }; + #include + #include + + int main() { + char **localep; + for (localep = my_locales; *localep; localep++) + if (setlocale(LC_ALL, *localep) && isprint(0xa0)) + return 0; + return 1; + } + "] + + AC_CACHE_CHECK(if the isprint() function is broken, + zsh_cv_c_broken_isprint, + [AC_RUN_IFELSE([AC_LANG_SOURCE([[$locale_prog]])],[zsh_cv_c_broken_isprint=yes],[zsh_cv_c_broken_isprint=no],[zsh_cv_c_broken_isprint=no])]) + if test x$zsh_cv_c_broken_isprint = xyes; then + AC_DEFINE(BROKEN_ISPRINT) + fi +fi + +dnl +dnl musl support +dnl +AH_TEMPLATE([LIBC_MUSL], +[Define to 1 if musl is being used as the C library]) +AC_ARG_ENABLE(libc-musl, +AS_HELP_STRING([--enable-libc-musl],[compile with musl as the C library]), +[if test x$enableval = xyes; then + AC_DEFINE(LIBC_MUSL) +fi]) + +dnl +dnl static user lookup +dnl +AC_ARG_ENABLE(dynamic-nss, + AS_HELP_STRING([--disable-dynamic-nss],[do not call + functions that will require dynamic NSS + modules]), +[zsh_cv_c_dynamic_nss=$enableval], +[]) + +AH_TEMPLATE([DISABLE_DYNAMIC_NSS], +[Define to 1 if you want to avoid calling functions that will require + dynamic NSS modules.]) +if test x$zsh_cv_c_dynamic_nss = xno; then + AC_DEFINE(DISABLE_DYNAMIC_NSS) +fi + +dnl --------------- +dnl dynamic loading +dnl --------------- +AH_TEMPLATE([HPUX10DYNAMIC], +[Define to 1 if you want to use dynamically loaded modules on HPUX 10.]) +L=N +INSTLIB="install.bin-\$(L)" +UNINSTLIB="uninstall.bin-\$(L)" +LINKMODS=NOLINKMODS +MOD_EXPORT= +MOD_IMPORT_VARIABLE= +MOD_IMPORT_FUNCTION= +aixdynamic=no +hpuxdynamic=no +if test "$ac_cv_func_load" = yes && + test "$ac_cv_func_unload" = yes && + test "$ac_cv_func_loadbind" = yes && + test "$ac_cv_func_loadquery" = yes; then + dnl Force AIXDYNAMIC even on newer versions that have dl family + if test "x$dynamic" = xyes; then + aixdynamic=yes + fi +elif test "$ac_cv_func_dlopen" != yes || + test "$ac_cv_func_dlsym" != yes || + test "$ac_cv_func_dlerror" != yes; then + if test "$ac_cv_func_shl_load" != yes || + test "$ac_cv_func_shl_unload" != yes || + test "$ac_cv_func_shl_findsym" != yes; then + dynamic=no + elif test "x$dynamic" = xyes; then + hpuxdynamic=yes + DL_EXT="${DL_EXT=sl}" + dnl autoheader won't allow us to define anything which isn't + dnl going into a header, and we can't undefine anything, so + dnl just define this anyway and rely on the later tests to + dnl define DYNAMIC or not. + AC_DEFINE(HPUX10DYNAMIC)dnl + fi +fi + +test -n "$GCC" && LDARG=-Wl, + +AH_TEMPLATE([DLSYM_NEEDS_UNDERSCORE], +[Define to 1 if an underscore has to be prepended to dlsym() argument.]) +AH_TEMPLATE([DYNAMIC_NAME_CLASH_OK], +[Define to 1 if multiple modules defining the same symbol are OK.]) +if test "x$aixdynamic" = xyes; then + DL_EXT="${DL_EXT=so}" + DLLD="${DLLD=$CC}" + zsh_cv_func_dlsym_needs_underscore=no + if test -n "$GCC"; then + DLLDFLAGS=${DLLDFLAGS=-shared} + else + DLLDFLAGS=${DLLDFLAGS=-bM:SRE} + fi + DLLDFLAGS=${DLLDFLAGS=} + EXTRA_LDFLAGS=${EXTRA_LDFLAGS=} + EXPOPT=${LDARG}-bE: + IMPOPT=${LDARG}-bI: + zsh_cv_sys_dynamic_clash_ok="${zsh_cv_sys_dynamic_clash_ok=yes}" + zsh_cv_sys_dynamic_rtld_global="${zsh_cv_sys_dynamic_rtld_global=yes}" + zsh_cv_sys_dynamic_execsyms="${zsh_cv_sys_dynamic_execsyms=yes}" + zsh_cv_sys_dynamic_strip_exe="${zsh_cv_sys_dynamic_strip_exe=yes}" + zsh_cv_sys_dynamic_strip_lib="${zsh_cv_sys_dynamic_strip_lib=yes}" + zsh_cv_shared_environ="${zsh_cv_shared_environ=yes}" +elif test "$host_os" = cygwin; then + DL_EXT="${DL_EXT=dll}" +##DLLD="${DLLD=dllwrap}" + DLLD="${DLLD=$CC}" +##DLLDFLAGS="${DLLDFLAGS=--export-all-symbols}" + DLLDFLAGS=${DLLDFLAGS=-shared -Wl,--export-all-symbols} + zsh_cv_func_dlsym_needs_underscore=no + DLLDFLAGS=${DLLDFLAGS=} + EXTRA_LDFLAGS=${EXTRA_LDFLAGS=} + zsh_cv_sys_dynamic_clash_ok="${zsh_cv_sys_dynamic_clash_ok=no}" + zsh_cv_sys_dynamic_rtld_global="${zsh_cv_sys_dynamic_rtld_global=yes}" + zsh_cv_sys_dynamic_execsyms="${zsh_cv_sys_dynamic_execsyms=no}" + zsh_cv_sys_dynamic_strip_exe="${zsh_cv_sys_dynamic_strip_exe=yes}" + zsh_cv_sys_dynamic_strip_lib="${zsh_cv_sys_dynamic_strip_lib=yes}" + # + # THAT SUCKS! and must be changed + # + zsh_cv_shared_environ="${zsh_cv_shared_environ=yes}" + LINKMODS=LINKMODS + MOD_EXPORT="__attribute__((__dllexport__))" + MOD_IMPORT_VARIABLE="__attribute__((__dllimport__))" + MOD_IMPORT_FUNCTION= +elif test "x$dynamic" = xyes; then + AC_CACHE_CHECK(if your system uses ELF binaries, + zsh_cv_sys_elf, + [AC_RUN_IFELSE([AC_LANG_SOURCE([[/* Test for whether ELF binaries are produced */ +#include +#include +main(argc, argv) +int argc; +char *argv[]; +{ + char b[4]; + int i = open(argv[0],O_RDONLY); + if(i == -1) + exit(1); /* fail */ + if(read(i,b,4)==4 && b[0]==127 && b[1]=='E' && b[2]=='L' && b[3]=='F') + exit(0); /* succeed (yes, it's ELF) */ + else + exit(1); /* fail */ +}]])],[zsh_cv_sys_elf=yes],[zsh_cv_sys_elf=no],[zsh_cv_sys_elf=yes])]) + + # We use [0-9]* in case statements, so need to change quoting + changequote(, ) + + DL_EXT="${DL_EXT=so}" + if test x$zsh_cv_sys_elf = xyes; then + case "$host" in + mips-sni-sysv4*) + # Forcibly set ld to native compiler to avoid obscure GCC problems + DLLD="${DLLD=/usr/ccs/bin/cc}" + DLLDARG="${LDARG}" + ;; + * ) + DLLD="${DLLD=$CC}" + DLLDARG="${LDARG}" + ;; + esac + else + case "$host" in + *openbsd*) + case "$host_os" in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + DLLD="${DLLD=ld}" + ;; + *) + DLLD="${DLLD=$CC}" + ;; + esac + DLLDARG="${LDARG}" + ;; + *darwin*) + DLLD="${DLLD=$CC}" + DLLDARG="" + ;; + *interix*) + DLLD="${DLLD=$CC}" + DLLDARG="" + ;; + * ) + DLLD="${DLLD=ld}" + DLLDARG="" + ;; + esac + fi + if test -n "$GCC"; then + case "$host_os" in + hpux*) DLLDFLAGS="${DLLDFLAGS=-shared}" ;; + darwin*) DLCFLAGS="${DLCFLAGS=-fno-common}" ;; + interix*) DLCFLAGS="${DLCFLAGS=}" ;; + *) DLCFLAGS="${DLCFLAGS=-fPIC}" ;; + esac + else + case "$host_os" in + hpux*) + DLCFLAGS="${DLCFLAGS=+z}" + DLLDFLAGS="${DLLDFLAGS=-b}" + ;; + sunos*) DLCFLAGS="${DLCFLAGS=-pic}" ;; + solaris*|sysv4*|esix*) DLCFLAGS="${DLCFLAGS=-KPIC}" ;; + esac + fi + case "$host_os" in + osf*) DLLDFLAGS="${DLLDFLAGS=-shared -expect_unresolved '*'}" ;; + *freebsd*|*netbsd*|linux*|irix*|gnu*|interix*|dragonfly*) DLLDFLAGS="${DLLDFLAGS=-shared}" ;; + sunos*) DLLDFLAGS="${DLLDFLAGS=-assert nodefinitions}" ;; + sysv4*|esix*) DLLDFLAGS="${DLLDFLAGS=-G $ldflags}" ;; + aix*) DLLDFLAGS="${DLLDFLAGS=-G -bexpall -lc}" ;; + solaris*|sysv4*|esix*) DLLDFLAGS="${DLLDFLAGS=-G}" ;; + darwin*) DLLDFLAGS="${DLLDFLAGS=-bundle -flat_namespace -undefined suppress}" ;; + beos*|haiku*) DLLDFLAGS="${DLLDFLAGS=-nostart}" ;; + openbsd*) + if test x$zsh_cv_sys_elf = xyes; then + DLLDFLAGS="${DLLDFLAGS=-shared -fPIC}" + else + case "$host_os" in + openbsd[01].* | openbsd2.[0-7] | openbsd2.[0-7].*) + DLLDFLAGS="${DLLDFLAGS=-Bshareable}" + ;; + *) + DLLDFLAGS="${DLLDFLAGS=-shared -fPIC}" + ;; + esac + fi + ;; + esac + case "$host" in + *-hpux*) EXTRA_LDFLAGS="${EXTRA_LDFLAGS=-Wl,-E}" ;; + *openbsd*) + if test x$zsh_cv_sys_elf = xyes; then + EXTRA_LDFLAGS="${EXTRA_LDFLAGS=-Wl,-E}" + fi + ;; + mips-sni-sysv4) + # + # unfortunately, we have different compilers + # that need different flags + # + if test -n "$GCC"; then + sni_cc_version=GCC + else + sni_cc_version=`$CC -V 2>&1 | head -1` + fi + case "$sni_cc_version" in + *CDS*|GCC ) + EXTRA_LDFLAGS="${EXTRA_LDFLAGS=-Wl,-Blargedynsym}" + ;; + * ) + EXTRA_LDFLAGS="${EXTRA_LDFLAGS=-LD-Blargedynsym}" + ;; + esac + ;; + *-beos*) + # gcc on BeOS doesn't like -rdynamic... + EXTRA_LDFLAGS="${EXTRA_LDFLAGS= }" + # also, dlopen() at least in Zeta respects $LIBRARY_PATH, so needs %A added to it. + export LIBRARY_PATH="$LIBRARY_PATH:%A/" + ;; + *-haiku*) + # + ;; + esac + + # Done with our shell code, so restore autotools quoting + changequote([, ]) + +AC_CACHE_CHECK(if we can use -rdynamic, zsh_cv_rdynamic_available, +old_LDFLAGS="$LDFLAGS" +LDFLAGS="$LDFLAGS -rdynamic" +AC_LINK_IFELSE([AC_LANG_PROGRAM([[]], [[]])],[zsh_cv_rdynamic_available=yes +EXTRA_LDFLAGS="${EXTRA_LDFLAGS=-rdynamic}"],[zsh_cvs_rdynamic_available=no]) +LDFLAGS="$old_LDFLAGS") + AC_CACHE_CHECK(if your dlsym() needs a leading underscore, + zsh_cv_func_dlsym_needs_underscore, + [echo failed >conftestval && cat >conftest.c <&AS_MESSAGE_LOG_FD) && + AC_TRY_COMMAND($DLLD $LDFLAGS $DLLDFLAGS -o conftest.$DL_EXT conftest.o 1>&AS_MESSAGE_LOG_FD) && + AC_RUN_IFELSE([AC_LANG_SOURCE([[ +#include +#ifdef HPUX10DYNAMIC +#include +#define RTLD_LAZY BIND_DEFERRED +#define RTLD_GLOBAL DYNAMIC_PATH + +char *zsh_gl_sym_addr ; + +#define dlopen(file,mode) (void *)shl_load((file), (mode), (long) 0) +#define dlclose(handle) shl_unload((shl_t)(handle)) +#define dlsym(handle,name) (zsh_gl_sym_addr=0,shl_findsym((shl_t *)&(handle),name,TYPE_UNDEFINED,&zsh_gl_sym_addr), (void *)zsh_gl_sym_addr) +#define dlerror() 0 +#else +#ifdef HAVE_DLFCN_H +#include +#else +#include +#include +#include +#endif +#endif +#ifndef RTLD_LAZY +#define RTLD_LAZY 1 +#endif + +extern int fred() ; + +main() +{ + void * handle ; + void * symbol ; + FILE *f=fopen("conftestval", "w"); + if (!f) exit(1); + handle = dlopen("./conftest.$DL_EXT", RTLD_LAZY) ; + if (handle == NULL) { + fprintf (f, "dlopen failed") ; + exit(1); + } + symbol = dlsym(handle, "fred") ; + if (symbol == NULL) { + /* try putting a leading underscore */ + symbol = dlsym(handle, "_fred") ; + if (symbol == NULL) { + fprintf (f, "dlsym failed") ; + exit(1); + } + fprintf (f, "yes") ; + } + else + fprintf (f, "no") ; + exit(0); +}]])],[zsh_cv_func_dlsym_needs_underscore=`cat conftestval`],[zsh_cv_func_dlsym_needs_underscore=failed + dynamic=no],[zsh_cv_func_dlsym_needs_underscore=no])]) + if test "x$zsh_cv_func_dlsym_needs_underscore" = xyes; then + AC_DEFINE(DLSYM_NEEDS_UNDERSCORE) + elif test "x$zsh_cv_func_dlsym_needs_underscore" != xno; then + dnl Do not cache failed value + unset zsh_cv_func_dlsym_needs_underscore + fi +fi + +if test "x$dynamic" = xyes; then + zsh_SHARED_VARIABLE([environ], [char **]) + test "$zsh_cv_shared_environ" = yes || dynamic=no + if test "$ac_cv_func_tgetent" = yes; then + zsh_SHARED_FUNCTION([tgetent]) + fi + if test "$ac_cv_func_tigetstr" = yes; then + zsh_SHARED_FUNCTION([tigetstr]) + fi +fi + +if test "x$dynamic" = xyes; then + zsh_SYS_DYNAMIC_CLASH + zsh_SYS_DYNAMIC_GLOBAL + RTLD_GLOBAL_OK=$zsh_cv_sys_dynamic_rtld_global + zsh_SYS_DYNAMIC_EXECSYMS + if test "$zsh_cv_sys_dynamic_execsyms" != yes; then + L=L + fi + zsh_SYS_DYNAMIC_STRIP_EXE + zsh_SYS_DYNAMIC_STRIP_LIB + if $strip_exeldflags && test "$zsh_cv_sys_dynamic_strip_exe" = yes; then + EXELDFLAGS="$EXELDFLAGS -s" + fi + if $strip_libldflags && test "$zsh_cv_sys_dynamic_strip_lib" = yes; then + LIBLDFLAGS="$LIBLDFLAGS -s" + fi + if test "$host_os" = cygwin; then + INSTLIB="install.cygwin-lib" + UNINSTLIB="uninstall.cygwin-lib" + fi +else + $strip_exeldflags && EXELDFLAGS="$EXELDFLAGS -s" + $strip_libldflags && LIBLDFLAGS="$LIBLDFLAGS -s" + RTLD_GLOBAL_OK=no +fi + +AH_TEMPLATE([DYNAMIC], +[Define to 1 if you want to use dynamically loaded modules.]) +if test "x$dynamic" = xyes; then + D=D + AC_DEFINE(DYNAMIC)dnl +else + D=N +fi + +AH_TEMPLATE([AIXDYNAMIC], +[Define to 1 if you want to use dynamically loaded modules on AIX.]) +if test "x$aixdynamic" = xyes; then + E=E + AC_DEFINE(AIXDYNAMIC)dnl +else + E=N +fi + +if test "x$zsh_cv_sys_dynamic_clash_ok" = xyes; then + SHORTBOOTNAMES=yes +else + SHORTBOOTNAMES=no +fi +AC_SUBST(SHORTBOOTNAMES) + +AC_SUBST(INSTLIB)dnl +AC_SUBST(UNINSTLIB)dnl + +if test "$host_os" = cygwin; then + EXTRAZSHOBJS="$EXTRAZSHOBJS zsh.res.o" +fi + +AC_DEFINE_UNQUOTED(DL_EXT, "$DL_EXT", +[The extension used for dynamically loaded modules.])dnl +AC_SUBST(D)dnl +AC_SUBST(DL_EXT)dnl +AC_SUBST(DLLD)dnl +AC_SUBST(DLCFLAGS)dnl +AC_SUBST(DLLDFLAGS)dnl +AC_SUBST(E)dnl +AC_SUBST(EXTRA_LDFLAGS)dnl +AC_SUBST(EXPOPT)dnl +AC_SUBST(IMPOPT)dnl +AC_SUBST(L)dnl +AC_SUBST(LINKMODS)dnl +AC_SUBST(MOD_EXPORT)dnl +AC_SUBST(MOD_IMPORT_VARIABLE)dnl +AC_SUBST(MOD_IMPORT_FUNCTION)dnl +AC_SUBST(EXTRAZSHOBJS)dnl + +# Generate config.modules. We look for *.mdd files in first and second +# level subdirectories. Any existing line not containing 'auto=y' will be +# retained, provided the .mdd file itself was found. +CONFIG_MODULES=./config.modules +cat < ${CONFIG_MODULES}.sh +srcdir="$srcdir" +dynamic="$dynamic" +CONFIG_MODULES="${CONFIG_MODULES}" +EOM +cat <<\EOM >> ${CONFIG_MODULES}.sh +echo "creating ${CONFIG_MODULES}" +userlist=" " +if test -f ${CONFIG_MODULES}; then + userlist="`sed -e '/^#/d' -e '/auto=y/d' -e 's/ .*/ /' -e 's/^name=/ /' \ + ${CONFIG_MODULES}`" + mv ${CONFIG_MODULES} ${CONFIG_MODULES}.old +else + # Save testing for existence each time. + echo > ${CONFIG_MODULES}.old +fi +(echo "# Edit this file to change the way modules are loaded." +echo "# The format is strict; do not break lines or add extra spaces." +echo "# Run \`make prep' if you change anything here after compiling" +echo "# (there is no need if you change this just after the first time" +echo "# you run \`configure')." +echo "#" +echo "# Values of \`link' are \`static', \`dynamic' or \`no' to compile the" +echo "# module into the shell, link it in at run time, or not use it at all." +echo "# In the final case, no attempt will be made to compile it." +echo "# Use \`static' or \`no' if you do not have dynamic loading." +echo "#" +echo "# Values of \`load' are \`yes' or \`no'; if yes, any builtins etc." +echo "# provided by the module will be autoloaded by the main shell" +echo "# (so long as \`link' is not set to \`no')." +echo "#" +echo "# Values of \`auto' are \`yes' or \`no'. configure sets the value to" +echo "# \`yes'. If you set it by hand to \`no', the line will be retained" +echo "# when the file is regenerated in future." +echo "#" +echo "# Note that the \`functions' entry extends to the end of the line." +echo "# It should not be quoted; it is used verbatim to find files to install." +echo "#" +echo "# You will need to run \`config.status --recheck' if you add a new" +echo "# module." +echo "#" +echo "# You should not change the values for the pseudo-module zsh/main," +echo "# which is the main shell (apart from the functions entry)." +EOM +dnl The autoconf macros are only available in configure, not +dnl config.status, and only change when configure is rerun. +dnl So we need to run the autoconf tests here and store the results. +dnl We then generate config.modules, preserving any user-generated +dnl information, from config.status. +for modfile in `cd ${srcdir}; echo */*.mdd */*/*.mdd`; do + name= + link= + load= + functions= + result= + . ${srcdir}/$modfile + if test x$name != x && test x"$link" != x; then + case "$link" in + *\ *) eval "link=\`$link\`" + ;; + esac + case "${load}" in + y*) load=" load=yes" + ;; + *) load=" load=no" + ;; + esac + if test "x$functions" != x; then + # N.B. no additional quotes + f=" functions=$functions" + else + f= + fi + case "$link" in + static) result="name=$name modfile=$modfile link=static auto=yes${load}$f" + ;; + dynamic) if test x$dynamic != xno; then + result="name=$name modfile=$modfile link=dynamic\ + auto=yes${load}$f" + else + result="name=$name modfile=$modfile link=no\ + auto=yes load=no$f" + fi + ;; + either) if test x$dynamic != xno; then + result="name=$name modfile=$modfile link=dynamic\ + auto=yes${load}$f" + else + result="name=$name modfile=$modfile link=static\ + auto=yes${load}$f" + fi + ;; + *) result="name=$name modfile=$modfile link=no auto=yes load=no$f" + ;; + esac +dnl $result is the default output for config.modules. We generate +dnl code to check if we should use this. +cat <> ${CONFIG_MODULES}.sh +case "\$userlist" in + *" $name "*) grep "^name=$name " \${CONFIG_MODULES}.old;; + *) echo "$result";; +esac +EOM + fi +done +cat <<\EOM >> ${CONFIG_MODULES}.sh +) >${CONFIG_MODULES} +rm -f ${CONFIG_MODULES}.old +EOM + +dnl AH_TOP replaces the code which used to appear at the top +dnl of acconfig.h. +AH_TOP([/***** begin user configuration section *****/ + +/* Define this to be the location of your password file */ +#define PASSWD_FILE "/etc/passwd" + +/* Define this to be the name of your NIS/YP password * + * map (if applicable) */ +#define PASSWD_MAP "passwd.byname" + +/* Define to 1 if you want user names to be cached */ +#define CACHE_USERNAMES 1 + +/* Define to 1 if system supports job control */ +#define JOB_CONTROL 1 + +/* Define this if you use "suspended" instead of "stopped" */ +#define USE_SUSPENDED 1 + +/* The default history buffer size in lines */ +#define DEFAULT_HISTSIZE 30 + +/* The default editor for the fc builtin */ +#define DEFAULT_FCEDIT "vi" + +/* The default prefix for temporary files */ +#define DEFAULT_TMPPREFIX "/tmp/zsh" + +/***** end of user configuration section *****/ +/***** shouldn't have to change anything below here *****/ + +]) + +CLEAN_MK="${srcdir}/Config/clean.mk" +CONFIG_MK="${srcdir}/Config/config.mk" +dnl defs.mk is in the build tree, not the source tree +DEFS_MK="Config/defs.mk" +VERSION_MK="${srcdir}/Config/version.mk" + +AC_SUBST_FILE(CLEAN_MK)dnl +AC_SUBST_FILE(CONFIG_MK)dnl +AC_SUBST_FILE(DEFS_MK)dnl +AC_SUBST_FILE(VERSION_MK)dnl + +AC_CONFIG_FILES(Config/defs.mk Makefile Src/Makefile Test/Makefile) +AC_CONFIG_COMMANDS([config.modules], [. ./config.modules.sh]) +AC_CONFIG_COMMANDS([stamp-h], [echo >stamp-h]) + +AC_OUTPUT + +eval "zshbin1=${bindir}" +eval "zshbin2=${zshbin1}" +eval "zshman1=${mandir}" +eval "zshman2=${zshman1}" +eval "zshinfo1=${infodir}" +eval "zshinfo2=${zshinfo1}" +eval "zshfndir1=${fndir}" +eval "zshfndir2=${zshfndir1}" + +echo " +zsh configuration +----------------- +zsh version : ${VERSION} +host operating system : ${host_cpu}-${host_vendor}-${host_os} +source code location : ${srcdir} +compiler : ${CC} +preprocessor flags : ${CPPFLAGS} +executable compiler flags : ${CFLAGS}" +if test "x$dynamic" = xyes; then + echo "\ +module compiler flags : ${CFLAGS} ${DLCFLAGS}" +fi +echo "\ +executable linker flags : ${LDFLAGS} ${EXELDFLAGS} ${EXTRA_LDFLAGS}" +if test "x$dynamic" = xyes; then + echo "\ +module linker flags : ${LDFLAGS} ${LIBLDFLAGS} ${DLLDFLAGS}" +fi +echo "\ +library flags : ${LIBS} +installation basename : ${tzsh_name} +binary install path : ${zshbin2} +man page install path : ${zshman2} +info install path : ${zshinfo2}" +if test "$zshfndir2" != no; then + echo "functions install path : ${zshfndir2}" +fi +if test "x$additionalfpath" != x; then + echo "additional fpath entries : ${additionalfpath}" +fi +echo "See config.modules for installed modules and functions. +" + +case x$LIBS in + *-lgdbm*) + echo "WARNING: zsh will be linked against libgdbm. +This means the binary is covered by the GNU General Public License. +This does not affect the source code. +Run configure with --disable-gdbm if required." + ;; +esac + +exit 0 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/copy_from_zsh_src.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/copy_from_zsh_src.zsh new file mode 100755 index 00000000..89eee013 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/copy_from_zsh_src.zsh @@ -0,0 +1,29 @@ +#!/usr/bin/env zsh + +[[ -z "$1" || "$1" = "-h" || "$1" = "--help" ]] && { print "Single argument: path to Zsh source tree"; exit 0; } + +print "Will invoke git clean -dxf, 3 seconds" +sleep 3 + +git clean -dxf + +[[ ! -d "$1" ]] && { print "Path to Zsh source doesn't exist (i.e.: $1)"; exit 1; } + +local from="$1" + +autoload -Uz colors +colors + +integer count=0 + +for i in configure.ac Src/*.c Src/*.h; do + if [[ -f "$from/$i" ]]; then + cp -vf "$from/$i" "$i" && (( ++ count )) || print "${fg_bold[red]}Copy error for: $i${reset_color}" + else + print "${fg[red]}$i Doesn't exist${reset_color}" + fi +done + +echo "${fg[green]}Copied ${fg[yellow]}$count${fg[green]} files${reset_color}" + +patch -p2 -i ./patch_cfgac.diff diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/install-sh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/install-sh new file mode 100755 index 00000000..4fbbae7b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/install-sh @@ -0,0 +1,507 @@ +#!/bin/sh +# install - install a program, script, or datafile + +scriptversion=2006-10-14.15 + +# This originates from X11R5 (mit/util/scripts/install.sh), which was +# later released in X11R6 (xc/config/util/install.sh) with the +# following copyright and license. +# +# Copyright (C) 1994 X Consortium +# +# 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 +# X CONSORTIUM BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN +# AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNEC- +# TION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. +# +# Except as contained in this notice, the name of the X Consortium shall not +# be used in advertising or otherwise to promote the sale, use or other deal- +# ings in this Software without prior written authorization from the X Consor- +# tium. +# +# +# FSF changes to this file are in the public domain. +# +# Calling this script install-sh is preferred over install.sh, to prevent +# `make' implicit rules from creating a file called install from it +# when there is no Makefile. +# +# This script is compatible with the BSD install script, but was written +# from scratch. + +nl=' +' +IFS=" "" $nl" + +# set DOITPROG to echo to test this script + +# Don't use :- since 4.3BSD and earlier shells don't like it. +doit="${DOITPROG-}" +if test -z "$doit"; then + doit_exec=exec +else + doit_exec=$doit +fi + +# Put in absolute file names if you don't have them in your path; +# or use environment vars. + +mvprog="${MVPROG-mv}" +cpprog="${CPPROG-cp}" +chmodprog="${CHMODPROG-chmod}" +chownprog="${CHOWNPROG-chown}" +chgrpprog="${CHGRPPROG-chgrp}" +stripprog="${STRIPPROG-strip}" +rmprog="${RMPROG-rm}" +mkdirprog="${MKDIRPROG-mkdir}" + +posix_glob= +posix_mkdir= + +# Desired mode of installed file. +mode=0755 + +chmodcmd=$chmodprog +chowncmd= +chgrpcmd= +stripcmd= +rmcmd="$rmprog -f" +mvcmd="$mvprog" +src= +dst= +dir_arg= +dstarg= +no_target_directory= + +usage="Usage: $0 [OPTION]... [-T] SRCFILE DSTFILE + or: $0 [OPTION]... SRCFILES... DIRECTORY + or: $0 [OPTION]... -t DIRECTORY SRCFILES... + or: $0 [OPTION]... -d DIRECTORIES... + +In the 1st form, copy SRCFILE to DSTFILE. +In the 2nd and 3rd, copy all SRCFILES to DIRECTORY. +In the 4th, create DIRECTORIES. + +Options: +-c (ignored) +-d create directories instead of installing files. +-g GROUP $chgrpprog installed files to GROUP. +-m MODE $chmodprog installed files to MODE. +-o USER $chownprog installed files to USER. +-s $stripprog installed files. +-t DIRECTORY install into DIRECTORY. +-T report an error if DSTFILE is a directory. +--help display this help and exit. +--version display version info and exit. + +Environment variables override the default commands: + CHGRPPROG CHMODPROG CHOWNPROG CPPROG MKDIRPROG MVPROG RMPROG STRIPPROG +" + +while test $# -ne 0; do + case $1 in + -c) shift + continue;; + + -d) dir_arg=true + shift + continue;; + + -g) chgrpcmd="$chgrpprog $2" + shift + shift + continue;; + + --help) echo "$usage"; exit $?;; + + -m) mode=$2 + shift + shift + case $mode in + *' '* | *' '* | *' +'* | *'*'* | *'?'* | *'['*) + echo "$0: invalid mode: $mode" >&2 + exit 1;; + esac + continue;; + + -o) chowncmd="$chownprog $2" + shift + shift + continue;; + + -s) stripcmd=$stripprog + shift + continue;; + + -t) dstarg=$2 + shift + shift + continue;; + + -T) no_target_directory=true + shift + continue;; + + --version) echo "$0 $scriptversion"; exit $?;; + + --) shift + break;; + + -*) echo "$0: invalid option: $1" >&2 + exit 1;; + + *) break;; + esac +done + +if test $# -ne 0 && test -z "$dir_arg$dstarg"; then + # When -d is used, all remaining arguments are directories to create. + # When -t is used, the destination is already specified. + # Otherwise, the last argument is the destination. Remove it from $@. + for arg + do + if test -n "$dstarg"; then + # $@ is not empty: it contains at least $arg. + set fnord "$@" "$dstarg" + shift # fnord + fi + shift # arg + dstarg=$arg + done +fi + +if test $# -eq 0; then + if test -z "$dir_arg"; then + echo "$0: no input file specified." >&2 + exit 1 + fi + # It's OK to call `install-sh -d' without argument. + # This can happen when creating conditional directories. + exit 0 +fi + +if test -z "$dir_arg"; then + trap '(exit $?); exit' 1 2 13 15 + + # Set umask so as not to create temps with too-generous modes. + # However, 'strip' requires both read and write access to temps. + case $mode in + # Optimize common cases. + *644) cp_umask=133;; + *755) cp_umask=22;; + + *[0-7]) + if test -z "$stripcmd"; then + u_plus_rw= + else + u_plus_rw='% 200' + fi + cp_umask=`expr '(' 777 - $mode % 1000 ')' $u_plus_rw`;; + *) + if test -z "$stripcmd"; then + u_plus_rw= + else + u_plus_rw=,u+rw + fi + cp_umask=$mode$u_plus_rw;; + esac +fi + +for src +do + # Protect names starting with `-'. + case $src in + -*) src=./$src ;; + esac + + if test -n "$dir_arg"; then + dst=$src + dstdir=$dst + test -d "$dstdir" + dstdir_status=$? + else + + # Waiting for this to be detected by the "$cpprog $src $dsttmp" command + # might cause directories to be created, which would be especially bad + # if $src (and thus $dsttmp) contains '*'. + if test ! -f "$src" && test ! -d "$src"; then + echo "$0: $src does not exist." >&2 + exit 1 + fi + + if test -z "$dstarg"; then + echo "$0: no destination specified." >&2 + exit 1 + fi + + dst=$dstarg + # Protect names starting with `-'. + case $dst in + -*) dst=./$dst ;; + esac + + # If destination is a directory, append the input filename; won't work + # if double slashes aren't ignored. + if test -d "$dst"; then + if test -n "$no_target_directory"; then + echo "$0: $dstarg: Is a directory" >&2 + exit 1 + fi + dstdir=$dst + dst=$dstdir/`basename "$src"` + dstdir_status=0 + else + # Prefer dirname, but fall back on a substitute if dirname fails. + dstdir=` + (dirname "$dst") 2>/dev/null || + expr X"$dst" : 'X\(.*[^/]\)//*[^/][^/]*/*$' \| \ + X"$dst" : 'X\(//\)[^/]' \| \ + X"$dst" : 'X\(//\)$' \| \ + X"$dst" : 'X\(/\)' \| . 2>/dev/null || + echo X"$dst" | + sed '/^X\(.*[^/]\)\/\/*[^/][^/]*\/*$/{ + s//\1/ + q + } + /^X\(\/\/\)[^/].*/{ + s//\1/ + q + } + /^X\(\/\/\)$/{ + s//\1/ + q + } + /^X\(\/\).*/{ + s//\1/ + q + } + s/.*/./; q' + ` + + test -d "$dstdir" + dstdir_status=$? + fi + fi + + obsolete_mkdir_used=false + + if test $dstdir_status != 0; then + case $posix_mkdir in + '') + # Create intermediate dirs using mode 755 as modified by the umask. + # This is like FreeBSD 'install' as of 1997-10-28. + umask=`umask` + case $stripcmd.$umask in + # Optimize common cases. + *[2367][2367]) mkdir_umask=$umask;; + .*0[02][02] | .[02][02] | .[02]) mkdir_umask=22;; + + *[0-7]) + mkdir_umask=`expr $umask + 22 \ + - $umask % 100 % 40 + $umask % 20 \ + - $umask % 10 % 4 + $umask % 2 + `;; + *) mkdir_umask=$umask,go-w;; + esac + + # With -d, create the new directory with the user-specified mode. + # Otherwise, rely on $mkdir_umask. + if test -n "$dir_arg"; then + mkdir_mode=-m$mode + else + mkdir_mode= + fi + + posix_mkdir=false + case $umask in + *[123567][0-7][0-7]) + # POSIX mkdir -p sets u+wx bits regardless of umask, which + # is incompatible with FreeBSD 'install' when (umask & 300) != 0. + ;; + *) + tmpdir=${TMPDIR-/tmp}/ins$RANDOM-$$ + trap 'ret=$?; rmdir "$tmpdir/d" "$tmpdir" 2>/dev/null; exit $ret' 0 + + if (umask $mkdir_umask && + exec $mkdirprog $mkdir_mode -p -- "$tmpdir/d") >/dev/null 2>&1 + then + if test -z "$dir_arg" || { + # Check for POSIX incompatibilities with -m. + # HP-UX 11.23 and IRIX 6.5 mkdir -m -p sets group- or + # other-writeable bit of parent directory when it shouldn't. + # FreeBSD 6.1 mkdir -m -p sets mode of existing directory. + ls_ld_tmpdir=`ls -ld "$tmpdir"` + case $ls_ld_tmpdir in + d????-?r-*) different_mode=700;; + d????-?--*) different_mode=755;; + *) false;; + esac && + $mkdirprog -m$different_mode -p -- "$tmpdir" && { + ls_ld_tmpdir_1=`ls -ld "$tmpdir"` + test "$ls_ld_tmpdir" = "$ls_ld_tmpdir_1" + } + } + then posix_mkdir=: + fi + rmdir "$tmpdir/d" "$tmpdir" + else + # Remove any dirs left behind by ancient mkdir implementations. + rmdir ./$mkdir_mode ./-p ./-- 2>/dev/null + fi + trap '' 0;; + esac;; + esac + + if + $posix_mkdir && ( + umask $mkdir_umask && + $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir" + ) + then : + else + + # The umask is ridiculous, or mkdir does not conform to POSIX, + # or it failed possibly due to a race condition. Create the + # directory the slow way, step by step, checking for races as we go. + + case $dstdir in + /*) prefix=/ ;; + -*) prefix=./ ;; + *) prefix= ;; + esac + + case $posix_glob in + '') + if (set -f) 2>/dev/null; then + posix_glob=true + else + posix_glob=false + fi ;; + esac + + oIFS=$IFS + IFS=/ + $posix_glob && set -f + set fnord $dstdir + shift + $posix_glob && set +f + IFS=$oIFS + + prefixes= + + for d + do + test -z "$d" && continue + + prefix=$prefix$d + if test -d "$prefix"; then + prefixes= + else + if $posix_mkdir; then + (umask=$mkdir_umask && + $doit_exec $mkdirprog $mkdir_mode -p -- "$dstdir") && break + # Don't fail if two instances are running concurrently. + test -d "$prefix" || exit 1 + else + case $prefix in + *\'*) qprefix=`echo "$prefix" | sed "s/'/'\\\\\\\\''/g"`;; + *) qprefix=$prefix;; + esac + prefixes="$prefixes '$qprefix'" + fi + fi + prefix=$prefix/ + done + + if test -n "$prefixes"; then + # Don't fail if two instances are running concurrently. + (umask $mkdir_umask && + eval "\$doit_exec \$mkdirprog $prefixes") || + test -d "$dstdir" || exit 1 + obsolete_mkdir_used=true + fi + fi + fi + + if test -n "$dir_arg"; then + { test -z "$chowncmd" || $doit $chowncmd "$dst"; } && + { test -z "$chgrpcmd" || $doit $chgrpcmd "$dst"; } && + { test "$obsolete_mkdir_used$chowncmd$chgrpcmd" = false || + test -z "$chmodcmd" || $doit $chmodcmd $mode "$dst"; } || exit 1 + else + + # Make a couple of temp file names in the proper directory. + dsttmp=$dstdir/_inst.$$_ + rmtmp=$dstdir/_rm.$$_ + + # Trap to clean up those temp files at exit. + trap 'ret=$?; rm -f "$dsttmp" "$rmtmp" && exit $ret' 0 + + # Copy the file name to the temp name. + (umask $cp_umask && $doit_exec $cpprog "$src" "$dsttmp") && + + # and set any options; do chmod last to preserve setuid bits. + # + # If any of these fail, we abort the whole thing. If we want to + # ignore errors from any of these, just make sure not to ignore + # errors from the above "$doit $cpprog $src $dsttmp" command. + # + { test -z "$chowncmd" || $doit $chowncmd "$dsttmp"; } \ + && { test -z "$chgrpcmd" || $doit $chgrpcmd "$dsttmp"; } \ + && { test -z "$stripcmd" || $doit $stripcmd "$dsttmp"; } \ + && { test -z "$chmodcmd" || $doit $chmodcmd $mode "$dsttmp"; } && + + # Now rename the file to the real destination. + { $doit $mvcmd -f "$dsttmp" "$dst" 2>/dev/null \ + || { + # The rename failed, perhaps because mv can't rename something else + # to itself, or perhaps because mv is so ancient that it does not + # support -f. + + # Now remove or move aside any old file at destination location. + # We try this two ways since rm can't unlink itself on some + # systems and the destination file might be busy for other + # reasons. In this case, the final cleanup might fail but the new + # file should still install successfully. + { + if test -f "$dst"; then + $doit $rmcmd -f "$dst" 2>/dev/null \ + || { $doit $mvcmd -f "$dst" "$rmtmp" 2>/dev/null \ + && { $doit $rmcmd -f "$rmtmp" 2>/dev/null; :; }; }\ + || { + echo "$0: cannot unlink or rename $dst" >&2 + (exit 1); exit 1 + } + else + : + fi + } && + + # Now rename the file to the real destination. + $doit $mvcmd "$dsttmp" "$dst" + } + } || exit 1 + + trap '' 0 + fi +done + +# Local variables: +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-end: "$" +# End: diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/mkinstalldirs b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/mkinstalldirs new file mode 100755 index 00000000..1c3d072f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/mkinstalldirs @@ -0,0 +1,162 @@ +#! /bin/sh +# mkinstalldirs --- make directory hierarchy + +scriptversion=2006-05-11.19 + +# Original author: Noah Friedman +# Created: 1993-05-16 +# Public domain. +# +# This file is maintained in Automake, please report +# bugs to or send patches to +# . + +nl=' +' +IFS=" "" $nl" +errstatus=0 +# Default directory mode for all zsh files is world read- and executable +dirmode=755 + +usage="\ +Usage: mkinstalldirs [-h] [--help] [--version] [-m MODE] DIR ... + +Create each directory DIR (with mode MODE, if specified), including all +leading file name components. + +Report bugs to ." + +# process command line arguments +while test $# -gt 0 ; do + case $1 in + -h | --help | --h*) # -h for help + echo "$usage" + exit $? + ;; + -m) # -m PERM arg + shift + test $# -eq 0 && { echo "$usage" 1>&2; exit 1; } + dirmode=$1 + shift + ;; + --version) + echo "$0 $scriptversion" + exit $? + ;; + --) # stop option processing + shift + break + ;; + -*) # unknown option + echo "$usage" 1>&2 + exit 1 + ;; + *) # first non-opt arg + break + ;; + esac +done + +for file +do + if test -d "$file"; then + shift + else + break + fi +done + +case $# in + 0) exit 0 ;; +esac + +# Solaris 8's mkdir -p isn't thread-safe. If you mkdir -p a/b and +# mkdir -p a/c at the same time, both will detect that a is missing, +# one will create a, then the other will try to create a and die with +# a "File exists" error. This is a problem when calling mkinstalldirs +# from a parallel make. We use --version in the probe to restrict +# ourselves to GNU mkdir, which is thread-safe. +case $dirmode in + '') + if mkdir -p --version . >/dev/null 2>&1 && test ! -d ./--version; then + echo "mkdir -p -- $*" + exec mkdir -p -- "$@" + else + # On NextStep and OpenStep, the `mkdir' command does not + # recognize any option. It will interpret all options as + # directories to create, and then abort because `.' already + # exists. + test -d ./-p && rmdir ./-p + test -d ./--version && rmdir ./--version + fi + ;; + *) + if mkdir -m "$dirmode" -p --version . >/dev/null 2>&1 && + test ! -d ./--version; then + echo "mkdir -m $dirmode -p -- $*" + exec mkdir -m "$dirmode" -p -- "$@" + else + # Clean up after NextStep and OpenStep mkdir. + for d in ./-m ./-p ./--version "./$dirmode"; + do + test -d $d && rmdir $d + done + fi + ;; +esac + +for file +do + case $file in + /*) pathcomp=/ ;; + *) pathcomp= ;; + esac + oIFS=$IFS + IFS=/ + set fnord $file + shift + IFS=$oIFS + + for d + do + test "x$d" = x && continue + + pathcomp=$pathcomp$d + case $pathcomp in + -*) pathcomp=./$pathcomp ;; + esac + + if test ! -d "$pathcomp"; then + echo "mkdir $pathcomp" + + mkdir "$pathcomp" || lasterr=$? + + if test ! -d "$pathcomp"; then + errstatus=$lasterr + else + if test ! -z "$dirmode"; then + echo "chmod $dirmode $pathcomp" + lasterr= + chmod "$dirmode" "$pathcomp" || lasterr=$? + + if test ! -z "$lasterr"; then + errstatus=$lasterr + fi + fi + fi + fi + + pathcomp=$pathcomp/ + done +done + +exit $errstatus + +# Local Variables: +# mode: shell-script +# sh-indentation: 2 +# eval: (add-hook 'write-file-hooks 'time-stamp) +# time-stamp-start: "scriptversion=" +# time-stamp-format: "%:y-%02m-%02d.%02H" +# time-stamp-end: "$" +# End: diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/patch_cfgac.diff b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/patch_cfgac.diff new file mode 100644 index 00000000..50624bc3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/patch_cfgac.diff @@ -0,0 +1,73 @@ +diff --git a/module/configure.ac b/module/configure.ac +index 298af02..b116b80 100644 +--- a/module/configure.ac ++++ b/module/configure.ac +@@ -437,11 +437,6 @@ fi], + [AC_DEFINE(DEFAULT_READNULLCMD,"more")] + ) + +-dnl Do you want to look for pcre support? +-AC_ARG_ENABLE(pcre, +-AC_HELP_STRING([--enable-pcre], +-[enable the search for the pcre library (may create run-time library dependencies)])) +- + dnl Do you want to look for capability support? + AC_ARG_ENABLE(cap, + AC_HELP_STRING([--enable-cap], +@@ -672,16 +667,6 @@ AC_HEADER_STAT + AC_HEADER_SYS_WAIT + + oldcflags="$CFLAGS" +-if test x$enable_pcre = xyes; then +-AC_CHECK_PROG([PCRECONF], pcre-config, pcre-config) +-dnl Typically (meaning on this single RedHat 9 box in front of me) +-dnl pcre-config --cflags produces a -I output which needs to go into +-dnl CPPFLAGS else configure's preprocessor tests don't pick it up, +-dnl producing a warning. +-if test "x$ac_cv_prog_PCRECONF" = xpcre-config; then +- CPPFLAGS="$CPPFLAGS `pcre-config --cflags`" +-fi +-fi + + AC_CHECK_HEADERS(sys/time.h sys/times.h sys/select.h termcap.h termio.h \ + termios.h sys/param.h sys/filio.h string.h memory.h \ +@@ -689,7 +674,7 @@ AC_CHECK_HEADERS(sys/time.h sys/times.h sys/select.h termcap.h termio.h \ + locale.h errno.h stdio.h stdarg.h varargs.h stdlib.h \ + unistd.h sys/capability.h \ + utmp.h utmpx.h sys/types.h pwd.h grp.h poll.h sys/mman.h \ +- netinet/in_systm.h pcre.h langinfo.h wchar.h stddef.h \ ++ netinet/in_systm.h langinfo.h wchar.h stddef.h \ + sys/stropts.h iconv.h ncurses.h ncursesw/ncurses.h \ + ncurses/ncurses.h) + if test x$dynamic = xyes; then +@@ -932,12 +917,6 @@ if test "x$ac_found_iconv" = "xyes"; then + [Define as const if the declaration of iconv() needs const.]) + fi + +-if test x$enable_pcre = xyes; then +-dnl pcre-config should probably be employed here +-dnl AC_SEARCH_LIBS(pcre_compile, pcre) +- LIBS="`$ac_cv_prog_PCRECONF --libs` $LIBS" +-fi +- + dnl --------------------- + dnl CHECK TERMCAP LIBRARY + dnl --------------------- +@@ -1311,7 +1290,6 @@ AC_CHECK_FUNCS(strftime strptime mktime timelocal \ + pathconf sysconf \ + tgetent tigetflag tigetnum tigetstr setupterm initscr resize_term \ + getcchar setcchar waddwstr wget_wch win_wch use_default_colors \ +- pcre_compile pcre_study pcre_exec \ + nl_langinfo \ + erand48 open_memstream \ + posix_openpt \ +@@ -3278,8 +3256,7 @@ AC_SUBST_FILE(CONFIG_MK)dnl + AC_SUBST_FILE(DEFS_MK)dnl + AC_SUBST_FILE(VERSION_MK)dnl + +-AC_CONFIG_FILES(Config/defs.mk Makefile Doc/Makefile Etc/Makefile \ +-Src/Makefile Test/Makefile) ++AC_CONFIG_FILES(Config/defs.mk Makefile Src/Makefile Test/Makefile) + AC_CONFIG_COMMANDS([config.modules], [. ./config.modules.sh]) + AC_CONFIG_COMMANDS([stamp-h], [echo >stamp-h]) + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/stamp-h.in b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/stamp-h.in new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/modules/stamp-h.in @@ -0,0 +1 @@ + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/.gitignore b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/.gitignore new file mode 100644 index 00000000..dea2d4fb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/.gitignore @@ -0,0 +1 @@ +.zcompdump diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/comptest b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/comptest new file mode 100644 index 00000000..1a58bccb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/comptest @@ -0,0 +1,174 @@ +comptestinit () { + setopt extendedglob + + zmodload zsh/zpty || return $? + + comptest_zsh=${ZSH:-zsh} + comptest_keymap=e + + while getopts vz: opt; do + case $opt in + z) comptest_zsh="$OPTARG";; + v) comptest_keymap="v";; + esac + done + (( OPTIND > 1 )) && shift $(( OPTIND - 1 )) + + export PS1="" + zpty zsh "$comptest_zsh -f +Z" + + zpty -r zsh log1 "**" || { + print "first prompt hasn't appeared." + return 1 + } + + comptesteval \ +"export LC_ALL=${ZSH_TEST_LANG:-C}" \ +"emulate -R zsh" \ +"export ZDOTDIR=$ZTST_testdir" \ +"bindkey -$comptest_keymap" \ +'LISTMAX=10000000 +stty 38400 columns 80 rows 24 tabs -icanon -iexten +TERM=vt100 +KEYTIMEOUT=1 +setopt zle +autoload -U compinit +compinit -u +zstyle ":completion:*:default" list-colors "no=" "fi=" "di=" "ln=" "pi=" "so=" "bd=" "cd=" "ex=" "mi=" "tc=" "sp=" "lc=" "ec=\n" "rc=" +zstyle ":completion:*" group-name "" +zstyle ":completion:*:messages" format "%d +" +zstyle ":completion:*:descriptions" format "%d" +zstyle ":completion:*:options" verbose yes +zstyle ":completion:*:values" verbose yes +setopt noalwayslastprompt listrowsfirst completeinword +zmodload zsh/complist +expand-or-complete-with-report () { + print -lr "" + zle expand-or-complete + print -lr - "$LBUFFER" "$RBUFFER" + zle clear-screen + zle -R +} +list-choices-with-report () { + print -lr "" + zle list-choices + zle clear-screen + zle -R +} +comp-finish () { + print "" + zle kill-whole-line + zle clear-screen + zle -R +} +zle-finish () { + local buffer="$BUFFER" cursor="$CURSOR" mark="$MARK" + (( region_active)) || unset mark + BUFFER="" + zle -I + zle clear-screen + zle redisplay + print -lr "" "BUFFER: $buffer" "CURSOR: $cursor" + (( $+mark )) && print -lr "MARK: $mark" + zle accept-line +} +zle -N expand-or-complete-with-report +zle -N list-choices-with-report +zle -N comp-finish +zle -N zle-finish +bindkey "^I" expand-or-complete-with-report +bindkey "^D" list-choices-with-report +bindkey "^Z" comp-finish +bindkey "^X" zle-finish +bindkey -a "^X" zle-finish +' +} + +zpty_flush() { + local junk + if zpty -r -t zsh junk \*; then + (( ZTST_verbose > 2 )) && print -n -u $ZTST_fd "$*: ${(V)junk}" + while zpty -r -t zsh junk \* ; do + (( ZTST_verbose > 2 )) && print -n -u $ZTST_fd "${(V)junk}" + done + (( ZTST_verbose > 2 )) && print -u $ZTST_fd '' + fi +} + +zpty_run() { + zpty -w zsh "$*" + zpty -r -m zsh log "**" || { + print "prompt hasn't appeared." + return 1 + } +} + +comptesteval () { + local tmp=/tmp/comptest.$$ + + print -lr - "$@" > $tmp + # zpty_flush Before comptesteval + zpty -w zsh ". $tmp" + zpty -r -m zsh log_eval "**" || { + print "prompt hasn't appeared." + return 1 + } + zpty_flush After comptesteval + rm $tmp +} + +comptest () { + input="$*" + zpty -n -w zsh "$input"$'\C-Z' + zpty -r -m zsh log "***" || { + print "failed to invoke finish widget." + return 1 + } + + logs=(${(s::)log}) + shift logs + + for log in "$logs[@]"; do + if [[ "$log" = (#b)*$''(*)$'\r\n'(*)$''* ]]; then + print -lr "line: {$match[1]}{$match[2]}" + fi + while (( ${(N)log#*(#b)(<(??)>(*)|(*)|(*)|(*)|(*)|(*)|(*))} )); do + log="${log[$mend[1]+1,-1]}" + if (( 0 <= $mbegin[2] )); then + if [[ $match[2] != TC && $match[3] != \ # ]]; then + print -lr "$match[2]:{${match[3]%${(%):-%E}}}" + fi + elif (( 0 <= $mbegin[4] )); then + print -lr "DESCRIPTION:{$match[4]}" + elif (( 0 <= $mbegin[5] )); then + print -lr "MESSAGE:{$match[5]}" + elif (( 0 <= $mbegin[6] )); then + print -lr "COMPADD:{${${match[6]}//[$'\r\n']/}}" + elif (( 0 <= $mbegin[7] )); then + print -lr "INSERT_POSITIONS:{${${match[7]}//[$'\r\n']/}}" + elif (( 0 <= $mbegin[8] )); then + print -lr "QUERY:{${match[8]}}" + elif (( 0 <= $mbegin[9] )); then + print -lr "WARN:{${match[9]}}" + fi + done + done +} + +zletest () { + local first=0 + for input; do + # zpty_flush Before zletest + # sleep for $KEYTIMEOUT + (( first++ )) && { sleep 2 & } | read -t 0.011 -u 0 -k 1 + zpty -n -w zsh "$input" + done + zpty -n -w zsh $'\C-X' + zpty -r -m zsh log "***" || { + print "failed to invoke finish widget." + return 1 + } + # zpty_flush After zletest + print -lr "${(@)${(@ps:\r\n:)log##*}[2,-2]}" +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/fzftab.ztst b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/fzftab.ztst new file mode 100644 index 00000000..98028f3a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/fzftab.ztst @@ -0,0 +1,211 @@ +# Tests for fzf tab. + +%prep + unset -m LC_\* + ZSH_TEST_LANG= + langs=(en_{US,GB}.{UTF-,utf}8 en.UTF-8 + $(locale -a 2>/dev/null | egrep 'utf8|UTF-8')) + for LANG in $langs; do + if [[ é = ? ]]; then + ZSH_TEST_LANG=$LANG + break; + fi + done + if [[ $OSTYPE = cygwin ]]; then + ZTST_unimplemented="the zsh/zpty module does not work on Cygwin" + elif ( zmodload zsh/zpty 2>/dev/null ); then + . $ZTST_srcdir/comptest + mkdir comp.tmp + cd comp.tmp + comptestinit -z zsh && + { + comptesteval 'compdef _tst tst' + mkdir dir1 && + mkdir dir2 && + touch file1 && + touch file2 + touch dir1/file1 + git init + } + else + ZTST_unimplemented="the zsh/zpty module is not available" + fi + + comptesteval ". $ZTST_srcdir/../fzf-tab.zsh" + comptesteval "zstyle ':fzf-tab:*' debug-command $ZTST_srcdir/select -n 1 -h '\$#_ftb_headers' -q '\"\$_ftb_query\"'" + comptesteval ' + zstyle ":fzf-tab:*" default-color "" + zstyle ":fzf-tab:*" single-group color header + zstyle ":fzf-tab:*" group-colors "" "" "" "" + fzf-tab-complete-with-report() { + print -lr "" + zle fzf-tab-complete 2>&1 + print -lr - "$LBUFFER" "$RBUFFER" + zle clear-screen + zle -R + } + zle -N fzf-tab-complete-with-report + bindkey "^I" fzf-tab-complete-with-report + ' + +%test + + comptest $': \t' +0:directories and files +>line: {: dir1/}{} +>QUERY:{} +>DESCRIPTION:{file} +>C1:{dir1/} +>C1:{dir2/} +>C1:{file1} +>C1:{file2} + + comptest $': d\t' +0:prefix +>line: {: dir1/}{} +>QUERY:{dir} +>DESCRIPTION:{file} +>C1:{dir1/} +>C1:{dir2/} + + comptesteval '_tst () { compadd d c b a }' + comptest $'tst \t' +0:normal +>line: {tst a }{} +>QUERY:{} +>C0:{a} +>C0:{b} +>C0:{c} +>C0:{d} + + comptesteval 'zstyle ":completion:*:tst:*" sort false' + comptest $'tst \t' +0:no sort +>line: {tst d }{} +>QUERY:{} +>C0:{d} +>C0:{c} +>C0:{b} +>C0:{a} + + comptesteval 'zstyle ":fzf-tab:*:tst:*" fzf-flags -n 1,2' + comptest $'tst \t' + comptesteval 'zstyle -d ":fzf-tab:*:tst:*" fzf-flags' +0:multi select +>line: {tst c d }{} +>QUERY:{} +>C0:{d} +>C0:{c} +>C0:{b} +>C0:{a} + + comptest $': *\t' +0:expand +>line: {: dir1 dir2 file1 file2 }{} + + comptesteval 'zstyle ":completion:*:warnings" format "%d"' + comptest $': asd\t' +0:warnings +>line: {: asd}{} +>WARN:{`file'} +>WARN:{`file'} +# FIXME:why two warnings? + + comptesteval "touch 'abc def'" + comptest $': ./a\t' +0:filename with space +>line: {: ./abc\ def }{} + + comptest $': ./abdef\C-b\C-b\C-b\t' +0:complete in word +>line: {: ./abc\ def }{} + + comptest $': ./abc def\C-b\C-b\C-b\C-b\t' + comptesteval "rm 'abc def'" +0:complete in word(with known bug) +>line: {: ./abc\ def}{ def} + + comptesteval 'mkdir -p abc/def/hij abc/dfe/hij' + comptest $': ./a/d/h\t' + comptesteval 'rm -rd abc' +0:nested directory +>line: {: ./abc/def/h}{} +>QUERY:{d} +>DESCRIPTION:{file} +>C1:{def/} +>C1:{dfe/} + + comptesteval '_tst() { a=(a); _describe "group1" a; a=(b); _describe "group2" a }' + comptest $'tst \t' +0:multi headers +>line: {tst a }{} +>QUERY:{} +>DESCRIPTION:{group1} +>DESCRIPTION:{group2} +>C1:{·a} +>C2:{·b} + + comptest $'git add dir1\t' +0:add empty word +>line: {git add dir1/}{} +# FIXME:why two warnings? + + comptesteval "zstyle ':completion:*' matcher-list 'm:{a-zA-Z}={A-Za-z}' 'r:|=*' 'l:|=* r:|=*'" + comptesteval "touch vim.coc" + comptest $': coc\t' + comptesteval "rm vim.coc; zstyle -d ':completion:*' matcher-list" +0:matcher-list +>line: {: vim.coc }{} + + comptesteval $'cd dir1' + comptest $': ../d\t' + comptesteval $'cd ..' +0:IPREFIX +>line: {: ../dir1/}{} +>QUERY:{dir} +>DESCRIPTION:{file} +>C1:{dir1/} +>C1:{dir2/} + + comptest $': $PWD/d\t' +0:expansion +>line: {: $PWD/dir1/}{} +>QUERY:{dir} +>DESCRIPTION:{file} +>C1:{dir1/} +>C1:{dir2/} + + comptesteval 'echo no > called' + comptesteval "touch 'dir\`echo yes > called\`'" + comptest $': d\t' + echo called:$( called\`' called" +0:don''t expand file name +>line: {: dir1/}{} +>QUERY:{dir} +>DESCRIPTION:{file} +>C1:{dir1/} +>C1:{dir2/} +>C1:{dir`echo yes > called`} +>called:no + + comptesteval "zstyle ':fzf-tab:*' debug-command true" + comptest $': d\t' + comptesteval "zstyle ':fzf-tab:*' debug-command $ZTST_srcdir/select -n 1 -h '\$#headers' -q '\"\$query\"'" +0:cancel completion +>line: {: d}{} + + comptesteval "zstyle ':fzf-tab:*' debug-command $ZTST_srcdir/select -n QUERY -h '\$#headers' -q '\"dragon\"'" + comptest $': ./d\t' + comptesteval "zstyle ':fzf-tab:*' debug-command $ZTST_srcdir/select -n 1 -h '\$#headers' -q '\"\$query\"'" +0:use query directly +>line: {: ./dragon}{} +>QUERY:{dragon} +>DESCRIPTION:{file} +>C1:{dir1/} +>C1:{dir2/} + +%clean + + zmodload -ui zsh/zpty + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/runtests.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/runtests.zsh new file mode 100644 index 00000000..18406c0f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/runtests.zsh @@ -0,0 +1,27 @@ +#!/bin/zsh -f + +emulate zsh + +# Run all specified tests, keeping count of which succeeded. +# The reason for this extra layer above the test script is to +# protect from catastrophic failure of an individual test. +# We could probably do that with subshells instead. + +integer success failure skipped retval +for file in ${@:1}; do + zsh +Z -f ./ztst.zsh $file + retval=$? + if (( $retval == 2 )); then + (( skipped++ )) + elif (( $retval )); then + (( failure++ )) + else + (( success++ )) + fi +done +print "************************************** +$success successful test script${${success:#1}:+s}, \ +$failure failure${${failure:#1}:+s}, \ +$skipped skipped +**************************************" +return $(( failure ? 1 : 0 )) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/select b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/select new file mode 100755 index 00000000..d06d4e9c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/select @@ -0,0 +1,32 @@ +#!/usr/bin/env zsh + +zmodload zsh/zutil + +local -A headers range query + +zparseopts -E h:=headers n:=range q:=query e:=expect + +print -r -- "${query//\"/}" +print -r -- "$expect" +print -r -- "${query//\"/}" >&2 + +local -a lines=() +while read input; do + lines+=(${input%$'\033[00m'}) +done + +for ((i = 1; i <= headers; i++)); do + print -r -- $lines[i] >&2 +done + +lines[1,headers]=() + +for i in {1..$#lines}; do + print -r -- ${lines[i]//$'\0'}"" >&2 +done + +if [[ $range != QUERY ]]; then + for i in ${(s:,:)range}; do + print -r -- $lines[i] + done +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/ztst.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/ztst.zsh new file mode 100755 index 00000000..eb942b8a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/fzf-tab/test/ztst.zsh @@ -0,0 +1,581 @@ +#!/bin/zsh -f +# The line above is just for convenience. Normally tests will be run using +# a specified version of zsh. With dynamic loading, any required libraries +# must already have been installed in that case. +# +# Takes one argument: the name of the test file. Currently only one such +# file will be processed each time ztst.zsh is run. This is slower, but +# much safer in terms of preserving the correct status. +# To avoid namespace pollution, all functions and parameters used +# only by the script begin with ZTST_. +# +# Options (without arguments) may precede the test file argument; these +# are interpreted as shell options to set. -x is probably the most useful. + +# Produce verbose messages if non-zero. +# If 1, produce reports of tests executed; if 2, also report on progress. +# Defined in such a way that any value from the environment is used. +: ${ZTST_verbose:=0} + +# We require all options to be reset, not just emulation options. +# Unfortunately, due to the crud which may be in /etc/zshenv this might +# still not be good enough. Maybe we should trick it somehow. +emulate -R zsh + +# Ensure the locale does not screw up sorting. Don't supply a locale +# unless there's one set, to minimise problems. +[[ -n $LC_ALL ]] && LC_ALL=C +[[ -n $LC_COLLATE ]] && LC_COLLATE=C +[[ -n $LC_NUMERIC ]] && LC_NUMERIC=C +[[ -n $LC_MESSAGES ]] && LC_MESSAGES=C +[[ -n $LANG ]] && LANG=C + +# Don't propagate variables that are set by default in the shell. +typeset +x WORDCHARS + +# We need to be able to save and restore the options used in the test. +# We use the $options variable of the parameter module for this. +zmodload zsh/parameter + +# Note that both the following are regular arrays, since we only use them +# in whole array assignments to/from $options. +# Options set in test code (i.e. by default all standard options) +ZTST_testopts=(${(kv)options}) + +setopt extendedglob nonomatch +while [[ $1 = [-+]* ]]; do + set $1 + shift +done +# Options set in main script +ZTST_mainopts=(${(kv)options}) + +# We run in the current directory, so remember it. +ZTST_testdir=$PWD +ZTST_testname=$1 + +integer ZTST_testfailed + +# This is POSIX nonsense. Because of the vague feeling someone, somewhere +# may one day need to examine the arguments of "tail" using a standard +# option parser, every Unix user in the world is expected to switch +# to using "tail -n NUM" instead of "tail -NUM". Older versions of +# tail don't support this. +tail() { + emulate -L zsh + + if [[ -z $TAIL_SUPPORTS_MINUS_N ]]; then + local test + test=$(echo "foo\nbar" | command tail -n 1 2>/dev/null) + if [[ $test = bar ]]; then + TAIL_SUPPORTS_MINUS_N=1 + else + TAIL_SUPPORTS_MINUS_N=0 + fi + fi + + integer argi=${argv[(i)-<->]} + + if [[ $argi -le $# && $TAIL_SUPPORTS_MINUS_N = 1 ]]; then + argv[$argi]=(-n ${argv[$argi][2,-1]}) + fi + + command tail "$argv[@]" +} + +# The source directory is not necessarily the current directory, +# but if $0 doesn't contain a `/' assume it is. +if [[ $0 = */* ]]; then + ZTST_srcdir=${0%/*} +else + ZTST_srcdir=$PWD +fi +[[ $ZTST_srcdir = /* ]] || ZTST_srcdir="$ZTST_testdir/$ZTST_srcdir" + + +: ${TMPPREFIX:=/tmp/zsh} +ZTST_tmp=${TMPPREFIX}.ztst.$$ +if ! rm -f $ZTST_tmp || ! mkdir -p $ZTST_tmp || ! chmod go-w $ZTST_tmp; then + print "Can't create $ZTST_tmp for exclusive use." >&2 + exit 1 +fi +# Temporary files for redirection inside tests. +ZTST_in=${ZTST_tmp}/ztst.in +# hold the expected output +ZTST_out=${ZTST_tmp}/ztst.out +ZTST_err=${ZTST_tmp}/ztst.err +# hold the actual output from the test +ZTST_tout=${ZTST_tmp}/ztst.tout +ZTST_terr=${ZTST_tmp}/ztst.terr + +ZTST_cleanup() { + cd $ZTST_testdir + rm -rf $ZTST_testdir/dummy.tmp $ZTST_testdir/*.tmp(N) ${ZTST_tmp} +} + +# This cleanup always gets performed, even if we abort. Later, +# we should try and arrange that any test-specific cleanup +# always gets called as well. +##trap 'print cleaning up... +##ZTST_cleanup' INT QUIT TERM +# Make sure it's clean now. +rm -rf dummy.tmp *.tmp + +# Report failure. Note that all output regarding the tests goes to stdout. +# That saves an unpleasant mixture of stdout and stderr to sort out. +ZTST_testfailed() { + print -r "Test $ZTST_testname failed: $1" + if [[ -n $ZTST_message ]]; then + print -r "Was testing: $ZTST_message" + fi + print -r "$ZTST_testname: test failed." + if [[ -n $ZTST_failmsg ]]; then + print -r "The following may (or may not) help identifying the cause: +$ZTST_failmsg" + fi + ZTST_testfailed=1 + return 1 +} + +# Print messages if $ZTST_verbose is non-empty +ZTST_verbose() { + local lev=$1 + shift + if [[ -n $ZTST_verbose && $ZTST_verbose -ge $lev ]]; then + print -r -u $ZTST_fd -- $* + fi +} +ZTST_hashmark() { + if [[ ZTST_verbose -le 0 && -t $ZTST_fd ]]; then + print -n -u$ZTST_fd -- ${(pl:SECONDS::\#::\#\r:)} + fi + (( SECONDS > COLUMNS+1 && (SECONDS -= COLUMNS) )) +} + +if [[ ! -r $ZTST_testname ]]; then + ZTST_testfailed "can't read test file." + exit 1 +fi + +exec {ZTST_fd}>&1 +exec {ZTST_input}<$ZTST_testname + +# The current line read from the test file. +ZTST_curline='' +# The current section being run +ZTST_cursect='' + +# Get a new input line. Don't mangle spaces; set IFS locally to empty. +# We shall skip comments at this level. +ZTST_getline() { + local IFS= + while true; do + read -u $ZTST_input -r ZTST_curline || return 1 + [[ $ZTST_curline == \#* ]] || return 0 + done +} + +# Get the name of the section. It may already have been read into +# $curline, or we may have to skip some initial comments to find it. +# If argument present, it's OK to skip the reset of the current section, +# so no error if we find garbage. +ZTST_getsect() { + local match mbegin mend + + while [[ $ZTST_curline != '%'(#b)([[:alnum:]]##)* ]]; do + ZTST_getline || return 1 + [[ $ZTST_curline = [[:blank:]]# ]] && continue + if [[ $# -eq 0 && $ZTST_curline != '%'[[:alnum:]]##* ]]; then + ZTST_testfailed "bad line found before or after section: +$ZTST_curline" + exit 1 + fi + done + # have the next line ready waiting + ZTST_getline + ZTST_cursect=${match[1]} + ZTST_verbose 2 "ZTST_getsect: read section name: $ZTST_cursect" + return 0 +} + +# Read in an indented code chunk for execution +ZTST_getchunk() { + # Code chunks are always separated by blank lines or the + # end of a section, so if we already have a piece of code, + # we keep it. Currently that shouldn't actually happen. + ZTST_code='' + # First find the chunk. + while [[ $ZTST_curline = [[:blank:]]# ]]; do + ZTST_getline || break + done + while [[ $ZTST_curline = [[:blank:]]##[^[:blank:]]* ]]; do + ZTST_code="${ZTST_code:+${ZTST_code} +}${ZTST_curline}" + ZTST_getline || break + done + ZTST_verbose 2 "ZTST_getchunk: read code chunk: +$ZTST_code" + [[ -n $ZTST_code ]] +} + +# Read in a piece for redirection. +ZTST_getredir() { + local char=${ZTST_curline[1]} fn + ZTST_redir=${ZTST_curline[2,-1]} + while ZTST_getline; do + [[ $ZTST_curline[1] = $char ]] || break + ZTST_redir="${ZTST_redir} +${ZTST_curline[2,-1]}" + done + ZTST_verbose 2 "ZTST_getredir: read redir for '$char': +$ZTST_redir" + + case $char in + ('<') fn=$ZTST_in + ;; + ('>') fn=$ZTST_out + ;; + ('?') fn=$ZTST_err + ;; + (*) ZTST_testfailed "bad redir operator: $char" + return 1 + ;; + esac + if [[ $ZTST_flags = *q* && $char = '<' ]]; then + # delay substituting output until variables are set + print -r -- "${(e)ZTST_redir}" >>$fn + else + print -r -- "$ZTST_redir" >>$fn + fi + + return 0 +} + +# Execute an indented chunk. Redirections will already have +# been set up, but we need to handle the options. +ZTST_execchunk() { + setopt localloops # don't let continue & break propagate out + options=($ZTST_testopts) + () { + unsetopt localloops + eval "$ZTST_code" + } + ZTST_status=$? + # careful... ksh_arrays may be in effect. + ZTST_testopts=(${(kv)options[*]}) + options=(${ZTST_mainopts[*]}) + ZTST_verbose 2 "ZTST_execchunk: status $ZTST_status" + return $ZTST_status +} + +# Functions for preparation and cleaning. +# When cleaning up (non-zero string argument), we ignore status. +ZTST_prepclean() { + # Execute indented code chunks. + while ZTST_getchunk; do + ZTST_execchunk >/dev/null || [[ -n $1 ]] || { + [[ -n "$ZTST_unimplemented" ]] || + ZTST_testfailed "non-zero status from preparation code: +$ZTST_code" && return 0 + } + done +} + +# diff wrapper +ZTST_diff() { + emulate -L zsh + setopt extendedglob + + local diff_out + integer diff_pat diff_ret + + case $1 in + (p) + diff_pat=1 + ;; + + (d) + ;; + + (*) + print "Bad ZTST_diff code: d for diff, p for pattern match" + ;; + esac + shift + + if (( diff_pat )); then + local -a diff_lines1 diff_lines2 + integer failed i l + local p + + diff_lines1=("${(f@)$(<$argv[-2])}") + diff_lines2=("${(f@)$(<$argv[-1])}") + if (( ${#diff_lines1} != ${#diff_lines2} )); then + failed=1 + print -r "Pattern match failed, line mismatch (${#diff_lines1}/${#diff_lines2}):" + else + for (( i = 1; i <= ${#diff_lines1}; i++ )); do + if [[ ${diff_lines2[i]} != ${~diff_lines1[i]} ]]; then + failed=1 + print -r "Pattern match failed, line $i:" + break + fi + done + fi + if (( failed )); then + for (( l = 1; l <= ${#diff_lines1}; ++l )); do + if (( l == i )); then + p="-" + else + p=" " + fi + print -r -- "$p<${diff_lines1[l]}" + done + for (( l = 1; l <= ${#diff_lines2}; ++l )); do + if (( l == i )); then + p="+" + else + p=" " + fi + print -r -- "$p>${diff_lines2[l]}" + done + diff_ret=1 + fi + else + diff_out=$(diff -a "$@") + diff_ret="$?" + if [[ "$diff_ret" != "0" ]]; then + print -r -- "$diff_out" + fi + fi + + return "$diff_ret" +} + +ZTST_test() { + local last match mbegin mend found substlines + local diff_out diff_err + local ZTST_skip + integer expected_to_fail + + while true; do + rm -f $ZTST_in $ZTST_out $ZTST_err + touch $ZTST_in $ZTST_out $ZTST_err + ZTST_message='' + ZTST_failmsg='' + found=0 + diff_out=d + diff_err=d + + ZTST_verbose 2 "ZTST_test: looking for new test" + + while true; do + ZTST_verbose 2 "ZTST_test: examining line: +$ZTST_curline" + case $ZTST_curline in + (%*) if [[ $found = 0 ]]; then + break 2 + else + last=1 + break + fi + ;; + ([[:space:]]#) + if [[ $found = 0 ]]; then + ZTST_getline || break 2 + continue + else + break + fi + ;; + ([[:space:]]##[^[:space:]]*) ZTST_getchunk + if [[ $ZTST_curline == (#b)([-0-9]##)([[:alpha:]]#)(:*)# ]]; then + ZTST_xstatus=$match[1] + ZTST_flags=$match[2] + ZTST_message=${match[3]:+${match[3][2,-1]}} + else + ZTST_testfailed "expecting test status at: +$ZTST_curline" + return 1 + fi + ZTST_getline + found=1 + ;; + ('<'*) ZTST_getredir || return 1 + found=1 + ;; + ('*>'*) + ZTST_curline=${ZTST_curline[2,-1]} + diff_out=p + ;& + ('>'*) + ZTST_getredir || return 1 + found=1 + ;; + ('*?'*) + ZTST_curline=${ZTST_curline[2,-1]} + diff_err=p + ;& + ('?'*) + ZTST_getredir || return 1 + found=1 + ;; + ('F:'*) ZTST_failmsg="${ZTST_failmsg:+${ZTST_failmsg} +} ${ZTST_curline[3,-1]}" + ZTST_getline + found=1 + ;; + (*) ZTST_testfailed "bad line in test block: +$ZTST_curline" + return 1 + ;; + esac + done + + # If we found some code to execute... + if [[ -n $ZTST_code ]]; then + ZTST_hashmark + ZTST_verbose 1 "Running test: $ZTST_message" + ZTST_verbose 2 "ZTST_test: expecting status: $ZTST_xstatus" + ZTST_verbose 2 "Input: $ZTST_in, output: $ZTST_out, error: $ZTST_terr" + + ZTST_execchunk <$ZTST_in >$ZTST_tout 2>$ZTST_terr + + if [[ -n $ZTST_skip ]]; then + ZTST_verbose 0 "Test case skipped: $ZTST_skip" + ZTST_skip= + if [[ -n $last ]]; then + break + else + continue + fi + fi + + if [[ $ZTST_flags = *f* ]]; then + expected_to_fail=1 + ZTST_xfail_diff() { ZTST_diff "$@" > /dev/null } + ZTST_diff=ZTST_xfail_diff + else + expected_to_fail=0 + ZTST_diff=ZTST_diff + fi + + # First check we got the right status, if specified. + if [[ $ZTST_xstatus != - && $ZTST_xstatus != $ZTST_status ]]; then + if (( expected_to_fail )); then + ZTST_verbose 1 "Test failed, as expected." + continue + fi + ZTST_testfailed "bad status $ZTST_status, expected $ZTST_xstatus from: +$ZTST_code${$(<$ZTST_terr):+ +Error output: +$(<$ZTST_terr)}" + return 1 + fi + + ZTST_verbose 2 "ZTST_test: test produced standard output: +$(<$ZTST_tout) +ZTST_test: and standard error: +$(<$ZTST_terr)" + + # Now check output and error. + if [[ $ZTST_flags = *q* && -s $ZTST_out ]]; then + substlines="$(<$ZTST_out)" + rm -rf $ZTST_out + print -r -- "${(e)substlines}" >$ZTST_out + fi + if [[ $ZTST_flags != *d* ]] && ! $ZTST_diff $diff_out -u $ZTST_out $ZTST_tout; then + if (( expected_to_fail )); then + ZTST_verbose 1 "Test failed, as expected." + continue + fi + ZTST_testfailed "output differs from expected as shown above for: +$ZTST_code${$(<$ZTST_terr):+ +Error output: +$(<$ZTST_terr)}" + return 1 + fi + if [[ $ZTST_flags = *q* && -s $ZTST_err ]]; then + substlines="$(<$ZTST_err)" + rm -rf $ZTST_err + print -r -- "${(e)substlines}" >$ZTST_err + fi + if [[ $ZTST_flags != *D* ]] && ! $ZTST_diff $diff_err -u $ZTST_err $ZTST_terr; then + if (( expected_to_fail )); then + ZTST_verbose 1 "Test failed, as expected." + continue + fi + ZTST_testfailed "error output differs from expected as shown above for: +$ZTST_code" + return 1 + fi + if (( expected_to_fail )); then + ZTST_testfailed "test was expected to fail, but passed." + return 1 + fi + fi + ZTST_verbose 1 "Test successful." + [[ -n $last ]] && break + done + + ZTST_verbose 2 "ZTST_test: all tests successful" + + # reset message to keep ZTST_testfailed output correct + ZTST_message='' +} + + +# Remember which sections we've done. +typeset -A ZTST_sects +ZTST_sects=(prep 0 test 0 clean 0) + +print "$ZTST_testname: starting." + +# Now go through all the different sections until the end. +# prep section may set ZTST_unimplemented, in this case the actual +# tests will be skipped +ZTST_skipok= +ZTST_unimplemented= +while [[ -z "$ZTST_unimplemented" ]] && ZTST_getsect $ZTST_skipok; do + case $ZTST_cursect in + (prep) if (( ${ZTST_sects[prep]} + ${ZTST_sects[test]} + \ + ${ZTST_sects[clean]} )); then + ZTST_testfailed "\`prep' section must come first" + exit 1 + fi + ZTST_prepclean + ZTST_sects[prep]=1 + ;; + (test) + if (( ${ZTST_sects[test]} + ${ZTST_sects[clean]} )); then + ZTST_testfailed "bad placement of \`test' section" + exit 1 + fi + # careful here: we can't execute ZTST_test before || or && + # because that affects the behaviour of traps in the tests. + ZTST_test + (( $? )) && ZTST_skipok=1 + ZTST_sects[test]=1 + ;; + (clean) + if (( ${ZTST_sects[test]} == 0 || ${ZTST_sects[clean]} )); then + ZTST_testfailed "bad use of \`clean' section" + else + ZTST_prepclean 1 + ZTST_sects[clean]=1 + fi + ZTST_skipok= + ;; + *) ZTST_testfailed "bad section name: $ZTST_cursect" + ;; + esac +done + +if [[ -n "$ZTST_unimplemented" ]]; then + print "$ZTST_testname: skipped ($ZTST_unimplemented)" + ZTST_testfailed=2 +elif (( ! $ZTST_testfailed )); then + print "$ZTST_testname: all tests successful." +fi +ZTST_cleanup +exit $(( ZTST_testfailed )) diff --git a/dots/.config/zsh/config/plugins/init.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/init.zsh similarity index 100% rename from dots/.config/zsh/config/plugins/init.zsh rename to configurations/price/dots/xdg/config/zsh/config/plugins/init.zsh diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/.gitattributes b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/.gitattributes new file mode 100644 index 00000000..d17824d2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/.gitattributes @@ -0,0 +1 @@ +_* linguist-language=Shell diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/.github/workflows/test.yml b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/.github/workflows/test.yml new file mode 100644 index 00000000..14abc933 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/.github/workflows/test.yml @@ -0,0 +1,30 @@ +name: test +on: + pull_request: + types: + - opened + - synchronize + branches: + - master + push: + branches: + - master + +jobs: + tests: + name: Run tests + runs-on: ${{ matrix.os }} + strategy: + matrix: + os: [ubuntu-latest, macos-latest] + steps: + - name: Set up git repository + uses: actions/checkout@v2 + - name: Install zsh + if: runner.os == 'Linux' + run: sudo apt-get update; sudo apt-get install zsh + - name: Check syntax + run: | + for file in _* *.zsh; do + zsh -n "$file" || return 1 + done diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/ISSUE_TEMPLATE.md b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..f254963a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/ISSUE_TEMPLATE.md @@ -0,0 +1,41 @@ + + +### Description + +### Reproduction steps + + + +### System + +- nix-zsh-completions version: +- ZSH version: +- NIX_PATH: + + +### Completion trace + + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/LICENSE b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/LICENSE new file mode 100644 index 00000000..22dc1501 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2015, Spencer Whitt +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of Spencer Whitt nor the names of other + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/README.md new file mode 100644 index 00000000..571ae4b8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/README.md @@ -0,0 +1,57 @@ +ZSH Completions for Nix and NixOS +================================= + +This project aims to provide a highly complete set of ZSH completions for [Nix](https://nixos.org/nix/), +[NixOS](https://nixos.org/), [NixOps](http://nixos.org/nixops/), and the surrounding ecosystem. + +NixOS +---------------------- +Setting `programs.zsh.enable = true` in `/etc/nixos/configuration.nix` will automatically install and enable `nix-zsh-compeletions`. + +Oh-My-ZSH Installation +---------------------- + +```zsh +cd ~/.oh-my-zsh/custom/plugins +git clone git@github.com:nix-community/nix-zsh-completions.git +``` + +Then add `nix-zsh-completions` to the plugins list in `~/.zshrc` + +If you want your prompt to be prefixed by `[nix-shell]` when you're in a nix-shell add this to your zshrc: + +``` +prompt_nix_shell_setup +``` + +Antigen Installation +-------------------- + +Add the following to `~/.zshrc` + +```zsh +antigen bundle git@github.com:nix-community/nix-zsh-completions.git +``` + +Plain ZSH Installation +---------------------- + +Clone this repository and add the following to `~/.zshrc` with the path to +`nix-zsh-completions` updated as necessary. + +```zsh +source $HOME/nix-zsh-completions/nix-zsh-completions.plugin.zsh +fpath=($HOME/nix-zsh-completions $fpath) +autoload -U compinit && compinit +``` + +Required ZSH version +------------------------ + +The completion scripts are known to be broken in ZSH version `5.0.8` or older, `5.2` or newer works. + + +ZSH Completions Tutorial +------------------------ + +[zsh-completions-howto](https://github.com/zsh-users/zsh-completions/blob/master/zsh-completions-howto.org) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-build b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-build new file mode 100644 index 00000000..b7143e31 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-build @@ -0,0 +1,32 @@ +#compdef nix-build +#autoload + +_nix-common-options + +local -a _nix_build_opts=( + $__nix_expr_opts + $__nix_common_store_opts + '*'{--attr,-A}'[build a package from file (default: ./default.nix)]:package:_nix_complete_attr_paths' + --check'[Rebuild derivation]' + '--drv-link[Add a symlink to the store derivation]:Symlink Name:( )' + '--add-drv-link[Shorthand for --drv-link ./derivation]' + '--no-out-link[Do not create a symlink to the output path]' + {--out-link,-o}'[Name of the output symlink]:Output Symlink Name:( )' +) + +# TODO: Undocumented args to possibly add +# --add-root +# --check +# --quiet +# --command +# --exclude +# --pure +# --impure +# --packages,-p + +_arguments \ + $__nix_boilerplate_opts \ + $__nix_common_opts \ + $__nix_dry_run \ + $_nix_build_opts \ + '*:Paths:_nix_path' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-channel b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-channel new file mode 100644 index 00000000..b879ee6e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-channel @@ -0,0 +1,20 @@ +#compdef nix-channel +#autoload + +local context state state_descr line +typeset -A opt_args + +_nix-common-options + +_arguments \ + '(- *)--add[Subscribe to a channel]:Channel URL:_urls::Channel Name:( )'\ + '(- *)--remove[Unsubscribe from a channel]:Channel Name:->nix_channels'\ + '(- *)--list[List subscribed channels]'\ + '(- *)--update[Update and activate channels]:Channel Name:->nix_channels'\ + '(- *)--rollback[Revert the previous nix-channel --update]' + +case $state in + nix-channels) + local -a channels=(${${(f)"$(nix-channel --list)"}%% *}) + _values 'Nix Channels' ${channels} +esac diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-collect-garbage b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-collect-garbage new file mode 100644 index 00000000..55cf8935 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-collect-garbage @@ -0,0 +1,9 @@ +#compdef nix-collect-garbage +#autoload + +_nix-common-options + +_arguments \ + '(--delete-old -d)'{--delete-old,-d}'[Delete all old generations of all profiles]'\ + '--delete-older-than[Delete generations older than the given time]:Time such as 30d:( )'\ + $__nix_dry_run \ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-common-options b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-common-options new file mode 100644 index 00000000..ace6b997 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-common-options @@ -0,0 +1,614 @@ +#autoload + +if [[ $_NIX_SHELL_COMPLETION_LOADED ]]; then + # No point in re-defining these functions each time we do a completion + return 0 +fi + +# Simple completion function to select a system +# List gathered from: https://github.com/NixOS/nixpkgs/blob/master/lib/platforms.nix +_nix_systems () { + _values 'Systems' \ + i686-linux x86_64-linux \ + armv5tel-linux armv6l-linux armv7l-linux mips64el-linux \ + x86_64-darwin \ + i686-freebsd x86_64-freebsd \ + i686-openbsd x86_64-openbsd \ + i686-netbsd x86_64-netbsd \ + i686-cygwin x86_64-cygwin +} + +# Completion function to select an angle-bracket expression from the nix path +# Assumptions: No '=' in the actual path components in NIX_PATH +# TODO: Complete files in /some/path for expressions like +# IMPROVEMENT: Remove '' since that seems rather useless(?) +_nix_shortcuts () { + local nix_path=(${(s.:.)NIX_PATH}) + local named=(${(M)nix_path:#*=*}) + local dirs=(${nix_path:#*=*}) + local valid_dir_globs=($^dirs"/*/default.nix(N:h:t)") + local valid_dirs=(${~valid_dir_globs}) + local names=(${named%%=*}) + if [[ "$valid_dirs" || "$names" ]]; then + _values shortcuts "<"${^valid_dirs}">" "<"${^names}">" + fi +} + +_nix_path() { + _alternative \ + 'nixpkgs:Nixpkgs:_nix_shortcuts' \ + 'path:File Path:_nix_complete_dotnix_files' +} + +_nix_complete_dotnix_files () { + _alternative \ + "file:Local file:_path_files -g '*.nix(N) *(N-/)'" \ + 'shortcuts:Shortcuts:_nix_shortcuts' \ + 'channel:Channel:(channel: + channel:nixos-13.10 + channel:nixos-14.04 channel:nixos-14.04-small + channel:nixos-14.12 channel:nixos-14.12-small + channel:nixos-15.09 channel:nixos-15.09-small + channel:nixos-16.03 channel:nixos-16.03-small + channel:nixos-16.09 channel:nixos-16.09-small + channel:nixos-17.03 channel:nixos-17.03-small + channel:nixos-17.09 channel:nixos-17.09-small + channel:nixos-18.03 channel:nixos-18.03-small + channel:nixos-18.09 channel:nixos-18.09-small + channel:nixos-19.03 channel:nixos-19.03-small + channel:nixos-19.09 channel:nixos-19.09-small + channel:nixos-20.03 channel:nixos-20.03-small + channel:nixos-20.09 channel:nixos-20.09-small + channel:nixos-21.05 channel:nixos-21.05-small + channel:nixos-21.11 channel:nixos-21.11-small + channel:nixos-22.05 channel:nixos-22.05-small + channel:nixos-22.11 channel:nixos-22.11-small + channel:nixos-unstable channel:nixos-unstable-small + channel:nixpkgs-unstable)' \ + 'url:URL:(https:// http://)' +} # see: https://channels.nixos.org/ + +_nix_complete_includes () { + local cur=${words[$CURRENT]} + local -a nixpath=(${(s.:.)NIX_PATH}) + local -a path_names + local p + for p in ${nixpath[*]}; do + [[ "$p" == *=* ]] && \ + path_names+=(${p%=*}:Path:_nix_complete_dotnix_files) + done + if [[ $cur == *=* ]]; then + path_names+=(${cur%=*}:Path:_nix_complete_dotnix_files) + fi + if [[ "$path_names" ]]; then + _alternative \ + "nixpath:nixpath:_values -s = 'Nix path name' $path_names" \ + 'file:Path:_path_files -/' + else + _path_files -/ + fi + return +} + +_nix_generations () { + # List of package names with version numbers stripped + setopt extendedglob + local -a generations=(${${${(f)"$(nix-env --list-generations)"}## #}/ /:}) + _describe -V "Nix Generations" generations +} + +_nix_installed_packages () { + # List of package names with version numbers stripped + # with the alternative to specify store paths + local extra_help=$1 + local prefix='-P ./' + local current_word=$words[$CURRENT] + # When referencing an absolute path we can't prefix with ./ + if [[ -z ${current_word:##(/*|\~/*)} && -n $current_word ]]; then + prefix="" + fi + local -a packages=(${${(f)"$(nix-env -q)"}%%-[0-9]*}) + + _alternative \ + "package:packages:_values 'Installed package $extra_help' $packages" \ + "file:Store path to package:_files ${prefix}" +} + + +# Generate nix code creating the default expression used by 'nix-env -iA' +_nix_gen_defexpr () { + setopt local_options null_glob + local -A result # name -> path map + + # Search depth first for directories containing 'default.nix' + # nix-env -iA prioritize the user's channels in case of name collision + # Not sure how collisions in user-created directories are resolved. + local -aU initialQueue=($1/channels $1/channels_root $1/*) + local -a queue=($initialQueue) + + while [[ ${#queue} > 0 ]]; do + local current=$queue[1] + shift queue + if [[ -e $current/default.nix ]]; then + local name=$(basename $current) + if [[ -z $result[$name] ]]; then + result[$name]=$current + fi + else + queue=($current/* $queue) + fi + done + + local nix_expr="{\n" + for name expr_path in ${(kv)result}; do + nix_expr+="${name} = import ${expr_path};" + nix_expr+="\n" + done + nix_expr+="}" + + echo $nix_expr +} + + +# Complete attribute names using $1 as the toplevel expression NB: If calling +# this function from an action spec you need to prefix it with a space so that +# eg. _arguments won't pass it options which it doesn't expect, ie: +# `: _nix_attr_paths` +_nix_attr_paths () { + + local cur=${${words[$CURRENT]#(\'|\")}%(\'|\")} + + # Starting with '.' causes _sep_parts to complain, so exit early. + # This also guards against error output when completion './files' with nix. + if [[ $cur == .* ]]; then + return + fi + + local defexpr=$1 + local attr_path="" + if [[ $cur == *.* ]]; then + attr_path=${cur%.*} + fi + + # attr1.attr3 -> ("attr1" "attr2") + local -a paths=(${(s,.,)attr_path}) + # Add quotes in a second step to avoid ("") when empty + paths=(${${paths/%/\"}/#/\"}) + + # Auto call any functions in the attribute path. This isn't a language + # feature, but done by nix when passing attributes on the command line. + local -a result + result=($(_nix_eval_stdin < 0 ]]; then + _message "Eval failed, can't complete (an URL might not be cached): +$result" + return 1 + fi + + local -a prefix=() + if [[ -n $attr_path ]]; then + for i in ${=attr_path//./ }; do + prefix+=("($i)" .) + done + fi + + local package="" + _wanted package package "Attribute path" \ + _sep_parts $prefix result \. + return $? +} + +function _nix_eval_stdin () { + setopt local_options pipefail + # Build up a modified NIX_PATH using -I and --include + local i override="" + for ((i=1; i < ${#words[*]}; i++)); do + case "${words[i]}" in + -I|--include) + override+=${override:+:}${words[$((i+1))]} + ;; + esac + done + override+=${override:+:}${NIX_PATH} + + # Resolve channel: syntax + while [[ "$override" == *(=|:)channel:* ]]; do + local channel=${override#*channel:} + channel="channel:"${channel%%:*} + local url="https://nixos.org/channels/"${channel:8}"/nixexprs.tar.xz" + # Replace the channel with its url + override=${override/"$channel"/"$url"} + done + + # Resolve any url to a cache, else we might trigger a blocking download + while [[ "$override" == *https://* ]]; do + # Find the first url + local url=${override#*https://} + # Strip everything starting with the first colon + url="https://"${url%%:*} + local cache=$(_nix_resolve_url "$url") + # Replace the url with the cache + override=${override/"$url"/"$cache"} + done + + NIX_PATH=$override nix-instantiate --eval - 2>/dev/null | tr '[]"' ' ' + return $? +} + + +# Generate the top level expression in all the various ways the different +# commands expects it to be built. Then generate completions by calling +# _nix_attr_paths $defexpr +_nix_complete_attr_paths () { + + local defexpr="" + local file=$(_nix_get_file_arg) + if [[ "$file" ]]; then + # Extract --arg and --argstr into $args + local i=1 args="" name="" value="" + for ((i=1; i < ${#words[*]}; i++)); do + case "${words[$i]}" in + --arg) + name=${(Q)words[$((i+1))]} + value=${(Q)words[$((i+2))]} + args+="$name = $value;" + i=$((i+2)) + ;; + --argstr) + name=${(Q)words[$((i+1))]} + value=${(Q)words[$((i+2))]} + args+="$name = \"$value\";" + i=$((i+2)) + ;; + esac + done + args=${args:+{$args}} + + local opt + defexpr="import $file $args" + for opt in $words; do + case $opt in + --expr|-[^-]#E[^-]#) + defexpr="($file) $args" + break + ;; + esac + done + else + if [[ $service == nix-env ]]; then + defexpr=$(_nix_gen_defexpr ~/.nix-defexpr) + + elif [[ $service == nix ]]; then + # Extract the channels from NIX_PATH and -I/--include + local -a channels=(${(s.:.)NIX_PATH}) + # Add -I/--include afterwards, so they will shadow the NIX_PATH + channels+=(${(s.:.)opt_args[-I]}) + channels+=(${(s.:.)opt_args[--include]}) + + # Add the names in an associative array to avoid duplicates + local -A names + local channel name + for channel in $channels; do + name=${channel%%=*} + nix_path=${channel#*=} + if [[ $name != $channel ]]; then + # Only add paths with a name, not sure how they work + names[$name]=1 + fi + done + + defexpr=$'{ ' + for name in ${(@k)names}; do + # nixos-config isn't useful or possible to complete + [[ $name == nixos-config ]] && continue + defexpr+="$name = import <${name}>; " + done + defexpr+=' }' + fi + fi + + if [[ $defexpr ]]; then + _nix_attr_paths $defexpr + fi +} + +function _nix_resolve_url () { + local url=$1 + local version="$($service --version)" + local input + if [[ "${version##* }" == 1.11.* ]]; then + # works for nix 1.11 + input="$url" + else + # works for nix 1.12 + input="${url##*/}\0$url" + fi + local sha + sha=$(nix-hash --flat --base32 --type sha256 <(printf "$input")) + local cache=${XDG_CACHE_HOME:-~/.cache}/nix/tarballs + local link="$cache"/"$sha"-file + if [[ -e "$link" ]]; then + echo "$cache/$(basename $(readlink $link))-unpacked" + fi +} + +function _nix_get_file_arg () { + + local file="" + if [[ "$service" == (nix-env|nix) ]]; then + local i + # Extract the last seen -f/--file argument + for ((i=1; i < ${#words[*]}; i++)); do + case "${words[i]}" in + --file|-f) + file=${words[$((i+1))]} + ;; + -f\.) + # -f. is accepted shorthand for -f . + file=. + ;; + esac + done + elif [[ $line ]]; then + file=$line[1] + elif [[ -e shell.nix && $service == nix-shell ]]; then + file=shell.nix + elif [[ -e default.nix ]]; then + file=default.nix + fi + + # Remove one level of shell quoting to make sure we see the same value as + # the nix-* program will see. + # ($opt_args and $line contain the verbatim string: + # eg. given `nix-shell '' -A ` $line[1] will be `''` while + # nix-shell will see ``) + file=${(Q)file} + + if [[ "file" ]]; then + # Expand channel: syntax + if [[ "$file" == channel:* ]]; then + file="https://nixos.org/channels/"${file:8}"/nixexprs.tar.xz" + fi + + if [[ -e $file ]]; then + # If the path exist use the absolute path to make sure import will + # accept it. + # (Otherwise the path is likely a notation) + file=${file:a} + elif [[ "$file" == https://* ]]; then + file=$(_nix_resolve_url $file) + fi + fi + print -n -- $file +} + +function _nix_complete_function_arg () { + local file=$(_nix_get_file_arg) + local func=${file:+import $file} opt + local i exclude="" + for ((i=1; i < ${#words}; i++)); do + case "${words[$i]}" in + --expr|-[^-]#E[^-]#) + func="$file" + ;; + --arg|--argstr) + # Don't add the name we're currently typing + [[ $i == $((CURRENT - 1)) ]] && continue + exclude+=${exclude:+|}${words[$((i+1))]} + ;; + esac + done + if [[ ! $func ]]; then + return + fi + local -a names + names=($(_nix_eval_stdin 2>&1 < 0 ]]; then + _message "Eval failed, can't complete (an URL might not be cached): +$names" + return 1 + fi + names=(${names:#(${~exclude})}) + [[ "$names" ]] && _values "Argument name" $names +} + +_nix_profiles () { + local prefix='-P /nix/var/nix/profiles/ -W /nix/var/nix/profiles/' + local cur=$words[$CURRENT] + if [[ $cur ]]; then + prefix="" + fi + _path_files -/ ${=prefix} +} + +# Either true or false: useful for completing many Nix options +_nix_options_bool () { + _values true false +} +# List gathered from: https://nixos.org/nix/manual/#sec-conf-file +# TODO: Complete the value as well, not just the key +_nix_options () { + # Complete nix options with descriptions + local -a nix_options + # Strip the header line, remove leading spaces and replace separating + # whitespace with ':' + nix_options=(${${${${(f)"$(nix --help-config)"}:1:-1}/# /}/ ##/:}) + _describe -t nix_options "Option" nix_options +} + +_nix_options_value () { + # Print the description of the option we're setting + local OPTION=$words[$(($CURRENT - 1))] + # Remove lines not starting with " $OPTION " and strip eveything up to the + # last two consecutive spaces + local description=${${${(f)"$(nix --help-config)"}:#^( $OPTION *)}/* /} + local -a values=() + case "$description" in + Whether*) + _values $description true false + ;; + *) + _path_files + ;; + esac +} + +_nix_run_command_names () { + local cmd chan + + if (( ${+commands[sqlite3]} )); then + # Extract the channels from NIX_PATH and -I/--include + # Add -I/--include afterwards, so they will shadow the NIX_PATH + local -a nix_path=( + ${(s.:.)NIX_PATH} + ${(s.:.)opt_args[-I]} + ${(s.:.)opt_args[--include]} + ) + + # channels: key - channel name, value - path to channel + local -A channels + for chan in $nix_path; do + if [[ $chan = *=* ]]; then + # name=path + channels[${chan%%=*}]=${chan#*=} + else + # path to directory with channels + for chan in $chan/*(-/); do + channels[$chan:t]=$chan + done + fi + done + + # pkg_cmds is list of commands inside packages + # This is an associative array to avoid duplicates. + local -A pkg_cmds + for chan in ${(k)channels}; do + # Extract args with prefix "$chan." + local -a pkgs=( "${${(M)words[@]:#"$chan".*}[@]##"$chan".}" ) + (( ${#pkgs} )) || continue + + local db=${channels[$chan]}/programs.sqlite + [ -f "$db" ] || continue + + pkgs=( "'${^pkgs[@]//\'/''}'" ) # SQL-quote + local query="SELECT name FROM programs WHERE package IN (${(j:,:)pkgs})" + + for cmd in $(sqlite3 "$db" "$query"); do + pkg_cmds[$cmd]= + done + done + + compadd -X 'Package commands' -- ${(k)pkg_cmds} + fi + + _command_names -e -X 'All commands' +} + +## Common options + +# Used in: nix-build, nix-env, nix-instantiate, nix-shell, nixops +__nix_boilerplate_opts=( + '(- *)--help[Print help message and exit]' + '(- *)--version[Print version number and exit]' +) + +# Used in: nix-collect-garbage, nix-env, nix-store, nixops +__nix_dry_run='--dry-run[Show what would be done without doing it]' + +# Used in: nix-collect-garbage, nix-store +__nix_gc_common=( + '(- --print* --delete)--print-roots[Print roots used by garbage collector]' + '(- --print* --delete)--print-live[Print store paths reachable from roots]' + '(- --print* --delete)--print-dead[Print store paths not reachable from roots]' + '(- --print* --delete)--delete[Garbage collect all dead paths from the store]' +) + +# Used in: nixos-install, nix_common_opts +__nix_search_path_args=( + '*-I[add a path to the list of locations used to look up <...> file names]:include path:_nix_complete_includes' +) + +__nix_repair='--repair[Fix corrupted or missing store paths by redownloading or rebuilding]'; + +__nix_expr_opts=( + '(--expr -E)'{--expr,-E}'[interpret command line args as Nix expressions]' +) + +# Misc Nix options accepted by nixos-rebuild +__nix_common_nixos_rebuild=( + $__nix_search_path_args + $__nix_repair + '(--verbose -v)*'{--verbose,-v}'[Increase verbosity of diagnostic messages]' + '(--no-build-output -Q)'{--no-build-output,-Q}'[silence output to stdout and stderr]' + '(--max-jobs -j)'{--max-jobs,-j}'[max number of build jobs in parallel]:jobs:' + '--cores[threads per job (e.g. -j argument to make)]:cores:' + '(--keep-going -k)'{--keep-going,-k}"[keep going until all builds are finished]" + '(--keep-failed -K)'{--keep-failed,-K}'[keep failed builds (usually in /tmp)]' + '--fallback[If binary download fails, fall back on building from source]' + '--show-trace[Print stack trace of evaluation errors]' + '*--option[set Nix configuration option]:options:_nix_options:value:_nix_options_value' +) + +__nix_common_nixos_build_vms=( + '*--option[set Nix configuration option]:options:_nix_options:value:_nix_options_value' +) + +__nix_common_store_opts=( + '--add-root[register result as a root of the garbage collector]:path (Hint /nix/var/nix/gcroots):_path_files -/' + '--indirect[store gc root outside GC roots directory]' +) + +# Used in: nix-build, nix-env, nix-instantiate, nix-shell and nix-store +__nix_extra_build_opts=( + '--max-silent-time[max seconds without getting stdout/err from builder]:Seconds:' + '--timeout[max seconds builders should run]:seconds:' + '--readonly-mode[do not open Nix database]' + '--log-format[configure how output is formatted]:output format:((pretty\:"Default" escapes\:"Indicate nesting with escape codes" flat\:"Remove all nesting"))' +) + +# Used in: nix-build, nix-env, nix-instantiate, nix-shell +__nix_common_opts=( + $__nix_common_nixos_rebuild + $__nix_args_opts + $__nix_extra_build_opts + '*--include[add a path to the list of locations used to look up <...> file names]:include path:_nix_complete_includes' + '*--arg[argument to pass to the Nix function]:Name:_nix_complete_function_arg:Value: ' + '*--argstr[pass a string]:Name:_nix_complete_function_arg:String: ' +) + +# Options for nix-store --realise, used by nix-build +__nix_store_realise_opts=( + $__nix_dry_run + '--check[rebuild and see if output is deterministic]' +) + +_NIX_SHELL_COMPLETION_LOADED=1 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-copy-closure b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-copy-closure new file mode 100644 index 00000000..56d18887 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-copy-closure @@ -0,0 +1,14 @@ +#compdef nix-copy-closure +#autoload + +_nix-common-options + +_arguments \ + '(--from)--to[Copy the closure to the remote machine (default)]'\ + '(--to)--from[Copy the closure from the remote machine]'\ + '--sign[Cryptographically sign to allow sharing between untrusted users on trusted machines]'\ + '--gzip[Enable compression of the SSH connection]'\ + '--include-outputs[Also copy outputs of store derivations included in the closure]'\ + '(--use-substitutes -s)'{--use-substitutes,-s}'[Download files from the binary cache if possible]'\ + '1:user@machine:_user_at_host'\ + '2:paths:_files' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-env b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-env new file mode 100644 index 00000000..43ff4a3c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-env @@ -0,0 +1,170 @@ +#compdef nix-env +#autoload + +emulate -L zsh +setopt extendedglob + +local context state state_descr line +typeset -A opt_args + +_nix-common-options + +local -a _1st_arguments +_1st_arguments=( + {--install,-i}"[Install package]" + {--upgrade,-u}"[Upgrade package]" + {--uninstall,-e}"[Uninstall package]" + --set-flag'[Modify meta attribute of installed package]:Name:->flag_name:Value:->flag_value:*:Packages: _nix_installed_packages' + {--query,-q}"[List information about derivations]" + {--switch-profile,-S}"[Set the current profile path]" + "--list-generations[Print a list of all generations in the active profile]" + "--delete-generations[Delete specified generations]" + {--switch-generation,-G}"[Activate specified generation]" + "--rollback[Switch to the previous generation of active profile]" +) + +local -a _nix_env_common_opts=( + $__nix_common_opts + '(--profile -p)'{--profile,-p}'[Specify the profile to use]:Path:_nix_profiles' + $__nix_dry_run + '--system-filter[Only show derivations matching the specified platform]:system:_nix_systems' +) + +local -a _nix_env_b=( + '(--prebuilt-only -b)'{--prebuilt-only,-b}'[Fail if there is no pre-built binary available]' +) + +local _nix_env_from_profile +_nix_env_from_profile='--from-profile[Fetch store paths from another profile]:Profile:_nix_profiles' + +# Workaround: +# opt_args doesn't record plain options, so we can't use that +local expect_attr_paths=false +local opt +for opt in $words; do + case $opt in + --attr|-[^-]#A[^-]#) + expect_attr_paths=true + ;; + esac +done + +local -a command_options=() +# Look for a main option in the input and setup command_options appropriately +for opt in $words; do +case "$opt" in + --install|-[^-]#i[^-]#) + command_options=( + $_nix_env_common_opts + '(--attr -A)'{--attr,-A}'[Specify packages by attribute path instead of name]' + $_nix_env_b + $_nix_env_from_profile + '(--preserve-installed -P)'{--preserve-installed,-P}'[Do not remove derivations with the same name]' + '(--remove-all -r)'{--remove-all,-r}'[Remove all previously installed packages prior to installing]' + '*:Package:{if $expect_attr_paths; then + _nix_complete_attr_paths; + else + _nix_installed_packages "(use -A/--attr to access all packages)" + fi}') + break + ;; + --upgrade|-[^-]#u[^-]#) + command_options=( + $_nix_env_common_opts + $_nix_env_b + $_nix_env_from_profile + '(-lt -leq -eq --always)--lt[Upgrade derivations with newer versions (default)]' + '(-lt -leq -eq --always)--leq[Upgrade derivations with the same or newer version]' + '(-lt -leq -eq --always)--eq[Upgrade derivations with equivalent versions]' + '(-lt -leq -eq --always)--always[Upgrade even if version number decreases]' + '*:Packages: _nix_installed_packages') + break + ;; + --uninstall|-[^-]#e[^-]#) + command_options=( + ${_nix_env_common_opts:#'(--attr -A)'*} + '*::Packages: _nix_installed_packages') + break + ;; + --set-flag) + break + ;; + --query|-[^-]#q[^-]#) + command_options=( + $_nix_env_common_opts + '(--available -a)'{--available,-a}'[display all installable derivations]' + $_nix_env_b + '(--status -s)'{--status,-s}'[print status of derivation]' + '(--attr-path -P)'{--attr-path,-P}'[print attribute path of derivations]' + '--no-name[suppress printing of name attribute]' + '(--compare-versions -c)'{--compare-versions,-c}'[compare installed and available version]' + '--system[print system attribute]' + '--drv-path[print store derivation path]' + '--out-path[print output path]' + '--description[print description]' + '--xml[print output as xml]' + '--json[print output as json]' + '--meta[Print all meta attributes: only available with --xml]') + break + ;; + --switch-profile|-[^-]#S[^-]#) + command_options=($_nix_env_common_opts ':Profile:_nix_profiles') + break + ;; + --delete-generations) + command_options=($_nix_env_common_opts '*::Generations:_nix_generations') + break + ;; + --switch-generation|-[^-]#G[^-]#) + command_options=($_nix_env_common_opts '::Generations:_nix_generations') + break + ;; + --list-generations) + command_options=($_nix_env_common_opts) + break + ;; + --[^-]*|-[^-]#) + # Complete common options if the user has started writing something else + command_options=($_nix_env_common_opts) + ;; +esac +done + +# Let _arguments handle the rest, with _1st_arguments being mutually exclusive +# under the main_options group +_arguments -s $command_options \ + '*'{--file,-f}'[Specify Nix expression used to obtain derivations]:Path to file:_nix_path'\ + '-f.[evaluate ./default.nix rather than the default]' \ + $__nix_boilerplate_opts \ + - '(main_options)' \ + $_1st_arguments + +# Handle the --set-flag option +case $state in + flag_name) + local -a _set_flag_attrs=( + 'priority:Resolve package name conflicts' + 'keep:Prevent package from being upgraded' + 'active:Package is symlinked to profile' + ) + _describe -t commands "Package flag" _set_flag_attrs + break + ;; + flag_value) + local flag_name=$words[$(($CURRENT - 1))] + case $flag_name in + priority) + _message "Number, lower priority values denote a higher priority" + break + ;; + keep) + _values "TF" true false + break + ;; + active) + _values "TF" true false + break + ;; + esac + ;; +esac diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-hash b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-hash new file mode 100644 index 00000000..cf81fccd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-hash @@ -0,0 +1,16 @@ +#compdef nix-hash +#autoload + +_nix-common-options + +local -a ig +ig=( '--to-base16' '--to-base32' ) + +_arguments \ + '(- *)--to-base16[Convert a base 32 hash to hexadecimal]:Hash:( )' \ + '(- *)--to-base32[Convert a hexadecimal hash to base 32]:Hash:( )' \ + "($ig)--flat[Print hash of regular files rather than their NAR dump]" \ + "($ig)--base32[Print hash in base 32 rather than hexadecimal]" \ + "($ig)--truncate[Truncate hashes to 160 bits]" \ + "($ig)--type[Hash algorithm to use]:hashAlgo:(md5 sha1 sha256 sha512)" \ + "($ig)*:Store Paths:_files" && return 0 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-install-package b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-install-package new file mode 100644 index 00000000..6d53a016 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-install-package @@ -0,0 +1,11 @@ +#compdef nix-install-package +#autoload + +_nix-common-options + +_arguments \ + '--non-interactive[Do not open a terminal window and do not ask for confirmation]' \ + '(--profile -p)'{--profile,-p}'[Profile to install the package into]:Profile:_nix_profiles' \ + '--set[Install the package as the profile so that the profile contains nothing else]' \ + '(1)--url[URL to download the package file from]:URL:_urls' \ + '(--url)1:Package File:_files -g \*.nixpkg' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-instantiate b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-instantiate new file mode 100644 index 00000000..b79cc47e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-instantiate @@ -0,0 +1,23 @@ +#compdef nix-instantiate +#autoload + +_nix-common-options + +# --no-location: undocumented arg +# --repair: undocumented arg +_arguments \ + - regular \ + $__nix_boilerplate_opts \ + $__nix_common_opts \ + $__nix_common_store_opts \ + $__nix_expr_opts \ + '*'{--attr,-A}'[build a .drv from file (default: ./default.nix)]:package:_nix_complete_attr_paths' \ + '--xml[Print output from --eval as XML]'\ + '--json[Print output from --eval as JSON]'\ + '--parse[Just parse the input files and print their abstract syntax trees]'\ + '--eval[Just parse and evaluate the input files, and print the resulting values]'\ + '--strict[Cause --eval to recursively evaluate list elements and attributes]'\ + '--read-write-mode[Perform evaluation in read/write mode]'\ + '*:File to instantiate (default\: ./default.nix):_nix_path' \ + - find-file \ + "--find-file[Look up the given files on Nix's search path]:*:Lookup file using <...> logic:"\ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-prefetch-url b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-prefetch-url new file mode 100644 index 00000000..ed39e3f8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-prefetch-url @@ -0,0 +1,24 @@ +#compdef nix-prefetch-url +#autoload + +_nix-common-options + +_resource() { + local -a others=( + 'https\://:HTTPS URL' + 'http\://:HTTP URL' + 'mirror\://:Mirror defined in nixpkgs') + _alternative \ + 'url:Other: _describe "URLS and special options" others' \ + 'path:Local path (adds file url prefix):_path_files -P "file://"' +} + +_arguments \ + $__nix_search_path_args \ + '--unpack[Unpack tarball/zip first]'\ + '--print-path[Print the resulting store path]'\ + '--type[Use the specified hash algorithm]:Hash Algorithm:(md5 sha1 sha256 sha512)'\ + '--name[Override the resulting nix store filename]:nix store filename:'\ + '*'{--attr,-A}'[Fetch the src of derivation (eg. mpv.src)]:src (eg. mpv.src): _nix_complete_attr_paths'\ + '1:URL or a local nix file:_resource'\ + '2::Hash:( )' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-push b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-push new file mode 100644 index 00000000..9e050eb8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-push @@ -0,0 +1,15 @@ +#compdef nix-push +#autoload + +_nix-common-options + +_arguments \ + '--dest[Set the destination directory]:Destination directory:_path_files -/'\ + '(--none)--bzip2[Compress NARs using bzip2 instead of xz -9]'\ + '(--bzip2)--none[Do not compress NARs]'\ + '--force[Overwrite .narinfo files if they already exist]'\ + '--link[Hard link files into the destination directory rather than copying]'\ + '(--manifest-path)--manifest[Force the generation of a manifest suitable for use by nix-pull]'\ + '(--manifest)--manifest-path[Like --manifest, but specify the manifest filename]:Manifest filename:_files'\ + '--url-prefix[Specify the prefix URL used in the Manifest]:Prefix URL:_urls'\ + '*:Derivation Paths:_files' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-shell b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-shell new file mode 100644 index 00000000..ab16ae90 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-shell @@ -0,0 +1,36 @@ +#compdef nix-shell +#autoload + +_nix-common-options + +local -a _nix_shell_opts=( + '--command[Run a command instead of starting an interactive shell]:Command:_command_names' + '--exclude[Do not build any dependencies which match this regex]:Regex:( )' + '--pure[Clear the environment before starting the interactive shell]' + '--run[Run a command in a non-interactive shell instead of starting an interactive shell]:Command:_command_names' + '*'{--attr,-A}"[setup a build shell for package]:package:_nix_complete_attr_paths" +) + +local norm_arguments='*:Paths:_nix_path' +local word +for word in $words; do + case "$word" in + --packages|-[^-]#p[^-]#) + norm_arguments='*:Packages: _nix_attr_paths "import "' + break + ;; + --expr|-[^-]#E[^-]#) + norm_arguments='*:Expression:' + ;; + esac +done + +_arguments \ + $__nix_boilerplate_opts \ + $__nix_common_opts \ + $__nix_dry_run \ + $_nix_shell_opts \ + $norm_arguments \ + - '(group)' \ + $__nix_expr_opts \ + {--packages,-p}'[run with packages from (override usinge -I)]' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-store b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-store new file mode 100644 index 00000000..149942e0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nix-store @@ -0,0 +1,144 @@ +#compdef nix-store +#autoload + + +local context state state_descr line +typeset -A opt_args + +setopt extendedglob + +_nix-common-options + +local -a cmd_arguments=( + $__nix_boilerplate_opts + {--realise,-r}'[Build the specified store paths]' + '--serve[provide access to the nix store over stdin/stdout]' + '--gc[Perform garbage collection on the Nix store]' + '--delete[Delete store paths from the Nix store if it is safe to do so]' + {--query,-q}'[Display information about store paths]' + '--add[Add paths to the Nix store]' + '--verify[Verify the consistency of the Nix database and store]' + '--verify-path[Compare the contents of each store path to the hashes stored in the database]' + '--repair-path[Attempt to repair the specified paths by redownloading them]' + '--dump[Produce a NAR file containing the contents of the given path]' + '--restore[Unpack a NAR archive, read from stdin, to the given path]' + '--export[Serialize the specified store paths to stdout in a format which can be imported]' + '--import[Read searialized store paths from stdin and add them to the Nix store]' + '--optimise[Find identical files in the Nix store and hardlink them together to reduce disk usage]' + {--read-log,-l}'[Print the build log of the specified store paths]' + '--dump-db[Dump Nix database to stdout]' + '--load-db[Read a dump of the Nix database]' + '--print-env[Print the environment of a derivation as shell code]' + '--query-failed-paths[Print out store paths which failed to build]' + '--clear-failed-paths[Clear the "failed" state of the given store path]' + '--generate-binary-cache-key[generate an Ed25519 key pair to sign build outputs]:key-name::secret-key-file:_files:public-key-file:_files' +) + +# Common nix-store options +local -a common_opts=( + '*:Store Paths:_files' + $__nix_repair + $__nix_common_store_opts + $__nix_common_nixos_rebuild + $__nix_extra_build_opts +) + +local -a command_options +local opt +for opt in $words; do +case "$opt" in + --realise|-[^-]#r[^-]#) + command_options=( + $common_opts + $__nix_store_realise_opts + ) + break + ;; + --serve) + command_options=( + $common_opts + '--write[allow writing to the nix store]' + ) + break + ;; + --gc) + command_options=( + $common_opts + $__nix_gc_common + '--max-freed[stop the gc after freeing n bytes]:bytes:' + ) + break + ;; + --delete) + command_options=( + $common_opts + '--ignore-liveness[Ignore reachability from roots]' + ) + break + ;; + --query|-[^-]#q[^-]#) + command_options+=( + '(--use-output -u)'{--use-output,-u}'[Apply the query to the output path of any store derivations]' + '(--force-realise -f)'{--force-realise,-f}'[Realise each argument to the query first]' + ) + + local subopt + for subopt in $words; do + case "$subopt" in + --requisites|-R) + command_options+=( + $common_opts + '--include-outputs[Also include the output paths of store derivations]' + ) + break + ;; + --outputs|--references|--referrers|--referrers-closure|--deriver|-d|--graph|--tree|--binding|-b|--hash|--size|--roots) + command_options+=($common_opts) + break + ;; + esac + done + + command_options+=( + + '(query_subcmds)' + '--outputs[Print the output paths of the given store derivations]' + {--requisites,-R}'[Print the closure of the given store paths]' + '--references[Print immediate dependencies of the given store paths]' + '--referrers[Print store paths which refer to these paths]' + '--referrers-closure[Print the closure under the referrers relation]' + '--deriver[Print the deriver of the store paths]' + '--graph[Print the references graph of the store paths in Graphviz format]' + '--tree[Print the references graph of the store paths as an ASCII tree]' + {--binding,-b}'[Print the value of an attribute of the store derivations]:name:' + '--hash[Print the SHA-256 hash of the contents of the store paths]' + '--size[Print the size in bytes of the contents of the store paths]' + '--roots[Print the garbage collector roots that point to the store paths]' + ) + break + ;; + --verify) + command_options=( + $common_opts + '--check-contents[Compute and validate the SHA-256 hash of each store item]' + ) + break + ;; + --add|--verify-path|--repair-path|--dump|--restore|--export|--read-log|-l|--print-env) + command_options=($common_opts) + break + ;; + --dump-db|--load-db|--query-failed-paths|--optimise) + # nothing to complete + return + ;; + --[^-]*|-[^-]#) + # Complete common options if the user has started writing something else + command_options=($common_opts) + ;; +esac +done + +_arguments -s \ + $command_options \ + + '(main_options)' \ + $cmd_arguments && return 0 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixops b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixops new file mode 100644 index 00000000..7c056257 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixops @@ -0,0 +1,204 @@ +#compdef nixops +#autoload + +_nix-common-options + +# List of valid commands +local -a _1st_arguments +_1st_arguments=( + "list:list all known deployments"\ + "create:create a new deployment"\ + "modify:modify an existing deployment"\ + "clone:clone an existing deployment"\ + "delete:delete a deployment"\ + "info:show the state of the deployment"\ + "check:check the state of the machines in the network"\ + "set-args:persistently set arguments to the deployment specification"\ + "deploy:deploy the network configuration"\ + "send-keys:send encryption keys"\ + "destroy:destroy all resources in the specified deployment"\ + "stop:stop all virtual machines in the network"\ + "start:start all virtual machines in the network"\ + "reboot:reboot all virtual machines in the network"\ + "show-physical:print the physical network expression"\ + "ssh:login on the specified machine via SSH"\ + "ssh-for-each:execute a command on each machine via SSH"\ + "scp:copy files to or from the specified machine via scp"\ + "rename:rename machine in network"\ + "backup:make snapshots of persistent disks in network (EC2-only)"\ + "backup-status:get status of backups"\ + "remove-backup:remove a given backup"\ + "clean-backups:remove old backups"\ + "restore:restore machines based on snapshots of persistent disks in network (EC2-only)"\ + "show-option:print the value of a configuration option"\ + "list-generations:list previous configurations to which you can roll back"\ + "rollback:roll back to a previous configuration"\ + "delete-generation:remove a previous configuration"\ + "show-console-output:print the machines console output on stdout"\ + "dump-nix-paths:dump Nix paths referenced in deployments"\ + "export:export the state of a deployment"\ + "import:import deployments into the state file"\ + "edit:open the deployment specification in \$EDITOR"\ + ) + +# Options valid for every command +local -a _nixops_common_arguments +_nixops_common_arguments=( + '(--state -s)'{--state,-s}'[Path to state file that contains the deployments]:Statefile:_files -g \*.nixops'\ + '(--deployment -d)'{--deployment,-d}'[UUID or symbolic name of deployment on which to operate]'\ + '--confirm[Automatically confirm "dangerous" actions]'\ + '--debug[Turn on debugging output]'\ +) + +local -a _nixops_include_exclude +_nixops_include_exclude=( + '--include[Only operate on the specified machines]:Machine Names:_hosts' \ + '--exclude[Do not operate on the specified machines]:Machine Names:_hosts' \ +) + +local -a _nixops_search_path_args +_nixops_search_path_args=( + '-I[Add path to the Nix expression search path for all future evaluations]:Path:_nix_complete_includes' \ +) + +_arguments \ + $__nix_boilerplate_opts \ + '*:: :->subcmds' && return 0 + +if (( CURRENT==1 )); then + _describe -t commands "nixos-container subcommands" _1st_arguments + return +fi + +case "$words[1]" in + create) + _arguments \ + $_nixops_common_arguments\ + $_nixops_search_path_args \ + '*:Nix Expressions:_nix_complete_dotnix_files' + ;; + modify) + _arguments \ + $_nixops_common_arguments\ + $_nixops_search_path_args \ + '(--name -n)'{--name,-n}'[Change the symbolic name]:New Name:( )'\ + ;; + clone) + _arguments \ + $_nixops_common_arguments\ + '(--name -n)'{--name,-n}'[Symbolic name for the new deployment]'\ + ;; + delete) + _arguments \ + $_nixops_common_arguments\ + '--all[Delete all deployments in the state file]'\ + '--force[]' + ;; + deploy) + _arguments \ + $_nixops_common_arguments\ + '(--kill-obsolete -k)'{--kill-obsolete,-k}'[Destroy machines no longer listed in the deployment specification]'\ + $__nix_dry_run \ + $__nix_repair \ + '--create-only[Create missing machines only: build nothing and do not touch existing machines]'\ + '--build-only[Build the configuration without creating or deploying machines]'\ + '--copy-only[Do everything except activate the new configuration]'\ + '--check[Check that deployed machines are correctly configured]'\ + '--allow-reboot[Allow NixOps to reboot the instance if necessary]'\ + '--force-reboot[Reboot the machine to activate the new configuration]'\ + '--allow-recreate[Recreate resources that have disappeared]'\ + $_nixops_include_exclude \ + $_nixops_search_path_args \ + '--max-concurrent-copy[Set the maximum concurrent nix-copy-closure processes (Default 5)]:Number:( )' + ;; + destroy) + _arguments \ + $_nixops_common_arguments\ + '--all[Destroy all deployments]'\ + $_nixops_include_exclude \ + ;; + stop) + _arguments \ + $_nixops_common_arguments\ + $_nixops_include_exclude \ + ;; + start) + _arguments \ + $_nixops_common_arguments\ + $_nixops_include_exclude \ + ;; + info) + _arguments \ + $_nixops_common_arguments\ + '--all[Print information about all resources in all known deployments]'\ + '--plain[Print in a more easily parsed format]'\ + '--no-eval[Do not evaluate the deployment specification]' + ;; + check) + _arguments \ + $_nixops_common_arguments\ + '--all[Check all machines in all known deployments]' + ;; + ssh) + _arguments \ + $_nixops_common_arguments\ + '--include-keys[]' + ;; + ssh-for-each) + _arguments \ + $_nixops_common_arguments\ + '(--parallel -p)'{--parallel,-p}'[Execute the command on each machine in parallel]'\ + $_nixops_include_exclude \ + ;; + reboot) + _arguments \ + $_nixops_common_arguments\ + $_nixops_include_exclude \ + '--no-wait[Do not wait until the machines have finished rebooting]' + ;; + backup) + _arguments \ + $_nixops_common_arguments\ + $_nixops_include_exclude \ + ;; + restore) + _arguments \ + $_nixops_common_arguments\ + $_nixops_include_exclude \ + '--devices[Restore only the persistent disks which are mapped to the specified device names]:Device names:( )'\ + '--backup-id[Restore the persistent disks of all machines to a given backup except the ones listed here.]:Backup ids:( )' + ;; + show-option) + _arguments \ + $_nixops_common_arguments\ + '--xml[Format output as XML]'\ + '1:machine:_hosts'\ + '2:option:( )' + ;; + set-args) + _arguments \ + $_nixops_common_arguments\ + '--arg[Set the function argument]:Name:( ):Value:( )'\ + '--argstr[Like --arg but the value is a string]:Name:( ):Value:( )'\ + '--unset[Remove a previously set function argument]:Name:( )' + ;; + show-console-output) + _arguments \ + $_nixops_common_arguments\ + '1:machine:_hosts' + ;; + export) + _arguments \ + $_nixops_common_arguments\ + '--all[Apply to all deployments]' + ;; + import) + _arguments \ + $_nixops_common_arguments\ + '--include-keys[]' + ;; + *) + _arguments \ + $_nixops_common_arguments\ + ;; +esac diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-build-vms b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-build-vms new file mode 100644 index 00000000..d1046aae --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-build-vms @@ -0,0 +1,11 @@ +#compdef nixos-build-vms +#autoload + +_nix-common-options + +_arguments \ + $__nix_common_nixos_build_vms \ + '--show-trace[Show a trace of the output]'\ + "--no-out-link[Do not create a 'result' symlink]"\ + "--help[Show help]"\ + '1:Network Nix Expression:_nix_complete_dotnix_files' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-container b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-container new file mode 100644 index 00000000..93ebca9c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-container @@ -0,0 +1,70 @@ +#compdef nixos-container +#autoload + +_nix-common-options + +_containers () { + containers=($(nixos-container list)) + _wanted containers expl 'containers' compadd -a containers +} + +local -a _1st_arguments +_1st_arguments=( + 'list:Show list of containers'\ + 'create:Create a container'\ + 'destroy:Destroy a container'\ + 'start:Start a container'\ + 'stop:Stop a container'\ + 'status:Get status of a container'\ + 'update:Update container'\ + 'login:Login to a container'\ + 'root-login:Login to a container as root (no password needed)'\ + 'run:Run a container'\ + 'show-ip:Display the IP of a container'\ + 'show-host-key:Display the host key of a container' + ) + +_arguments \ + '(- 1 *)--help[Display help]'\ + '*:: :->subcmds' && return 0 + +if (( CURRENT==1 )); then + _describe -t commands "nixos-container subcommands" _1st_arguments + return +fi + +local _container_name='1:Container Name:_containers'; +local _container_config='--config[Config]:Config:( )'; +local _container_file='--config-file[Path to the container config file]:Path:_files'; + +case "$words[1]" in + create) + _arguments\ + $_container_name\ + $_container_config\ + $_container_file\ + '--system-path[System path]:Path:_files'\ + '--ensure-unique-name[Avoid name conflicts with other containers]'\ + '--auto-start[Start the container immediately]'\ + '--nixos-path[Path to ]:Path:_files'\ + '--host-address[Host IP of the veth interface]:host address:'\ + '--local-address[IPv4 address assined to the interface in the container]:local address:'\ + '--bridge[Put the host-side of the veth-pair into the named bridge]:Bridge interface'\ + '--port[Port forwarding]:port forwarding' + ;; + run) + # TODO: There are a few more arguments in this case + _arguments\ + $_container_name\ + ;; + update) + _arguments\ + $_container_name\ + $_container_config\ + $_container_file + ;; + destroy|start|stop|status|login|root-login|show-ip|show-host-key) + _arguments\ + $_container_name + ;; +esac diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-generate-config b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-generate-config new file mode 100644 index 00000000..b8299857 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-generate-config @@ -0,0 +1,11 @@ +#compdef nixos-generate-config +#autoload + +_nix-common-options + +_arguments \ + '--force[Overwrite /etc/nixos/configuration.nix if it exists]:'\ + '--root[Directory to treat as root of filesystem]:Root directory:_path_files -/'\ + '--dir[Directory to write configuration files to (Default /etc/nixos)]:Output directory:_path_files -/'\ + '--no-filesystems[Omit file system information from hardware configuration]'\ + '--show-hardware-config[Print hardware configuration to stdout without writing anything to disk]' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-install b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-install new file mode 100644 index 00000000..cca5b389 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-install @@ -0,0 +1,10 @@ +#compdef nixos-install +#autoload + +_nix-common-options + +_arguments \ + $__nix_search_path_args \ + '--root[Treat the given directory as the root of the NixOS installation]:Installation Root:_path_files -/'\ + '--show-trace[Print a stack trace in case of evaluation errors]'\ + '--chroot[Chroot into given installation]' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-option b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-option new file mode 100644 index 00000000..0b44ca4e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-option @@ -0,0 +1,23 @@ +#compdef nixos-option +#autoload +_nix-common-options # import _nix_attr_paths etc. + +_nixos-option-opts() { + local mods= + if [[ -n "$NIX_PATH" && "$NIX_PATH" =~ "nixos-config=" ]]; then + mods="(import )" + fi + local options=' + with import ; + (evalModules { + modules = import ++ [ '"$mods"' ]; + }).config + ' + + _nix_attr_paths $options +} + +_arguments \ + $__nix_search_path_args \ + '--all[Print the values of all options.]' \ + ':NixOS module options:_nixos-option-opts' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-rebuild b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-rebuild new file mode 100644 index 00000000..3586f24d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-rebuild @@ -0,0 +1,32 @@ +#compdef nixos-rebuild +#autoload + +_nix-common-options + +local -a _1st_arguments +_1st_arguments=( + 'switch:Build, activate, and update boot default' + 'boot:Build and update boot default without activating' + 'test:Build and activate without updating boot default' + 'build:Build without activating or updating boot default' + 'dry-build:Show what store paths would be built or downloaded without building' + 'dry-activate:Build and show what changes would be performed by the activation' + 'build-vm:Create a script which starts a VM with the built configuration' + 'build-vm-with-bootloader:Like build-vm, but boot using regular boot loader' +) + +_arguments \ + $__nix_common_nixos_rebuild \ + '--upgrade[Fetch the latest version of NixOS from the NixOS channel]'\ + '--install-bootloader[(Re)install bootloader on the configured device]'\ + "--no-build-nix[Don't build Nix package manager]"\ + '--fast[Equivalent to --no-build-nix --show-trace]'\ + '--rollback[Roll back to the previous configuration]'\ + '(--profile-name -p)'{--profile-name,-p}'[Profile to use to track current and previous system configurations]:Profile:_nix_profiles'\ + '1:: :->subcmds' && return 0 + +case $state in + subcmds) + _describe -t commands "nixos-rebuild subcommands" _1st_arguments + ;; +esac diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-version b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-version new file mode 100644 index 00000000..ece1b08d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/_nixos-version @@ -0,0 +1,7 @@ +#compdef nixos-version +#autoload + +_nix-common-options + +_arguments \ + '(- *)'{--hash,--revision}'[Print only the git hash of the channel]'\ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/init.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/init.zsh new file mode 100644 index 00000000..5ef4b434 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/init.zsh @@ -0,0 +1,3 @@ + +# Source module files. +source "${0:h}/nix.plugin.zsh" || return 1 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/nix-zsh-completions.plugin.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/nix-zsh-completions.plugin.zsh new file mode 100644 index 00000000..29833e18 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/nix-zsh-completions.plugin.zsh @@ -0,0 +1,31 @@ +# Nix Install +alias ni='nix-env -iA' + +# Nix Search +alias ns='nix-env -qaP' + +function prompt_nix_shell_precmd { + if [[ -n ${IN_NIX_SHELL} && ${IN_NIX_SHELL} != "0" || ${IN_NIX_RUN} && ${IN_NIX_RUN} != "0" ]]; then + if [[ -n ${IN_WHICH_NIX_SHELL} ]] then + NIX_SHELL_NAME=": ${IN_WHICH_NIX_SHELL}" + fi + if [[ -n ${IN_NIX_SHELL} && ${IN_NIX_SHELL} != "0" ]]; then + NAME="nix-shell" + else + NAME="nix-run" + fi + NIX_PROMPT="%F{8}[%F{3}${NAME}${NIX_SHELL_NAME}%F{8}]%f" + if [[ $PROMPT != *"$NIX_PROMPT"* ]] then + PROMPT="$NIX_PROMPT $PROMPT" + fi + fi +} + +function prompt_nix_shell_setup { + autoload -Uz add-zsh-hook + add-zsh-hook precmd prompt_nix_shell_precmd +} + +# Add this to your zshrc if you want the prompt prefixed with `[nix-shell]` +# when you're in a nix-shell environment. +# prompt_nix_shell_setup "$@" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/nix.plugin.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/nix.plugin.zsh new file mode 100644 index 00000000..29833e18 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/nix-zsh-completions/nix.plugin.zsh @@ -0,0 +1,31 @@ +# Nix Install +alias ni='nix-env -iA' + +# Nix Search +alias ns='nix-env -qaP' + +function prompt_nix_shell_precmd { + if [[ -n ${IN_NIX_SHELL} && ${IN_NIX_SHELL} != "0" || ${IN_NIX_RUN} && ${IN_NIX_RUN} != "0" ]]; then + if [[ -n ${IN_WHICH_NIX_SHELL} ]] then + NIX_SHELL_NAME=": ${IN_WHICH_NIX_SHELL}" + fi + if [[ -n ${IN_NIX_SHELL} && ${IN_NIX_SHELL} != "0" ]]; then + NAME="nix-shell" + else + NAME="nix-run" + fi + NIX_PROMPT="%F{8}[%F{3}${NAME}${NIX_SHELL_NAME}%F{8}]%f" + if [[ $PROMPT != *"$NIX_PROMPT"* ]] then + PROMPT="$NIX_PROMPT $PROMPT" + fi + fi +} + +function prompt_nix_shell_setup { + autoload -Uz add-zsh-hook + add-zsh-hook precmd prompt_nix_shell_precmd +} + +# Add this to your zshrc if you want the prompt prefixed with `[nix-shell]` +# when you're in a nix-shell environment. +# prompt_nix_shell_setup "$@" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/.gitignore b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/.gitignore new file mode 100644 index 00000000..6fd0a376 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/.gitignore @@ -0,0 +1,41 @@ +# Compiled Lua sources +luac.out + +# luarocks build files +*.src.rock +*.zip +*.tar.gz + +# Object files +*.o +*.os +*.ko +*.obj +*.elf + +# Precompiled Headers +*.gch +*.pch + +# Libraries +*.lib +*.a +*.la +*.lo +*.def +*.exp + +# Shared objects (inc. Windows DLLs) +*.dll +*.so +*.so.* +*.dylib + +# Executables +*.exe +*.out +*.app +*.i*86 +*.x86_64 +*.hex + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/LICENSE b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/LICENSE new file mode 100644 index 00000000..b9effe8c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2018 Linwei + +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. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/README.cn.md b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/README.cn.md new file mode 100644 index 00000000..4d386544 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/README.cn.md @@ -0,0 +1,461 @@ +# z.lua + +快速路径切换工具(类似 z.sh / autojump / fasd),兼容 Windows 和所有 Posix Shell 以及 Fish Shell,同时包含了众多改进。 + + +## Description + +z.lua 是一个快速路径切换工具,它会跟踪你在 shell 下访问过的路径,通过一套称为 Frecent 的机制(源自 FireFox),经过一段简短的学习之后,z.lua 会帮你跳转到所有匹配正则关键字的路径里 Frecent 值最高的那条路径去。 + +正则将按顺序进行匹配,"z foo bar" 可以匹配到 /foo/bar ,但是不能匹配 /bar/foo。 + + +## Features + +- 性能比 **z.sh** 快三倍,比 **fasd** / **autojump** 快十倍以上。 +- 支持 Posix Shell:bash, zsh, dash, sh, ash, busybox 等等。 +- 支持 Fish Shell,Power Shell 和 Windows cmd。 +- 使用增强匹配算法,更准确的带你去到你想去的地方。 +- 低占用,能够仅在当前路径改变时才更新数据库(将 `$_ZL_ADD_ONCE` 设成 1)。 +- 交互选择模式,如果有多个匹配结果的话,跳转前允许你进行选择。 +- 集成 fzf (可选),可以用来做可视化选择或者参数补全。 +- 快速跳转到父目录,或者项目根目录,代替反复 “cd ../../.." 。 +- 兼容 lua 5.1, 5.2 和 5.3 以上版本。 +- 自包含且无额外依赖,单个 `z.lua` 文件完成所有工作。 + + +## Examples + +```bash +z foo # 跳转到包含 foo 并且权重(Frecent)最高的路径 +z foo bar # 跳转到同时包含 foo 和 bar 并且权重最高的路径 +z -r foo # 跳转到包含 foo 并且访问次数最高的路径 +z -t foo # 跳转到包含 foo 并且最近访问过的路径 +z -l foo # 不跳转,只是列出所有匹配 foo 的路径 +z -c foo # 跳转到包含 foo 并且是当前路径的子路径的权重最高的路径 +z -e foo # 不跳转,只是打印出匹配 foo 并且权重最高的路径 +z -i foo # 进入交互式选择模式,让你自己挑选去哪里(多个结果的话) +z -I foo # 进入交互式选择模式,但是使用 fzf 来选择 +z -b foo # 跳转到父目录中名称以 foo 开头的那一级 +``` + + +## Install + +- Posix Shells(Bash、zsh、dash、sh 或 BusyBox 等): + + 在你的 `.bashrc`, `.zshrc` 或者 `.profile` 文件中按 shell 类型添加对应语句: + + eval "$(lua /path/to/z.lua --init bash)" # BASH 初始化 + eval "$(lua /path/to/z.lua --init zsh)" # ZSH 初始化 + eval "$(lua /path/to/z.lua --init posix)" # Posix shell 初始化 + + 用下面参数初始化会进入“增强匹配模式”: + + eval "$(lua /path/to/z.lua --init bash once enhanced)" # BASH 初始化 + eval "$(lua /path/to/z.lua --init zsh once enhanced)" # ZSH 初始化 + eval "$(lua /path/to/z.lua --init posix once enhanced)" # Posix shell 初始化 + + 同时 zsh 支持 antigen/oh-my-zsh 等包管理器,可以用下面路径: + + skywind3000/z.lua + + 进行安装,比如 antigen 的话,在 `.zshrc` 中加入: + + antigen bundle skywind3000/z.lua + + 就可以了(主要要放在 antigen apply 语句之前)。 + + **注意**:使用 WSL-1 的用户,需要安装 `lua-filesystem` 包: + + sudo apt-get install lua-filesystem + + 这是由于 wsl-1 的 [bug](https://github.com/microsoft/WSL/issues/5505) 引起的,使用 lua-filesystem 可以避免该问题。 + +- Fish Shell: + + 新建 `~/.config/fish/conf.d/z.fish` 文件,并包含如下代码: + + source (lua /path/to/z.lua --init fish | psub) + + Fish version `2.4.0` 或者以上版本都支持,还有一种初始化方法: + + lua /path/to/z.lua --init fish > ~/.config/fish/conf.d/z.fish + + 但是第二种方法需要记得在 z.lua 位置改变或者 lua 版本升级后需要重新生成。 + +- Power Shell: + + 在你 Power Shell 的配置文件 `profile.ps1` 中放入下面语句: + + Invoke-Expression (& { (lua /path/to/z.lua --init powershell) -join "`n" }) + + +- Windows cmd (with clink): + + - 将 z.lua 和 z.cmd 拷贝到 clink 的安装目录。 + - 将 clink 的安装目录添加到 `%PATH%` (z.cmd 可以被任意位置调用到)。 + - 保证 lua 命令在你的 `%PATH%` 环境变量中。 + + +- Windows cmder: + + - 将 z.lua 和 z.cmd 拷贝到 cmder/vendor 目录中。 + - 将 cmder/vendor 添加到环境变量 `%PATH%` 里面。 + - 保证 lua 命令在你的 `%PATH%` 环境变量中。 + + +## Options + +- 设置 `$_ZL_CMD` 来改变命令名称 (默认为 z)。 +- 设置 `$_ZL_DATA` 来改变数据文件 (default ~/.zlua)。 +- 设置 `$_ZL_NO_PROMPT_COMMAND` 为 1 来跳过钩子函数初始化(方便自己处理)。 +- 设置 `$_ZL_EXCLUDE_DIRS` 逗号分隔的路径列表,列表内的路径不会被收集。 +- 设置 `$_ZL_ADD_ONCE` 为 '1' 时,仅在当前路径 `$PWD` 改变时才更新数据库。 +- 设置 `$_ZL_MAXAGE` 来确定一个数据老化的阀值 (默认为 5000)。 +- 设置 `$_ZL_CD` 用来指定你想用的 cd 命令,比如有人用 cd_func 。 +- 设置 `$_ZL_ECHO` 为 1 可以在跳转后显示目标路径名称。 +- 设置 `$_ZL_MATCH_MODE` 为 1 可以打开 “增强匹配模式”。 +- 设置 `$_ZL_HYPHEN` 为 1 可以允许关键字中包含横线 (横线默认是 lua 正则关键字,要转写成 `%-`)。 + +## Aging + +`z.lua` 在数据库中为每条路径维护着一个称为 rank 的字段,用于记录每条历史路径的访问次数,每次访问某路径,该路径对应 rank 字段的值就会增加 1。随着被添加的路径越来越多,`z.lua` 使用一种称为 “数据老化” 的方式来控制数据的总量。即,每次更新数据库后,会将所有路径的 rank 值加起来,如果这个值大于 5000 (`$_ZL_MAXAGE`),所有路径的 rank 值都会乘以 0.9,然后剔除所有 rank 小于 1 的记录。 + + +## Frecency + +Frecency 是一个由 'recent' 和 'frequency' 组成的合成词,这个术语由 Mozilla 发明,用于同时兼顾访问的频率和上一次访问到现在的时间差(是否最近访问)两种情况。 + +对于 z.lua,一条路径如果访问次数过低,它的 rank 值就会比较低,但是如果它最近被访问过,那么它将迅速获得一个比其他曾经频繁访问但是最近没有访问过的路径更高的权重。Frecent 并不记录在数据库中,是运行的时候即时计算出来的。 + + + +## 默认匹配算法 + +默认情况下 z.lua 使用和 z.sh 类似的匹配算法,成为默认匹配法。给定路径会按顺序匹配各个正则表达式。 + +- cd 到一个包含 foo 的路径: + + z foo + +- cd 到一个以 foo 结尾的路径: + + z foo$ + +- 使用多个参数进行跳转: + + 假设路径历史数据库(~/.zlua)中有两条记录: + + 10 /home/user/work/inbox + 30 /home/user/mail/inbox + + `"z in"`将会跳转到 `/home/user/mail/inbox` 因为它有更高的权重,同时你可以传递更多参数给 z.lua 来更加精确的指明,如 `"z w in"` 则会让你跳到 `/home/user/work/inbox`。 + +## 增强匹配算法 + +你可以通过设置环境变量来启用增强匹配模式: + + export _ZL_MATCH_MODE=1 + +或者使用下面语句: + + eval "$(lua /path/to/z.lua --init bash enhanced)" + +进行初始化,他们是等效的,记得把上面的 bash 可以根据你的 shell 改为 `zsh` 或者 `posix`。 + + +对于一个给定的正则关键字序列(即 z 命令后面的参数),只有同时满足两个条件才算匹配成功: + +1. 正则关键字将按顺序进行匹配(这条和默认匹配法相同)。 +2. 最后一个关键字可以和路径名的最后一段相匹配。 + +如果两条规则同时启用找不到任何结果,那么将会退回到只用规则 1 进行筛选,这两条规则是参考 fasd 引入的。 + +- 匹配路径名的最后一段: + + 假设数据库内容为: + + 10 /home/user/workspace + 20 /home/user/workspace/project1 + 30 /home/user/workspace/project2 + 40 /home/user/workspace/project3 + + 在增强模式下使用 `"z wo"` 的话,只有 `/home/user/workspace` 满足匹配,因为按照第二条规则,这是唯一一条最有一段名称匹配 `wo` 的路径。 + + 因为最后一级目录名称总是最容易记住的,所以给到它比较高的优先级。在默认匹配算法中,你同样可以用 `"z space$"` 来达到相同的目的,但是 `"z wo"` 可以打更少的字。 + + 小技巧: + + - 如果你在增强匹配算法下,想让最后一个关键字不当匹配最后一段路径名,还可以像默认匹配算法中一样匹配路径的其他部分的话,你可以在最后加一个独立的 '$' 参数,比如:`"z wo $"` + - 如果你在增强匹配算法下,想让最后一个关键字匹配最后一段路径名以前的部分,那么可以增加一个斜杆参数,比如:`"z wo /"`。 + + +- 如果没法匹配,同时又存在一条路径名和关键字相同,那么 cd 过去: + + 有时候如果你输入: + + z foo + + 但是数据库里又没有任何匹配 foo 的记录,然后却存在一个可以在当前位置访问的目录,刚好名字是 "foo",那么 "`z foo`" 的效果将会和下面的命令效果相同: + + cd foo + + 因此,在增强匹配算法中,你总可以象 cd 命令一样使用 z 命令,而不必当心目标路径是否被记录过。 + +- 忽略当前路径: + + 如果你使用 `z xxx` 但是当前路径恰好是最佳匹配结果,那么 z.lua 会使用次优结果进行跳转。假设有如下数据: + + 10 /Users/Great_Wall/.rbenv/versions/2.4.1/lib/ruby/gems + 20 /Library/Ruby/Gems/2.0.0/gems + + 默认情况下,当我使用 `z gems` 时,我会被带到 `/Library/Ruby/Gems/2.0.0/gems`,因为它有更高权重,但是可能并不是我想要去的地方,这时我按一下方向键上键,再次执行 `z gems`,那么我就能被带到 `/Users/Great_Wall/.rbenv/versions/2.4.1/lib/ruby/gems` 目录中,而这正是我想去的地方。 + + 我当然可以每次使用`z env gems` 来精确指明,但是每当我输入 `z xxx` 我必然是想进行路径跳转的,而不是呆在原地,所以使用增强匹配模式,即便当前目录是最佳匹配,它也能懂得你想跳转的心思。 + +再我最初实现 z.lua 时,只有一个和 z.sh 类似的默认匹配算法,在网友的建议下,我陆续学习了来自 fasd / autojump 中的优秀理念,并加以完善改进,成为如今集三家之长的 “增强匹配算法” ,给它取个昵称,叫做 “更懂你的匹配算法”。 + + +## Add once + +何时更新数据呢?默认情况下,z.lua 会在每次显示命令提示符时记录当前路径(和 z.sh 一致),但是还提供了一个 $_ZL_ADD_ONCE 的环境变量选项,设置成 1 的话,只有当前路径改变,才会将新路径添加到数据库。 + +除了设置环境变量外,不同的 shell 下还可以在初始化时增加 "once" 参数来达到相同目的,比如: + +````bash +eval "$(lua /path/to/z.lua --init bash once enhanced)" +eval "$(lua /path/to/z.lua --init zsh once enhanced)" +source (lua /path/to/z.lua --init fish once enhanced | psub) +```` + +将会同时启用增强匹配算法和 once 机制,在一些比较慢的硬件下(路由器,cygwin,msys),使用该机制将有效的提升性能。其实 autojump 在 zsh 下会使用类似 once 的机制,而 bash 下则和 z.sh 类似。 + +从效果上来讲,z.sh 的模式(关闭 once)强调的是 “在某路径下工作的时间长短”,而 autojump 的模式(启用 once)则强调 “进入某路径的次数多少”。 + +## 交互式选择模式 + +使用 -i 参数进行跳转时, 如果有多个匹配结果,那么 z.lua 会给你显示一个列表: + +```bash +$ z -i soft +3: 0.25 /home/data/software +2: 3.75 /home/skywind/tmp/comma/software +1: 21 /home/skywind/software +> {光标位置} +``` + +然后你按照最前面的序号输入你想要去的地方,比如输入 3 就会进入 `/home/data/software`。如果你不输入任何东西直接按回车,那么将会直接退出而不进行任何跳转。 + +PS:如果你使用 Fish shell,需要 2.7.0 以上才支持该功能。 + +## FZF supports + +版本 1.1.0 引入了新的 `"-I"` 参数,让你可以使用 fzf 在多项结果进行快速选择: + + +![](images/fzf.png) + +当你使用 `"z -I vim"` 时,12 条路径被筛选出来,并按照 frecent 排序,他们都包含 "vim" 关键字,在实际 cd 改变路径前,z.lua 会调用 fzf 来让你更方便的选择你想去的地方,每条记录包含左边的 frecent 权重和右边的路径名,权重越高的排在越前面。 + +你可以在 fzf 里输入一些**空格分隔**的关键字(不需要先后顺序),或者按 `CTRL+J` / `CTRL+K` (方向键的上下也可以)进行选择,`ESC` 或者 `CTRL`+`D`/`G` 放弃。 + +你仍然可以用老方法,通过在 `z` 命令后面添加更多关键词来精确的匹配你想去的地方,这个特性给了你一个可视化的方式来做这件事情。为了方便起见,通常把 `z -I` alias 成 `zf` (z + fuzzy finder)。如果搜索结果只有一项,那么 z.lua 会直接跳转过去,不需要启动 fzf 再选择一遍,只有多项结果要选择时,才会启动 fzf。 + +`"z -I ."` 或者 `"zf ."` 可以让 fzf 来对整个数据库中的路径进行选择。 + +PS:你可以使用 `$_ZL_FZF` 环境变量来精确指明 fzf 的可执行路径,默认的话就是 fzf。如果你使用 Fish shell,需要 2.7.0 以上才支持该功能。 + + +## 快速回到父目录 + +`"-b"` 选项可以快速回到某一级父目录,避免重复的输入 "cd ../../.."。 + +- **(没有参数)**:`cd` 到项目根目录,即跳转到最近的包含 (.git/.svn/.hg) 的父目录。 +- **(单个参数)**:`cd` 到离当前目录最近的以关键字开头的父目录,如果找不到就尝试跳到包含关键字的父目录。 +- **(两个参数)**:将当前路径中的第一个关键词替换为第二个关键词。 + +先将 `z -b` 别名成 `zb`: + +```bash +# 一直向上退到项目根目录(就是里面有一个 .git 目录的地方) +~/github/lorem/src/public$ zb + => cd ~/github/lorem + +# cd 到第一个以 g 开头的父目录 +~/github/vimium/src/public$ zb g + => cd ~/github + +# 快速回到 site 目录 +~/github/demo/src/org/main/site/utils/file/reader/whatever$ zb si + => cd ~/github/demo/src/org/main/site + +# 将 jekyll 替换为 ghost +~/github/jekyll/test$ zb jekyll ghost + => cd ~/github/ghost/test +``` + +向后跳转同样也支持环境变量 `$_ZL_ECHO`(用来显示跳转结果),这样可以搭配其他工具,在目标目录内执行命令,而并不需要改变当前工作目录(比如:``ls `zb git` ``)。 + +环境变量 `$_ZL_ROOT_MARKERS` 是一个逗号分隔的列表,用来识别项目根目录,可以重定义成: + + +```bash +export _ZL_ROOT_MARKERS=".git,.svn,.hg,.root,package.json" +``` + +这样在用 `zb` 时,可以回到包含 `.root`文件,或者 `package.json` 文件的父目录。 + +**Bonus**:`zb ..` 相当于 `cd ..`,`zb ...` 相当于 `cd ../..`,而 `zb ....` 相当于 `cd ../../..` 等等。 最后 `zb ..20` 等同于调用 `cd ..` 二十次。 + +**Bonus**: 试试 `z -b -i` 以及 `z -b -I`,推荐把他们取个别名成 `zbi` 和 `zbf`。 + + +## 补全功能 + +zsh/fish 的补全系统是比较完善的,使用 `z foo` 就能触发补全,显示一个列表: + +![](images/complete-1.png) + +再次按 `` 键,就可以用可视化的方式对列表进行选择。 + +在 bash 下面补全系统没有那么强大,所以 z.lua 引入了 fzf 补全,初始化时在 `--init` 后追加 `fzf` 关键字: + +```bash +eval "$(lua /path/to/z.lua --init bash enhanced once echo fzf)" +``` + +如果你想在 zsh 中使用 fzf 补全,初始化时在 `--init` 后追加 `fzf` 关键字: + +```zsh +eval "$(lua /path/to/z.lua --init zsh enhanced once echo fzf)" +``` + +然后你在 bash/zsh 中,输入部分关键字后按 tab,就能把匹配的路径列出来: + +![](images/complete-2.png) + +有了 fzf 的帮助,bash 下补全也非常方便了。注意看左边的权重,fzf 搜索过滤的顺序是有讲究的,Frecent 权重越高的越靠前,不是乱排序的,更不是简单的按字符串字母排序。这里完全保证权重越高的路径越靠前。 + +`z.lua` 可以同 [fz](https://github.com/changyuheng/fz) 协作以提供**更好的补全结果**,详细见 [FAQ](https://github.com/skywind3000/z.lua/wiki/FAQ#fzsh-for-better-completion)。 + +注意:该功能在初始化 z.lua 之前,会检测 $PATH 中是否有 fzf 这个程序,有的话才启用。 + + +## MRU + +`z.lua` 提供 `dirstack` 让你更便捷的访问最近刚刚去过的目录,而不需要输入任何关键字。这个方法叫做 `dirstack`,它记录着最近你刚刚去过的 10 条最新路径,然后是用 `z -`,`z --` 和 `z -{num}` 来操作: + +```bash +# 显示当前的 dir stack +$ z -- + 0 /home/skywind/work/match/memory-match + 1 /home/skywind/.local/etc + 2 /home/skywind/software/vifm-0.9.1 + 3 /home/skywind/work + 4 /home/skywind/work/match + +# cd 到栈里 2 号路径 +$ z -2 + => cd /home/skywind/software/vifm-0.9.1 + +# 弹出栈顶 (cd 到上一次的老路径),和 "z -0" 相同 +$ z - + => cd - +``` + +这个 `dirstack` 是根据 z.lua 的路径历史数据库计算的出来的,和具体的 shell 或者操作系统无关。你退出再登陆不会丢失这些记录,不同的 shell 之间也可以共享同一份记录。 + +此外,还能通过前面提到的 `-I` 和 `-t` 参数组和,使用 fzf 选择最近去过的目录: + +```bash +alias zh='z -I -t .' +``` + +方便起见,定义个新的别名 `zh`(回到历史路径的意思),我们用 `-t` 参数来告诉 `z.lua` 按时间戳为权重排序,同时 `-I` 启用 fzf 搜索,最后句号代表任意路径。 + +那么当我们在命令行敲入 zh 时,就可以用 fzf 进行历史路径操作了: + +![](images/mru.png) + +第一列上次访问距今多少秒,第二列是目录名。你可以试着敲几个字母,用 fzf 的字符串模糊匹配进行定位,或者用光标键的上和下(CTRL+J/K 也可以)来上下移动,最后按回车 cd 过去,或者 ESC 放弃。 + + + +## Tips + +推荐一些常用的命令别名: + +```bash +alias zc='z -c' # 严格匹配当前路径的子路径 +alias zz='z -i' # 使用交互式选择模式 +alias zf='z -I' # 使用 fzf 对多个结果进行选择 +alias zb='z -b' # 快速回到父目录 +``` + +导入 z.sh 的数据: + + +```bash +cat ~/.z >> ~/.zlua +``` + +导入 autojump 的数据: + +```bash +FN="$HOME/.local/share/autojump/autojump.txt" +awk -F '\t' '{print $2 "|" $1 "|" 0}' $FN >> ~/.zlua +``` + +要更好的使用 `z.lua`,别忘记阅读:[Frequently Asked Questions](https://github.com/skywind3000/z.lua/wiki/FAQ)。 + + +## Benchmark + +最慢的部分当然是添加当前路径到数据库。该操作会在每次你按回车时执行,所以我在我的 Nas 上做了个对比: + +```bash +$ time autojump --add /tmp +real 0m0.352s +user 0m0.077s +sys 0m0.185s + +$ time fasd -A /tmp +real 0m0.618s +user 0m0.076s +sys 0m0.242s + +$ time _z --add /tmp +real 0m0.194s +user 0m0.046s +sys 0m0.154s + +$ time _zlua --add /tmp +real 0m0.052s +user 0m0.015s +sys 0m0.030s +``` + +可以看出,z.lua 是消耗资源最少,并且最快的,可以更流畅的在性能不好的环境中使用。 + +## Why Lua ? + +更好的兼容性,最开始我想要在我的路由器和 Nas 系统上使用 z.sh,但是它依赖的 awk 版本比较高,这两个系统上的 awk 都是一个 busybox 的经过裁剪的 awk ,z.sh 完全无法正常工作。使用 shell 开发还有一个问题是严重依赖 shell 的版本,很多逻辑既要在 zsh 下可以运行,又要在 dash 下能跑,用 lua 开发的话,核心逻辑全部写成 lua 不用考虑太多琐碎的兼容性,可以为各种 shell 提供完全一致的体验。 + +描述力强,可以更好的实现核心功能,同时速度更快,纯 shell 开发的话,太多语句是通过子进程 shell 的模式运行,所以性能很差,而 Python 开发的话启动速度又太慢,我在 Cygwin/msys 下用 z.sh 都觉得很卡,autojump/fasd 卡到不能用。 + +最关键的一点,Lua 速度很快 200 KB 的可执行程序,启动速度是 python 的 3倍,perl 的 2 倍,很多命令行工具 go/rust 写成,动不动就 2MB / 3MB,他们都还没有完成加载,lua 脚本可能都运行完了。 + + +## Credit + +Releated projects: + +- [rupa/z](https://github.com/rupa/z): origin z.sh implementation +- [JannesMeyer/z.ps](https://github.com/JannesMeyer/z.ps): z for powershell + + +## License + +Licensed under MIT license. + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/README.md new file mode 100644 index 00000000..301fa76e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/README.md @@ -0,0 +1,593 @@ +# z.lua + +A command line tool which helps you navigate faster by learning your habits :zap: + +An alternative to [z.sh](https://github.com/rupa/z) with windows and posix shells support and various improvements. + +【[README in Chinese | 中文文档](README.cn.md)】 + + +## Description + +z.lua is a faster way to navigate your filesystem. It tracks your most used directories, based on 'frecency'. After a short learning phase, z will take you to the most 'frecent' directory that matches ALL of the regexes given on the command line, in order. + +For example, `z foo bar` would match `/foo/bar` but not `/bar/foo`. + +## Reputation + +From people using z.lua: + +- I like this in principal. I’m pretty damn predictable at the command line and far too lazy to make shortcuts +- It feels far more intuitive and it's so incredibly convenient to be able to jump between folders I'm working in without having to traverse an entire tree. The shell used to feel so constraining for me, but tools like this are making me enjoy it so much more. +- I can finally have autojump-like functionality on my Raspberry Pi 1 without waiting 30 seconds every time I open a new shell. Thanks z.lua devs. +- Anyway, z.lua is a promising project. If you only need directory jumping, it may be the best choice. + + +## Features + +- **10x** times faster than **fasd** and **autojump**, **3x** times faster than **z.sh**. +- Gain the ultimate speed with an optional [native module](https://github.com/skywind3000/czmod) written in C. +- Available for **posix shells**: bash, zsh, dash, sh, ash, ksh, busybox and etc. +- Available for Fish Shell, Power Shell and Windows cmd. +- [Enhanced matching algorithm](#enhanced-matching) takes you to where ever you want precisely. +- Allow updating database only if `$PWD` changed with "$_ZL_ADD_ONCE" set to 1. +- Interactive selection enables you to choose where to go before cd. +- Integrated with FZF (optional) for interactive selection and completion. +- Quickly go back to a parent directory instead of typing "cd ../../..". +- Corresponding experience in different shells and operating systems. +- Compatible with Lua (5.1, 5.2, 5.3+) and luajit. +- Self contained, distributed as a single `z.lua` script, no other dependence. + + +## Examples + +```bash +z foo # cd to most frecent dir matching foo +z foo bar # cd to most frecent dir matching foo and bar +z -r foo # cd to the highest ranked dir matching foo +z -t foo # cd to most recently accessed dir matching foo +z -l foo # list matches instead of cd +z -c foo # restrict matches to subdirs of $PWD +z -e foo # echo the best match, don't cd +z -i foo # cd with interactive selection +z -I foo # cd with interactive selection using fzf +z -b foo # cd to the parent directory starting with foo +z -b foo bar # replace foo with bar in cwd and cd there +``` + + +## Install + +- Bash: + + put something like this in your `.bashrc`: + + eval "$(lua /path/to/z.lua --init bash)" + + the default matching algorithm is similar to z.sh to keep compatible, you may like the enhanced matching algorithm for productivity: + + eval "$(lua /path/to/z.lua --init bash enhanced once)" + + and perhaps this: + + eval "$(lua /path/to/z.lua --init bash enhanced once echo)" + + if you want `z.lua` print the new directory after cd. + + For `fzf` tab completion use: + + eval "$(lua /path/to/z.lua --init bash enhanced once fzf)" + + **NOTE**: For wsl-1 users, `lua-filesystem` must be installed: + + sudo apt-get install lua-filesystem + + To avoid a wsl-1 [defect](https://github.com/microsoft/WSL/issues/5505). + +- Zsh: + + put something like this in your `.zshrc`: + + eval "$(lua /path/to/z.lua --init zsh)" + + Options like "enhanced", "once" and "fzf" can be used after `--init` too. It can also be initialized from "skywind3000/z.lua" with your zsh plugin managers (antigen / oh-my-zsh). + + **NOTE**: for wsl-1 users, `lua-filesystem` must be installed. + +- Posix Shells: + + put something like this in your `.profile`: + + eval "$(lua /path/to/z.lua --init posix)" + + For old shells like ksh (Korn Shell), some features are missing, you can try: + + eval "$(lua /path/to/z.lua --init posix legacy)" + + To generate old posix compatible script. + +- Fish Shell (version `2.4.0` or above): + + Create `~/.config/fish/conf.d/z.fish` with following code + + lua /path/to/z.lua --init fish | source + + If you'd like `z.lua` to cooperate with fish's own [directory history](https://fishshell.com/docs/3.2/index.html#id34), you can put + + set -gx _ZL_CD cd + + into the same file. + +- Power Shell: + + > ⚠️ **WARNING**: users of [Starship Prompt](https://starship.rs/) should add the following command *after* `starship init`. + + put something like this in your `profile.ps1`: + + Invoke-Expression (& { (lua /path/to/z.lua --init powershell) -join "`n" }) + +- Windows cmd (with clink): + + - Copy z.lua and z.cmd to clink's home directory + - Add clink's home to `%PATH%` (z.cmd can be called anywhere) + - Ensure that "lua" can be called in `%PATH%` + +- Windows cmder: + + - Copy z.lua and z.cmd to cmder/vendor + - Add cmder/vendor to `%PATH%` + - Ensure that "lua" can be called in `%PATH%` + +- Windows WSL-1: + + Install `lua-filesystem` module before init z.lua: + + sudo apt-get install lua-filesystem + + This module is required due to a wsl-1 [defect](https://github.com/microsoft/WSL/issues/5505). + + + +## Options + +- set `$_ZL_CMD` in .bashrc/.zshrc to change the command (default z). +- set `$_ZL_DATA` in .bashrc/.zshrc to change the datafile (default ~/.zlua). +- set `$_ZL_NO_PROMPT_COMMAND` if you're handling PROMPT_COMMAND yourself. +- set `$_ZL_EXCLUDE_DIRS` to a comma separated list of dirs to exclude. +- set `$_ZL_ADD_ONCE` to '1' to update database only if `$PWD` changed. +- set `$_ZL_MAXAGE` to define a aging threshold (default is 5000). +- set `$_ZL_CD` to specify your own cd command (default is `builtin cd` in Unix shells). +- set `$_ZL_ECHO` to 1 to display new directory name after cd. +- set `$_ZL_MATCH_MODE` to 1 to enable enhanced matching. +- set `$_ZL_NO_CHECK` to 1 to disable path validation, use `z --purge` to clean +- set `$_ZL_HYPHEN` to 1 to treat hyphon (-) as a normal character not a lua regexp keyword. +- set `$_ZL_CLINK_PROMPT_PRIORITY` change clink prompt register priority (default 99). + +## Aging + +The rank of directories maintained by z.lua undergoes aging based on a simple formula. The rank of each entry is incremented every time it is accessed. When the sum of ranks is over 5000 (`$_ZL_MAXAGE`), all ranks are multiplied by 0.9. Entries with a rank lower than 1 are forgotten. + + +## Frecency + +Frecency is a portmanteau of 'recent' and 'frequency'. It is a weighted rank that depends on how often and how recently something occurred. As far as I know, Mozilla came up with the term. + +To z.lua, a directory that has low ranking but has been accessed recently will quickly have higher rank than a directory accessed frequently a long time ago. Frecency is determined at runtime. + + +## Default Matching + +By default, `z.lua` uses default matching algorithm similar to the original `z.sh`. Paths must be match all of the regexes in order. + +- cd to a directory contains foo: + + z foo + +- use multiple arguments: + + Assuming the following database: + + 10 /home/user/work/inbox + 30 /home/user/mail/inbox + + `"z in"` would cd into `/home/user/mail/inbox` as the higher weighted entry. However you can pass multiple arguments to z.lua to prefer a different entry. In the above example, `"z w in"` would then change directory to `/home/user/work/inbox`. + +- use regexes: + + ```bash + z foo$ # cd to a directory ends with foo + z %d # cd to a directory that contains a digit + ``` + + Unlike `z.sh`, `z.lua` uses the [Lua regular expression syntax](https://www.lua.org/pil/20.2.html). + +## Enhanced Matching + +Enhanced matching can be enabled by exporting the environment: + +```bash +export _ZL_MATCH_MODE=1 +``` + +Or, append a `enhanced` after `--init xxx`: + +```bash +eval "$(lua /path/to/z.lua --init bash enhanced)" +``` + +For a given set of queries (the set of command-line arguments passed to z.lua), a path is a match if and only if: + +1. Queries match the path in order (same as default method). +2. The last query matches the last segment of the path. + +If no match is found, it will fall back to default matching method. + +- match the last segment of the path: + + Assuming the following database: + + 10 /home/user/workspace + 20 /home/user/workspace/project1 + 30 /home/user/workspace/project2 + 40 /home/user/workspace/project3 + + If you use `"z wo"` in enhanced matching mode, only the `/home/user/workspace` will be matched, because according to rule No.2 it is the only path whose last segment matches `"wo"`. + + Since the last segment of a path is always easier to be recalled, it is sane to give it higher priority. You can also achieve this by typing `"z space$"` in both methods, but `"z wo"` is easier to type. + + Tips for rule No.2: + + - If you want your last query **not only** to match the last segment of the path, append '$' as the last query. eg. `"z wo $"`. + - If you want your last query **not** to match the last segment of the path, append '/' as the last query. eg. `"z wo /"`. + + +- cd to the existent path if there is no match: + + Sometimes if you use: + + z foo + + And there is no matching result in the database, but there is an existent directory which can be accessed with the name "foo" from current directory, "`z foo`" will just work as: + + cd foo + + So, in the enhanced matching method, you can always use `z` like `cd` to change directory even if the new directory is untracked (hasn't been accessed). + +- Skip the current directory: + + When you are calling `z xxx` but the best match is the current directory, z.lua will choose the 2nd best match result for you. Assuming the database: + + 10 /Users/Great_Wall/.rbenv/versions/2.4.1/lib/ruby/gems + 20 /Library/Ruby/Gems/2.0.0/gems + + When I use `z gems` by default, it will take me to `/Library/Ruby/Gems/2.0.0/gems`, but it's not what I want, so I press up arrow and execute `z gems` again, it will take me to `/Users/Great_Wall/.rbenv/versions/2.4.1/lib/ruby/gems` and this what I want. + + Of course, I can always use `z env gems` to indicate what I want precisely. Skip the current directory means when you use `z xxx` you always want to change directory instead of stay in the same directory and do nothing if current directory is the best match. + +The default matching method is designed to be compatible with original z.sh, but the enhanced matching method is much more handy and exclusive to z.lua. + + +## Add Once + +By default, z.lua will add current directory to database each time before display command prompt (correspond with z.sh). But there is an option to allow z.lua add path only if current working directory changed. + +To enable this, you can set `$_ZL_ADD_ONCE` to `1` before init z.lua. Or you can initialize z.lua on linux like this: + +````bash +eval "$(lua /path/to/z.lua --init bash once)" +eval "$(lua /path/to/z.lua --init zsh once)" +lua /path/to/z.lua --init fish once | source +```` + +With `add once` mode off (default), z.lua will consider the time you spent in the directory (like z.sh). When this mode is on, consider the times you accessed the directory (like autojump), and that could be much faster on slow hardware. + + +## Interactive Selection + +When there are multiple matches found, using `z -i` will display a list: + +```bash +$ z -i soft +3: 0.25 /home/data/software +2: 3.75 /home/skywind/tmp/comma/software +1: 21 /home/skywind/software +> {CURSOR} +``` + +And then you can input the number and choose where to go before actual cd. eg. input 3 to cd to `/home/data/software`. And if you just press ENTER and input nothing, it will just quit and stay where you were. + +NOTE: for fish shell, this feature requires fish 2.7.0 or above. + + +## FZF Supports + +From version 1.1.0, a new option `"-I"` will allow you to use fzf to select when there are multiple matches. + +![](images/fzf.png) + +When we use `"z -I vim"`,12 paths contains keyword "vim" has been matched and ordered by their frecent value, the higher frecent comes with the higher rank. Then without cd to the highest ranked path, z.lua passes all the candidates to fzf. + +Now you can input some space separated keywords (no order required) or use `CTRL+J`/`CTRL+K` (same as `UP`/`DOWN`) to select where you want to go, or `ESC` / `CTRL`+`D`/`G` to give up. + +Of course, you can always give more keywords to `z` command to match your destination precisely. `"z -I"` is similar to `"z -i"`, but use fzf. Both `"-i"` and `"-I"` provide you another way for path navigation. + +Usually, `z -I` can be aliased to `zf` (z + fuzzy finder) for convenience. If there are only one path matched, `z -I` will jump to it directly, fzf will only be invoked for multiple matches. `"z -I ."` or `"zf ."` can be used to use fzf select from entire database. + +For more information about this, please visit [wiki - effective with fzf](https://github.com/skywind3000/z.lua/wiki/Effective-with-fzf). + +NOTE: For fish shell, this feature requires fish 2.7.0 or above. You can specify fzf executable in `$_ZL_FZF` environment variable, `"fzf"` will be called by default. + + +## Jump Backwards + +New option `"-b"` can quickly go back to a specific parent directory in bash instead of typing "cd ../../.." redundantly. + +- **(No argument)**: `cd` into the project root, the project root the nearest parent directory with `.git`/`.hg`/`.svn` in it. +- **(One argument)**: `cd` into the closest parent starting with keyword, if not find, go to the parent containing keyword. +- **(Two arguments)**: replace the first value with the second one (in the current path). + If simple substitution does not work, falls back to fuzzily replacing path components. + +Let's start by aliasing `z -b` to `zb`: + +```bash +# go all the way up to the project root (in this case, the one that has .git in it) +~/github/lorem/src/public$ zb + => cd ~/github/lorem + +# cd into to the first parent directory named g* +~/github/vimium/src/public$ zb g + => cd ~/github + +# goto the site directory quickly +~/github/demo/src/org/main/site/utils/file/reader/whatever$ zb si + => cd ~/github/demo/src/org/main/site + +# substitute jekyll with ghost +~/github/jekyll/test$ zb jekyll ghost + => cd ~/github/ghost/test + +# same as above, but fuzzy +~/github/jekyll/test$ zb jek gh + => z ~/github/ gh /test + => cd ~/github/ghost/test # Assuming that's the most frecent match +``` + +Backward jumping can also be used with `$_ZL_ECHO` option (echo $PWD after cd), which makes it possible to combine them with other tools without actually changing the working directory (eg. ``ls `zb git` ``). + +Environment variable `$_ZL_ROOT_MARKERS` is a comma separated list for project root locating, and can be redefined as: + +```bash +export _ZL_ROOT_MARKERS=".git,.svn,.hg,.root,package.json" +``` + +If you want `zb` jump back to a parent directory contains a `.root` or `package.json` in it. + +**Bonus**: `zb ..` equals to `cd ..`, `zb ...` equals to `cd ../..` and `zb ....` equals to `cd ../../..`, and so on. Finally, `zb ..20` equals to `cd (..)x20`. + +**Bonus**: try `z -b -i` and `z -b -I` and you can alias them to `zbi` and `zbf`. + +## Completion + +For zsh/fish, completion can be triggered by `z foo`. and a list of candidates will display in zsh / fish: + +![](images/complete-1.png) + +Press `` again, you can select your destination in a visualized way. + +Bash is not as powerful as zsh/fish, so we introduced fzf-completion for bash, initialize your z.lua and append `fzf` keyword after `--init`: + +```bash +eval "$(lua /path/to/z.lua --init bash enhanced once echo fzf)" +``` + +If you want use fzf completion in zsh, initalize your z.lua and append `fzf` keyword after `--init`: + +```zsh +eval "$(lua /path/to/z.lua --init zsh enhanced once echo fzf)" +``` + +Then press `` after `z xxx`: + +![](images/complete-2.png) + +With the help of fzf, completion in bash is much easier now. + +`z.lua` can cooperate with [fz](https://github.com/changyuheng/fz) for **better completion** result in both bash and zsh, for more information see [FAQ](https://github.com/skywind3000/z.lua/wiki/FAQ#fzsh-for-better-completion). + +NOTE: To enable this, command `fzf` must be found in `$PATH` before initialization. + + +## Most Recently Accessed Path + +`z.lua` provides a fast way to visit MRU directories without typing any keyword. That is `dirstack`, which records recently visited paths and can be manipulated by `z -`, `z --` and `z -{num}`: + +```bash +# display current dir stack +$ z -- + 0 /home/skywind/work/match/memory-match + 1 /home/skywind/.local/etc + 2 /home/skywind/software/vifm-0.9.1 + 3 /home/skywind/work + 4 /home/skywind/work/match + +# cd to the 2nd directory in the stack +$ z -2 + => cd /home/skywind/software/vifm-0.9.1 + +# popup stacktop (cd to previous directory), same as "z -0" +$ z - + => cd - +``` + +The `dirstack` is calculated from z.lua's database, and has no dependency on shells or systems. You will not lost records after re-login, and history can be shared across shells and sessions. + +There is another way to access MRU directories interactively by utilizing parameter `-I` (fzf) and `-t` (sort by time): + +```bash +alias zh='z -I -t .' +``` + +The new alias `zh` (jump to history) is very easy to input: + +![](images/mru.png) + +The first column indicates how many seconds ago you have visited, and the second column is the path name. With `zh`, you can type some character to use string matching in fzf, or use ``/`` (as well as `CTRL+j/k`) to move the selector (red `>`) up and down. + +At last, press `` to accept or `` to give up. + +Remember to enable the [enhanced matching](#enhanced-matching) algorithm, the current working directory can be skipped with it. + + +## Ranger integration +To add a `:z` command to the [`ranger` file manager], copy the `ranger_zlua.py` file to `~/.config/ranger/plugins/`. +You can then use `:z foo`, `:z -b foo`, etc. from ranger. Use `:z -h` for help. + +[`ranger` file manager]: https://github.com/ranger/ranger + +To define additional commands (`:zb` for example) in ranger, you can put `alias zb z -b` into `~/.config/ranger/rc.conf`. + + +## Tips + +Recommended aliases you may find useful: + +```bash +alias zz='z -c' # restrict matches to subdirs of $PWD +alias zi='z -i' # cd with interactive selection +alias zf='z -I' # use fzf to select in multiple matches +alias zb='z -b' # quickly cd to the parent directory +``` + +Import data from z.sh: + + +```bash +cat ~/.z >> ~/.zlua +``` + +Import data from autojump: + +```bash +FN="$HOME/.local/share/autojump/autojump.txt" +awk -F '\t' '{print $2 "|" $1 "|" 0}' $FN >> ~/.zlua +``` + +Don't forget to read the [Frequently Asked Questions](https://github.com/skywind3000/z.lua/wiki/FAQ). + + +## Benchmark + +The slowest part is adding path to history data file. It will run every time when you press enter (installed in $PROMPT_COMMAND). So I profile it on my NAS: + +```bash +$ time autojump --add /tmp +real 0m0.352s +user 0m0.077s +sys 0m0.185s + +$ time fasd -A /tmp +real 0m0.618s +user 0m0.076s +sys 0m0.242s + +$ time _z --add /tmp +real 0m0.194s +user 0m0.046s +sys 0m0.154s + +$ time _zlua --add /tmp +real 0m0.052s +user 0m0.015s +sys 0m0.030s +``` + +As you see, z.lua is the fastest one and requires less resource. + +## Native Module + +z.lua is fast enough for most case, the path tracking action will be triggered each time when you change your current directory. + +So I still recommend the pure lua script for portability and flexibility, but for someone who really care about `10ms` or `1ms` things, this module can help them to gain the ultimate speed. + +- [czmod](https://github.com/skywind3000/czmod): native module to boost `z.lua`. + +Average performance: + +| Name | czmod | z.lua | +|-|-|-| +| **Update Time** | 1.6ms | 13.2ms | +| **Query Time** | 1.5ms | 9.8ms | + + + +## History + +- 1.8.7 (2020-06-29): use lfs or luajit's cffi if possible. +- 1.8.4 (2020-02-10): fish shell: set `$_ZL_ECHO` to global scope. +- 1.8.3 (2020-02-09): new: `z -b -i` and `z -b -I` to jump backwards in interactive mode. +- 1.7.4 (2019-12-29): new: `$_ZL_HYPHEN` to treat hyphen as a normal character, see [here](https://github.com/skywind3000/z.lua/wiki/FAQ#how-to-input-a-hyphen---in-the-keyword-). +- 1.7.3 (2019-09-07): use [lua-filesystem](http://keplerproject.github.io/luafilesystem/) package if possible when `$_ZL_USE_LFS` is `1`. +- 1.7.2 (2019-08-01): Improve bash/zsh shell compatibility by [@barlik](https://github.com/barlik). +- 1.7.1 (2019-06-07): Fixed: `$_ZL_DATA` failure on Linux sometimes. +- 1.7.0 (2019-03-09): Support [ranger](https://github.com/skywind3000/z.lua/wiki/FAQ#how-to-integrate-zlua-to-ranger-), fix ReplaceFile issue in luajit (windows). +- 1.6.0 (2019-03-04): optimize with ffi module (luajit builtin module). +- 1.5.11 (2019-03-02): fixed: os.path.isdir doesn't work for symbol link folders. +- 1.5.10 (2019-03-01): Prevent writing file racing. +- 1.5.9 (2019-02-25): `z -b` should not match current directory (close #56). +- 1.5.8 (2019-02-21): new `$_ZL_FZF_HEIGHT` to control `--height` parameter in fzf. +- 1.5.7 (2019-02-21): rename `$_ZL_FZF_SORT` to `$_ZL_INT_SORT` it will affect both `-i` and `-I`. +- 1.5.6 (2019-02-20): set `$_ZL_FZF_SORT` to 1 to sort directories by alphabet in fzf. +- 1.5.5 (2019-02-20): `$_ZL_FZF_FLAG` can be used to override fzf flags, default to "+s -e". +- 1.5.4 (2019-02-19): fixed: file/path existence detection fails on read-only fs (closed [#49](https://github.com/skywind3000/z.lua/issues/49) by [@contrun](https://github.com/contrun)). +- 1.5.3 (2019-02-17): new `$_ZL_FZF_FLAG` for passing additional flags to fzf, add `-e` argument to fzf. +- 1.5.2 (2019-02-16): be aware of all arguments in fzf completion. +- 1.5.1 (2019-02-15): new: simulated dir stack by `z -`, `z --` and `z -{num}`. +- 1.5.0 (2019-02-14): fixed minor issues in backward jumping. +- 1.4.7 (2019-02-13): Don't use regex in backward jumping (use plain text instead). +- 1.4.6 (2019-02-12): change: `_ZL_EXCLUDE_DIRS` to a comma separated list of dirs to exclude. +- 1.4.5 (2019-02-10): improve bash fzf completion and posix compatibility. +- 1.4.4 (2019-02-10): supports legacy posix shells like ksh, init with `z.lua --init posix legacy`. +- 1.4.3 (2019-02-08): fixed minor issues. +- 1.4.2 (2019-02-06): you can disabled path validation by `$_ZL_NO_CHECK`, and use `z --purge` to clear bad paths manually. +- 1.4.1 (2019-02-06): fzf tab-completion in bash ([@BarbUk](https://github.com/BarbUk)), fixed hang in fish shell (close [#29](https://github.com/skywind3000/z.lua/issues/29)). +- 1.4.0 (2019-02-04): Ported to Power Shell ([@manhong2112](https://github.com/manhong2112)) +- 1.3.0 (2019-02-04): Backward jumping, prevent "cd ../../.." repeatly. +- 1.2.0 (2019-02-03): Upgrade string lib and path lib. +- 1.1.0 (2019-02-02): New option '-I' to use fzf to select from multiple matches. +- 1.0.0 (2019-02-01): Fixed minor issues and make it stable. +- 0.5.0 (2019-01-21): Ported to Fish Shell ([@TeddyDD](https://github.com/TeddyDD)). +- 0.4.1 (2019-01-20): Don't return failed exit code when $_ZL_ECHO is unbind (Mario Rodas). +- 0.4.0 (2019-01-17): new enhanced matching algorithm,can be enabled by appending `enhanced` keyword after `--init`. +- 0.3.0 (2018-12-26): new option `-i` to enable interactive selection. +- 0.2.0 (2018-11-25): new option `$_ZL_ADD_ONCE` to enable updating datafile only if `$PWD` changed. +- 0.1.0 (2018-04-30): supports windows cmd, cmder and conemu. +- 0.0.0 (2018-03-21): initial commit, compatible with original z.sh. + +## Help + +This project needs help for the tasks below: + +- [ ] Support csh/tcsh. +- [ ] Completion: Actually I got little knowledge in completion, and need help to improve it. +- [ ] Completion: Implement completion for Power Shell. +- [ ] Completion: Implement completion for different arguments. +- [ ] Packaging: make it possible to be installed easily in different systems or popular plugin managers. + + +## Thanks + +- Thanks to [@rupa](https://github.com/rupa) for inspiring me to start this project. +- Thanks to [@vigneshwaranr](https://github.com/vigneshwaranr) and [@shyiko](https://github.com/shyiko) for inspiring me the backward jumping. +- Thanks to [@TeddyDD](https://github.com/TeddyDD) for Fish Shell porting. +- Thanks to [@manhong2112](https://github.com/manhong2112) for Power Shell porting. +- Thanks to [@BarbUk](https://github.com/BarbUk) for fzf completion in Bash. +- Thanks to [@barlik](https://github.com/barlik) for many improvements. + +And many others. + + + +## License + +Licensed under MIT license. + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/complete-1.png b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/complete-1.png new file mode 100644 index 00000000..dbffc105 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/complete-1.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/complete-2.png b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/complete-2.png new file mode 100644 index 00000000..e4ba4216 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/complete-2.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/fzf.png b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/fzf.png new file mode 100644 index 00000000..43e68b1f Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/fzf.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/mru.png b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/mru.png new file mode 100644 index 00000000..2e46d3ce Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/mru.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/step1.png b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/step1.png new file mode 100644 index 00000000..23229ee6 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/step1.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/step2.png b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/step2.png new file mode 100644 index 00000000..9e39cf53 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/step2.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/step3.png b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/step3.png new file mode 100644 index 00000000..656c5d8e Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/step3.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/step4.png b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/step4.png new file mode 100644 index 00000000..033a5033 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/images/step4.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/init.fish b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/init.fish new file mode 100644 index 00000000..cb2f5ad8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/init.fish @@ -0,0 +1,52 @@ +#! /usr/bin/env fish + +if test -z "$XDG_DATA_HOME" + set -U _ZL_DATA_DIR "$HOME/.local/share/zlua" +else + set -U _ZL_DATA_DIR "$XDG_DATA_HOME/zlua" +end + +set -x _ZL_DATA "$_ZL_DATA_DIR/zlua.txt" 2> /dev/null +set -U _ZL_DATA "$_ZL_DATA_DIR/zlua.txt" 2> /dev/null + +if test ! -e "$_ZL_DATA" + if test ! -e "$_ZL_DATA_DIR" + mkdir -p -m 700 "$_ZL_DATA_DIR" 2> /dev/null + end +end + +set -x _ZL_DATA "$_ZL_DATA" + +set -q XDG_DATA_HOME; or set XDG_DATA_HOME ~/.local/share +if functions -q fisher + set _zlua_dir $XDG_DATA_HOME/fisher/github.com/skywind3000/z.lua +else + set _zlua_dir (dirname (status --current-filename)) +end + +if test -e $_zlua_dir/z.lua + if type -q lua + lua $_zlua_dir/z.lua --init fish enhanced once echo | source + else if type -q luajit + luajit $_zlua_dir/z.lua --init fish enhanced once echo | source + else if type -q lua5.3 + lua5.3 $_zlua_dir/z.lua --init fish enhanced once echo | source + else if type -q lua5.2 + lua5.2 $_zlua_dir/z.lua --init fish enhanced once echo | source + else if type -q lua5.1 + lua5.1 $_zlua_dir/z.lua --init fish enhanced once echo | source + else + echo "init z.lua failed, not find lua in your system" + end + alias zc='z -c' # restrict matches to subdirs of $PWD + alias zz='z -i' # cd with interactive selection + alias zf='z -I' # use fzf to select in multiple matches + alias zb='z -b' # quickly cd to the parent directory + alias zbi='z -b -i' # interactive jump backward + alias zbf='z -b -I' # interactive jump backward with fzf + set -U ZLUA_SCRIPT "$ZLUA_SCRIPT" 2> /dev/null + set -U ZLUA_LUAEXE "$ZLUA_LUAEXE" 2> /dev/null +end + + + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/ranger_zlua.py b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/ranger_zlua.py new file mode 100644 index 00000000..67389fcf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/ranger_zlua.py @@ -0,0 +1,91 @@ +import time, sys, os +import ranger.api +import subprocess + +# $RANGER_LUA and $RANGER_ZLUA variables are deprecated, do not use them. +ZLUA_LUAEXE = os.environ.get('RANGER_LUA') or os.environ.get('ZLUA_LUAEXE') +ZLUA_SCRIPT = os.environ.get('RANGER_ZLUA') or os.environ.get('ZLUA_SCRIPT') + +if not ZLUA_LUAEXE: + for path in os.environ.get('PATH', '').split(os.path.pathsep): + for name in ('lua', 'luajit', 'lua5.3', 'lua5.2', 'lua5.1'): + test = os.path.join(path, name) + test = test + (sys.platform[:3] == 'win' and ".exe" or "") + if os.path.exists(test): + ZLUA_LUAEXE = test + break + +def _report_error(msg): + sys.stderr.write('ranger_zlua: ' + msg) + raise RuntimeError(msg) + +if not ZLUA_LUAEXE: + _report_error('Please install lua in $PATH or make sure $ZLUA_LUAEXE points to a lua executable.\n') +if (not ZLUA_SCRIPT) or (not os.path.exists(ZLUA_SCRIPT)): + _report_error('Could not find z.lua, please make sure $ZLUA_SCRIPT is set to absolute path of z.lua.\n') + + +# Inform z.lua about directories the user browses to inside ranger +old_hook_init = ranger.api.hook_init + +def hook_init(fm): + def update_zlua(signal): + import os, random + os.environ['_ZL_RANDOM'] = str(random.randint(0, 0x7fffffff)) + p = subprocess.Popen([ZLUA_LUAEXE, ZLUA_SCRIPT, "--add", signal.new.path]) + p.wait() + if ZLUA_SCRIPT and ZLUA_LUAEXE and os.path.exists(ZLUA_SCRIPT): + fm.signal_bind('cd', update_zlua) + return old_hook_init(fm) + +ranger.api.hook_init = hook_init + + +class z(ranger.api.commands.Command): + def execute (self): + import sys, os, time + args = self.args[1:] + if args: + mode = '' + for arg in args: + if arg in ('-l', '-e', '-x', '-h', '--help', '--'): + mode = arg + break + elif arg in ('-I', '-i'): + mode = arg + elif arg[:1] != '-': + break + if mode: + cmd = '"%s" "%s" '%(ZLUA_LUAEXE, ZLUA_SCRIPT) + if mode in ('-I', '-i', '--'): + cmd += ' --cd' + for arg in args: + cmd += ' "%s"'%arg + if mode in ('-e', '-x'): + path = subprocess.check_output([ZLUA_LUAEXE, ZLUA_SCRIPT, '--cd'] + args) + path = path.decode("utf-8", "ignore") + path = path.rstrip('\n') + self.fm.notify(path) + elif mode in ('-h', '-l', '--help'): + p = self.fm.execute_command(cmd + '| less +G', universal_newlines=True) + stdout, stderr = p.communicate() + elif mode == '--': + p = self.fm.execute_command(cmd + ' 2>&1 | less +G', universal_newlines=True) + stdout, stderr = p.communicate() + else: + p = self.fm.execute_command(cmd, universal_newlines=True, stdout=subprocess.PIPE) + stdout, stderr = p.communicate() + path = stdout.rstrip('\n') + self.fm.execute_console('redraw_window') + if path and os.path.exists(path): + self.fm.cd(path) + else: + path = subprocess.check_output([ZLUA_LUAEXE, ZLUA_SCRIPT, '--cd'] + args) + path = path.decode("utf-8", "ignore") + path = path.rstrip('\n') + if path and os.path.exists(path): + self.fm.cd(path) + else: + self.fm.notify('No matching found', bad = True) + return True + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/test_path.lua.rename b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/test_path.lua.rename new file mode 100644 index 00000000..2465ffbd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/test_path.lua.rename @@ -0,0 +1,193 @@ +local zmod = require('z') +local windows = os.path.sep == '\\' + +----------------------------------------------------------------------- +-- logo +----------------------------------------------------------------------- +function print_title(text) + print(string.rep('-', 72)) + print('-- '.. text) + print(string.rep('-', 72)) +end + + +----------------------------------------------------------------------- +-- os.path.normpath +----------------------------------------------------------------------- +print_title('os.path.normpath') + +function assert_posix(path, result) + local x = os.path.normpath(path) + print('[test] normpath: ('..path..') -> (' .. result .. ')') + if x:gsub('\\', '/') ~= result then + print('failed: "' .. x .. '" != "'..result.. '"') + os.exit() + else + print('passed') + print() + end +end + +function assert_windows(path, result) + local x = os.path.normpath(path) + print('[test] normpath: ('..path..') -> (' .. result .. ')') + if x ~= result then + print('failed: "' .. x .. '" != "'..result.. '"') + os.exit() + else + print('passed') + print() + end +end + +assert_posix("", ".") +assert_posix("/", "/") +assert_posix("///", "/") +assert_posix("///foo/.//bar//", "/foo/bar") +assert_posix("///foo/.//bar//.//..//.//baz", "/foo/baz") +assert_posix("///..//./foo/.//bar", "/foo/bar") + +if windows then + assert_windows('A//////././//.//B', 'A\\B') + assert_windows('A/./B', 'A\\B') + assert_windows('A/foo/../B', 'A\\B') + assert_windows('C:A//B', 'C:A\\B') + assert_windows('D:A/./B', 'D:A\\B') + assert_windows('e:A/foo/../B', 'e:A\\B') + assert_windows('C:///A//B', 'C:\\A\\B') + assert_windows('D:///A/./B', 'D:\\A\\B') + assert_windows('e:///A/foo/../B', 'e:\\A\\B') + assert_windows('..', '..') + assert_windows('.', '.') + assert_windows('', '.') + assert_windows('/', '\\') + assert_windows('c:/', 'c:\\') + assert_windows('/../.././..', '\\') + assert_windows('c:/../../..', 'c:\\') + assert_windows('../.././..', '..\\..\\..') + assert_windows('K:../.././..', 'K:..\\..\\..') + assert_windows('C:////a/b', 'C:\\a\\b') +end + +print() + + +----------------------------------------------------------------------- +-- os.path.join +----------------------------------------------------------------------- +print_title('os.path.join') + +function assert_join_posix(segments, result, isnt) + print('[test] join: '..zmod.dump(segments)..' -> (' .. result .. ')') + local path = '' + for _, item in ipairs(segments) do + path = os.path.join(path, item) + end + if windows and (not isnt) then + path = path:gsub('\\', '/') + end + if path ~= result then + print('failed: "' .. path .. '"') + os.exit() + else + print('passed') + end +end + +function assert_join_windows(segments, result) + assert_join_posix(segments, result, 1) +end + +assert_join_posix({"/foo", "bar", "/bar", "baz"}, "/bar/baz") +assert_join_posix({"/foo", "bar", "baz"}, "/foo/bar/baz") +assert_join_posix({"/foo/", "bar/", "baz/"}, "/foo/bar/baz/") + +if windows then + assert_join_windows({""}, '') + assert_join_windows({"", "", ""}, '') + assert_join_windows({"a"}, 'a') + assert_join_windows({"/a"}, '/a') + assert_join_windows({"\\a"}, '\\a') + assert_join_windows({"a:"}, 'a:') + assert_join_windows({"a:", "\\b"}, 'a:\\b') + assert_join_windows({"a", "\\b"}, '\\b') + assert_join_windows({"a", "b", "c"}, 'a\\b\\c') + assert_join_windows({"a\\", "b", "c"}, 'a\\b\\c') + assert_join_windows({"a", "b\\", "c"}, 'a\\b\\c') + assert_join_windows({"a", "b", "\\c"}, '\\c') + assert_join_windows({"d:\\", "\\pleep"}, 'd:\\pleep') + assert_join_windows({"d:\\", "a", "b"}, 'd:\\a\\b') + + assert_join_windows({'', 'a'}, 'a') + assert_join_windows({'', '', '', '', 'a'}, 'a') + assert_join_windows({'a', ''}, 'a\\') + assert_join_windows({'a', '', '', '', ''}, 'a\\') + assert_join_windows({'a\\', ''}, 'a\\') + assert_join_windows({'a\\', '', '', '', ''}, 'a\\') + assert_join_windows({'a/', ''}, 'a/') + + assert_join_windows({'a/b', 'x/y'}, 'a/b\\x/y') + assert_join_windows({'/a/b', 'x/y'}, '/a/b\\x/y') + assert_join_windows({'/a/b/', 'x/y'}, '/a/b/x/y') + assert_join_windows({'c:', 'x/y'}, 'c:x/y') + assert_join_windows({'c:a/b', 'x/y'}, 'c:a/b\\x/y') + assert_join_windows({'c:a/b/', 'x/y'}, 'c:a/b/x/y') + assert_join_windows({'c:/', 'x/y'}, 'c:/x/y') + assert_join_windows({'c:/a/b', 'x/y'}, 'c:/a/b\\x/y') + assert_join_windows({'c:/a/b/', 'x/y'}, 'c:/a/b/x/y') + + assert_join_windows({'a/b', '/x/y'}, '/x/y') + assert_join_windows({'/a/b', '/x/y'}, '/x/y') + assert_join_windows({'c:', '/x/y'}, 'c:/x/y') + assert_join_windows({'c:a/b', '/x/y'}, 'c:/x/y') + assert_join_windows({'c:/', '/x/y'}, 'c:/x/y') + assert_join_windows({'c:/a/b', '/x/y'}, 'c:/x/y') + + assert_join_windows({'c:', 'C:x/y'}, 'C:x/y') + assert_join_windows({'c:a/b', 'C:x/y'}, 'C:a/b\\x/y') + assert_join_windows({'c:/', 'C:x/y'}, 'C:/x/y') + assert_join_windows({'c:/a/b', 'C:x/y'}, 'C:/a/b\\x/y') + + for _, x in ipairs({'', 'a/b', '/a/b', 'c:', 'c:a/b', 'c:/', 'c:/a/b'}) do + for _, y in ipairs({'d:', 'd:x/y', 'd:/', 'd:/x/y'}) do + assert_join_windows({x, y}, y) + end + end +end + +print() + + +----------------------------------------------------------------------- +-- os.path.split +----------------------------------------------------------------------- +print_title('os.path.split') +function assert_split(path, sep1, sep2) + print('[test] split: "' .. path ..'" -> ("' .. sep1 .. '", "' .. sep2 .. '")') + local x, y = os.path.split(path) + if x ~= sep1 or y ~= sep2 then + print('failed: ("'..x..'", "'..y..'")') + os.exit() + else + print('passed') + end +end + +assert_split("", "", "") +assert_split(".", "", ".") +assert_split("/foo/bar", "/foo", "bar") +assert_split("/", "/", "") +assert_split("foo", "", "foo") +assert_split("////foo", "////", "foo") +assert_split("//foo//bar", "//foo", "bar") + +if windows then + assert_split("c:\\foo\\bar", 'c:\\foo', 'bar') + assert_split("\\\\conky\\mountpoint\\foo\\bar", '\\\\conky\\mountpoint\\foo', 'bar') + assert_split("c:\\", "c:\\", '') + assert_split("c:/", "c:/", '') + assert_split("c:test", "c:", 'test') + assert_split("c:", "c:", '') + -- assert_split("\\\\conky\\mountpoint\\", "\\\\conky\\mountpoint\\", '') +end + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/z.cmd b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/z.cmd new file mode 100644 index 00000000..f821238a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/z.cmd @@ -0,0 +1,130 @@ +@echo off +setlocal EnableDelayedExpansion + +set "LuaExe=lua" +set "LuaScript=%~dp0z.lua" +set "MatchType=-n" +set "StrictSub=-n" +set "RunMode=-n" +set "StripMode=" +set "InterMode=" + +if /i not "%_ZL_LUA_EXE%"=="" ( + set "LuaExe=%_ZL_LUA_EXE%" +) + + +:parse + +if /i "%1"=="-r" ( + set "MatchType=-r" + shift /1 + goto parse +) + +if /i "%1"=="-t" ( + set "MatchType=-t" + shift /1 + goto parse +) + +if /i "%1"=="-c" ( + set "StrictSub=-c" + shift /1 + goto parse +) + +if /i "%1"=="-l" ( + set "RunMode=-l" + shift /1 + goto parse +) + +if /i "%1"=="-e" ( + set "RunMode=-e" + shift /1 + goto parse +) + +if /i "%1"=="-x" ( + set "RunMode=-x" + shift /1 + goto parse +) + +if /i "%1"=="--add" ( + set "RunMode=--add" + shift /1 + goto parse +) + +if "%1"=="-i" ( + set "InterMode=-i" + shift /1 + goto parse +) + +if "%1"=="-I" ( + set "InterMode=-I" + shift /1 + goto parse +) + +if /i "%1"=="-s" ( + set "StripMode=-s" + shift /1 + goto parse +) + +if /i "%1"=="-h" ( + call "%LuaExe%" "%LuaScript%" -h + goto end +) + +if /i "%1"=="--purge" ( + call "%LuaExe%" "%LuaScript%" --purge + goto end +) + +:check + +if /i "%1"=="" ( + set "RunMode=-l" +) + +for /f "delims=" %%i in ('cd') do set "PWD=%%i" + +if /i "%RunMode%"=="-n" ( + for /f "delims=" %%i in ('call "%LuaExe%" "%LuaScript%" --cd %MatchType% %StrictSub% %InterMode% %*') do set "NewPath=%%i" + if not "!NewPath!"=="" ( + if exist !NewPath!\nul ( + if /i not "%_ZL_ECHO%"=="" ( + echo !NewPath! + ) + pushd !NewPath! + pushd !NewPath! + endlocal + goto popdir + ) + ) +) else ( + call "%LuaExe%" "%LuaScript%" "%RunMode%" %MatchType% %StrictSub% %InterMode% %StripMode% %* +) + +goto end + +:popdir +rem -- Exploits variable expansion and the pushd stack to set the current +rem -- directory without leaking a pushd. +popd +setlocal +set "NewPath=%CD%" +set "CDCmd=cd /d" +if /i not "%_ZL_CD%"=="" ( + set "CDCmd=%_ZL_CD%" +) +endlocal & popd & %CDCmd% "%NewPath%" + +:end +echo. + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/z.lua b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/z.lua new file mode 100755 index 00000000..1897a213 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/z.lua @@ -0,0 +1,2831 @@ +#! /usr/bin/env lua +--===================================================================== +-- +-- z.lua - a cd command that learns, by skywind 2018-2022 +-- Licensed under MIT license. +-- +-- Version 1.8.17, Last Modified: 2022/09/29 15:47 +-- +-- * 10x faster than fasd and autojump, 3x faster than z.sh +-- * available for posix shells: bash, zsh, sh, ash, dash, busybox +-- * available for fish shell, power shell and windows cmd +-- * compatible with lua 5.1, 5.2 and 5.3+ +-- +-- USE: +-- * z foo # cd to most frecent dir matching foo +-- * z foo bar # cd to most frecent dir matching foo and bar +-- * z -r foo # cd to highest ranked dir matching foo +-- * z -t foo # cd to most recently accessed dir matching foo +-- * z -l foo # list matches instead of cd +-- * z -c foo # restrict matches to subdirs of $PWD +-- * z -e foo # echo the best match, don't cd +-- * z -x path # remove path from history +-- * z -i foo # cd with interactive selection +-- * z -I foo # cd with interactive selection using fzf +-- * z -b foo # cd to the parent directory starting with foo +-- * z -b foo bar # replace foo with bar in cwd and cd there +-- +-- Bash Install: +-- * put something like this in your .bashrc: +-- eval "$(lua /path/to/z.lua --init bash)" +-- +-- Bash Enhanced Mode: +-- * put something like this in your .bashrc: +-- eval "$(lua /path/to/z.lua --init bash enhanced)" +-- +-- Bash fzf tab completion Mode: +-- * put something like this in your .bashrc: +-- eval "$(lua /path/to/z.lua --init bash fzf)" +-- +-- Zsh Install: +-- * put something like this in your .zshrc: +-- eval "$(lua /path/to/z.lua --init zsh)" +-- +-- Posix Shell Install: +-- * put something like this in your .profile: +-- eval "$(lua /path/to/z.lua --init posix)" +-- +-- Fish Shell Install: +-- * put something like this in your config file: +-- lua /path/to/z.lua --init fish | source +-- +-- Power Shell Install: +-- * put something like this in your config file: +-- Invoke-Expression (& { +-- (lua /path/to/z.lua --init powershell) -join "`n" }) +-- +-- Windows Install (with Clink): +-- * copy z.lua and z.cmd to clink's home directory +-- * Add clink's home to %PATH% (z.cmd can be called anywhere) +-- * Ensure that "lua" can be called in %PATH% +-- +-- Windows Cmder Install: +-- * copy z.lua and z.cmd to cmder/vendor +-- * Add cmder/vendor to %PATH% +-- * Ensure that "lua" can be called in %PATH% +-- +-- Windows WSL-1: +-- * Install lua-filesystem module before init z.lua: +-- sudo apt-get install lua-filesystem +-- +-- Configure (optional): +-- set $_ZL_CMD in .bashrc/.zshrc to change the command (default z). +-- set $_ZL_DATA in .bashrc/.zshrc to change the datafile (default ~/.zlua). +-- set $_ZL_NO_PROMPT_COMMAND if you're handling PROMPT_COMMAND yourself. +-- set $_ZL_EXCLUDE_DIRS to a comma separated list of dirs to exclude. +-- set $_ZL_ADD_ONCE to 1 to update database only if $PWD changed. +-- set $_ZL_CD to specify your own cd command +-- set $_ZL_ECHO to 1 to display new directory name after cd. +-- set $_ZL_MAXAGE to define a aging threshold (default is 5000). +-- set $_ZL_MATCH_MODE to 1 to enable enhanced matching mode. +-- set $_ZL_NO_CHECK to 1 to disable path validation. z --purge to clear. +-- set $_ZL_USE_LFS to 1 to use lua-filesystem package +-- set $_ZL_HYPHEN to 1 to stop treating hyphen as a regexp keyword +-- +--===================================================================== + + +----------------------------------------------------------------------- +-- Module Header +----------------------------------------------------------------------- +local modname = 'z' +local MM = {} +_G[modname] = MM +package.loaded[modname] = MM --return modname +setmetatable(MM, {__index = _G}) + +if _ENV ~= nil then + _ENV[modname] = MM +else + setfenv(1, MM) +end + + +----------------------------------------------------------------------- +-- Environment +----------------------------------------------------------------------- +local windows = package.config:sub(1, 1) ~= '/' and true or false +local in_module = pcall(debug.getlocal, 4, 1) and true or false +local utils = {} +os.path = {} +os.argv = arg ~= nil and arg or {} +os.path.sep = windows and '\\' or '/' + + +----------------------------------------------------------------------- +-- Global Variable +----------------------------------------------------------------------- +MAX_AGE = 5000 +DATA_FILE = '~/.zlua' +PRINT_MODE = '' +PWD = '' +Z_METHOD = 'frecent' +Z_SUBDIR = false +Z_INTERACTIVE = 0 +Z_EXCLUDE = {} +Z_CMD = 'z' +Z_MATCHMODE = 0 +Z_MATCHNAME = false +Z_SKIPPWD = false +Z_HYPHEN = false + +os.LOG_NAME = os.getenv('_ZL_LOG_NAME') + + +----------------------------------------------------------------------- +-- string lib +----------------------------------------------------------------------- +function string:split(sSeparator, nMax, bRegexp) + assert(sSeparator ~= '') + assert(nMax == nil or nMax >= 1) + local aRecord = {} + if self:len() > 0 then + local bPlain = not bRegexp + nMax = nMax or -1 + local nField, nStart = 1, 1 + local nFirst, nLast = self:find(sSeparator, nStart, bPlain) + while nFirst and nMax ~= 0 do + aRecord[nField] = self:sub(nStart, nFirst - 1) + nField = nField + 1 + nStart = nLast + 1 + nFirst, nLast = self:find(sSeparator, nStart, bPlain) + nMax = nMax - 1 + end + aRecord[nField] = self:sub(nStart) + else + aRecord[1] = '' + end + return aRecord +end + +function string:startswith(text) + local size = text:len() + if self:sub(1, size) == text then + return true + end + return false +end + +function string:endswith(text) + return text == "" or self:sub(-#text) == text +end + +function string:lstrip() + if self == nil then return nil end + local s = self:gsub('^%s+', '') + return s +end + +function string:rstrip() + if self == nil then return nil end + local s = self:gsub('%s+$', '') + return s +end + +function string:strip() + return self:lstrip():rstrip() +end + +function string:rfind(key) + if key == '' then + return self:len(), 0 + end + local length = self:len() + local start, ends = self:reverse():find(key:reverse(), 1, true) + if start == nil then + return nil + end + return (length - ends + 1), (length - start + 1) +end + +function string:join(parts) + if parts == nil or #parts == 0 then + return '' + end + local size = #parts + local text = '' + local index = 1 + while index <= size do + if index == 1 then + text = text .. parts[index] + else + text = text .. self .. parts[index] + end + index = index + 1 + end + return text +end + + +----------------------------------------------------------------------- +-- table size +----------------------------------------------------------------------- +function table.length(T) + local count = 0 + if T == nil then return 0 end + for _ in pairs(T) do count = count + 1 end + return count +end + + +----------------------------------------------------------------------- +-- print table +----------------------------------------------------------------------- +function dump(o) + if type(o) == 'table' then + local s = '{ ' + for k,v in pairs(o) do + if type(k) ~= 'number' then k = '"'..k..'"' end + s = s .. '['..k..'] = ' .. dump(v) .. ',' + end + return s .. '} ' + else + return tostring(o) + end +end + + +----------------------------------------------------------------------- +-- print table +----------------------------------------------------------------------- +function printT(table, level) + key = "" + local func = function(table, level) end + func = function(table, level) + level = level or 1 + local indent = "" + for i = 1, level do + indent = indent.." " + end + if key ~= "" then + print(indent..key.." ".."=".." ".."{") + else + print(indent .. "{") + end + + key = "" + for k, v in pairs(table) do + if type(v) == "table" then + key = k + func(v, level + 1) + else + local content = string.format("%s%s = %s", indent .. " ",tostring(k), tostring(v)) + print(content) + end + end + print(indent .. "}") + end + func(table, level) +end + + +----------------------------------------------------------------------- +-- invoke command and retrive output +----------------------------------------------------------------------- +function os.call(command) + local fp = io.popen(command) + if fp == nil then + return nil + end + local line = fp:read('*l') + fp:close() + return line +end + + +----------------------------------------------------------------------- +-- write log +----------------------------------------------------------------------- +function os.log(text) + if not os.LOG_NAME then + return + end + local fp = io.open(os.LOG_NAME, 'a') + if not fp then + return + end + local date = "[" .. os.date('%Y-%m-%d %H:%M:%S') .. "] " + fp:write(date .. text .. "\n") + fp:close() +end + + +----------------------------------------------------------------------- +-- ffi optimize (luajit has builtin ffi module) +----------------------------------------------------------------------- +os.native = {} +os.native.status, os.native.ffi = pcall(require, "ffi") +if os.native.status then + local ffi = os.native.ffi + if windows then + ffi.cdef[[ + int GetFullPathNameA(const char *name, uint32_t size, char *out, char **name); + int ReplaceFileA(const char *dstname, const char *srcname, void *, uint32_t, void *, void *); + uint32_t GetTickCount(void); + uint32_t GetFileAttributesA(const char *name); + uint32_t GetCurrentDirectoryA(uint32_t size, char *ptr); + uint32_t GetShortPathNameA(const char *longname, char *shortname, uint32_t size); + uint32_t GetLongPathNameA(const char *shortname, char *longname, uint32_t size); + ]] + local kernel32 = ffi.load('kernel32.dll') + local buffer = ffi.new('char[?]', 4100) + local INVALID_FILE_ATTRIBUTES = 0xffffffff + local FILE_ATTRIBUTE_DIRECTORY = 0x10 + os.native.kernel32 = kernel32 + function os.native.GetFullPathName(name) + local hr = kernel32.GetFullPathNameA(name, 4096, buffer, nil) + return (hr > 0) and ffi.string(buffer, hr) or nil + end + function os.native.ReplaceFile(replaced, replacement) + local hr = kernel32.ReplaceFileA(replaced, replacement, nil, 2, nil, nil) + return (hr ~= 0) and true or false + end + function os.native.GetTickCount() + return kernel32.GetTickCount() + end + function os.native.GetFileAttributes(name) + return kernel32.GetFileAttributesA(name) + end + function os.native.GetLongPathName(name) + local hr = kernel32.GetLongPathNameA(name, buffer, 4096) + return (hr ~= 0) and ffi.string(buffer, hr) or nil + end + function os.native.GetShortPathName(name) + local hr = kernel32.GetShortPathNameA(name, buffer, 4096) + return (hr ~= 0) and ffi.string(buffer, hr) or nil + end + function os.native.GetRealPathName(name) + local short = os.native.GetShortPathName(name) + if short then + return os.native.GetLongPathName(short) + end + return nil + end + function os.native.exists(name) + local attr = os.native.GetFileAttributes(name) + return attr ~= INVALID_FILE_ATTRIBUTES + end + function os.native.isdir(name) + local attr = os.native.GetFileAttributes(name) + local isdir = FILE_ATTRIBUTE_DIRECTORY + if attr == INVALID_FILE_ATTRIBUTES then + return false + end + return (attr % (2 * isdir)) >= isdir + end + function os.native.getcwd() + local hr = kernel32.GetCurrentDirectoryA(4096, buffer) + if hr <= 0 then return nil end + return ffi.string(buffer, hr) + end + else + ffi.cdef[[ + typedef struct { long tv_sec; long tv_usec; } timeval; + int gettimeofday(timeval *tv, void *tz); + int access(const char *name, int mode); + char *realpath(const char *path, char *resolve); + char *getcwd(char *buf, size_t size); + ]] + local timeval = ffi.new('timeval[?]', 1) + local buffer = ffi.new('char[?]', 4100) + function os.native.gettimeofday() + local hr = ffi.C.gettimeofday(timeval, nil) + local sec = tonumber(timeval[0].tv_sec) + local usec = tonumber(timeval[0].tv_usec) + return sec + (usec * 0.000001) + end + function os.native.access(name, mode) + return ffi.C.access(name, mode) + end + function os.native.realpath(name) + local path = ffi.C.realpath(name, buffer) + return (path ~= nil) and ffi.string(buffer) or nil + end + function os.native.getcwd() + local hr = ffi.C.getcwd(buffer, 4099) + return hr ~= nil and ffi.string(buffer) or nil + end + end + function os.native.tickcount() + if windows then + return os.native.GetTickCount() + else + return math.floor(os.native.gettimeofday() * 1000) + end + end + os.native.init = true +end + + +----------------------------------------------------------------------- +-- get current path +----------------------------------------------------------------------- +function os.pwd() + if os.native and os.native.getcwd then + local hr = os.native.getcwd() + if hr then return hr end + end + if os.getcwd then + return os.getcwd() + end + if windows then + local fp = io.popen('cd') + if fp == nil then + return '' + end + local line = fp:read('*l') + fp:close() + return line + else + local fp = io.popen('pwd') + if fp == nil then + return '' + end + local line = fp:read('*l') + fp:close() + return line + end +end + + +----------------------------------------------------------------------- +-- which executable +----------------------------------------------------------------------- +function os.path.which(exename) + local path = os.getenv('PATH') + if windows then + paths = ('.;' .. path):split(';') + else + paths = path:split(':') + end + for _, path in pairs(paths) do + if not windows then + local name = path .. '/' .. exename + if os.path.exists(name) then + return name + end + else + for _, ext in pairs({'.exe', '.cmd', '.bat'}) do + local name = path .. '\\' .. exename .. ext + if path == '.' then + name = exename .. ext + end + if os.path.exists(name) then + return name + end + end + end + end + return nil +end + + +----------------------------------------------------------------------- +-- absolute path (simulated) +----------------------------------------------------------------------- +function os.path.absolute(path) + local pwd = os.pwd() + return os.path.normpath(os.path.join(pwd, path)) +end + + +----------------------------------------------------------------------- +-- absolute path (system call, can fall back to os.path.absolute) +----------------------------------------------------------------------- +function os.path.abspath(path) + if path == '' then path = '.' end + if os.native and os.native.GetFullPathName then + local test = os.native.GetFullPathName(path) + if test then return test end + end + if windows then + local script = 'FOR /f "delims=" %%i IN ("%s") DO @echo %%~fi' + local script = string.format(script, path) + local script = 'cmd.exe /C ' .. script .. ' 2> nul' + local output = os.call(script) + local test = output:gsub('%s$', '') + if test ~= nil and test ~= '' then + return test + end + else + local test = os.path.which('realpath') + if test ~= nil and test ~= '' then + test = os.call('realpath -s \'' .. path .. '\' 2> /dev/null') + if test ~= nil and test ~= '' then + return test + end + test = os.call('realpath \'' .. path .. '\' 2> /dev/null') + if test ~= nil and test ~= '' then + return test + end + end + local test = os.path.which('perl') + if test ~= nil and test ~= '' then + local s = 'perl -MCwd -e "print Cwd::realpath(\\$ARGV[0])" \'%s\'' + local s = string.format(s, path) + test = os.call(s) + if test ~= nil and test ~= '' then + return test + end + end + for _, python in pairs({'python3', 'python2', 'python'}) do + local s = 'sys.stdout.write(os.path.abspath(sys.argv[1]))' + local s = '-c "import os, sys;' .. s .. '" \'' .. path .. '\'' + local s = python .. ' ' .. s + local test = os.path.which(python) + if test ~= nil and test ~= '' then + test = os.call(s) + if test ~= nil and test ~= '' then + return test + end + end + end + end + return os.path.absolute(path) +end + + +----------------------------------------------------------------------- +-- dir exists +----------------------------------------------------------------------- +function os.path.isdir(pathname) + if pathname == '/' then + return true + elseif pathname == '' then + return false + elseif windows then + if pathname == '\\' then + return true + end + end + if os.native and os.native.isdir then + return os.native.isdir(pathname) + end + if clink and os.isdir then + return os.isdir(pathname) + end + local name = pathname + if (not name:endswith('/')) and (not name:endswith('\\')) then + name = name .. os.path.sep + end + return os.path.exists(name) +end + + +----------------------------------------------------------------------- +-- file or path exists +----------------------------------------------------------------------- +function os.path.exists(name) + if name == '/' then + return true + end + if os.native and os.native.exists then + return os.native.exists(name) + end + local ok, err, code = os.rename(name, name) + if not ok then + if code == 13 or code == 17 then + return true + elseif code == 30 then + local f = io.open(name,"r") + if f ~= nil then + io.close(f) + return true + end + elseif name:sub(-1) == '/' and code == 20 and (not windows) then + local test = name .. '.' + ok, err, code = os.rename(test, test) + if code == 16 or code == 13 or code == 22 then + return true + end + end + return false + end + return true +end + + +----------------------------------------------------------------------- +-- is absolute path +----------------------------------------------------------------------- +function os.path.isabs(path) + if path == nil or path == '' then + return false + elseif path:sub(1, 1) == '/' then + return true + end + if windows then + local head = path:sub(1, 1) + if head == '\\' then + return true + elseif path:match('^%a:[/\\]') ~= nil then + return true + end + end + return false +end + + +----------------------------------------------------------------------- +-- normalize path +----------------------------------------------------------------------- +function os.path.norm(pathname) + if windows then + pathname = pathname:gsub('\\', '/') + end + if windows then + pathname = pathname:gsub('/', '\\') + end + return pathname +end + + +----------------------------------------------------------------------- +-- normalize . and .. +----------------------------------------------------------------------- +function os.path.normpath(path) + if os.path.sep ~= '/' then + path = path:gsub('\\', '/') + end + path = path:gsub('/+', '/') + local srcpath = path + local basedir = '' + local isabs = false + if windows and path:sub(2, 2) == ':' then + basedir = path:sub(1, 2) + path = path:sub(3, -1) + end + if path:sub(1, 1) == '/' then + basedir = basedir .. '/' + isabs = true + path = path:sub(2, -1) + end + local parts = path:split('/') + local output = {} + for _, path in ipairs(parts) do + if path == '.' or path == '' then + elseif path == '..' then + local size = #output + if size == 0 then + if not isabs then + table.insert(output, '..') + end + elseif output[size] == '..' then + table.insert(output, '..') + else + table.remove(output, size) + end + else + table.insert(output, path) + end + end + path = basedir .. string.join('/', output) + if windows then path = path:gsub('/', '\\') end + return path == '' and '.' or path +end + + +----------------------------------------------------------------------- +-- join two path +----------------------------------------------------------------------- +function os.path.join(path1, path2) + if path1 == nil or path1 == '' then + if path2 == nil or path2 == '' then + return '' + else + return path2 + end + elseif path2 == nil or path2 == '' then + local head = path1:sub(-1, -1) + if head == '/' or (windows and head == '\\') then + return path1 + end + return path1 .. os.path.sep + elseif os.path.isabs(path2) then + if windows then + local head = path2:sub(1, 1) + if head == '/' or head == '\\' then + if path1:match('^%a:') then + return path1:sub(1, 2) .. path2 + end + end + end + return path2 + elseif windows then + local d1 = path1:match('^%a:') and path1:sub(1, 2) or '' + local d2 = path2:match('^%a:') and path2:sub(1, 2) or '' + if d1 ~= '' then + if d2 ~= '' then + if d1:lower() == d2:lower() then + return d2 .. os.path.join(path1:sub(3), path2:sub(3)) + else + return path2 + end + end + elseif d2 ~= '' then + return path2 + end + end + local postsep = true + local len1 = path1:len() + local len2 = path2:len() + if path1:sub(-1, -1) == '/' then + postsep = false + elseif windows then + if path1:sub(-1, -1) == '\\' then + postsep = false + elseif len1 == 2 and path1:sub(2, 2) == ':' then + postsep = false + end + end + if postsep then + return path1 .. os.path.sep .. path2 + else + return path1 .. path2 + end +end + + +----------------------------------------------------------------------- +-- split +----------------------------------------------------------------------- +function os.path.split(path) + if path == '' then + return '', '' + end + local pos = path:rfind('/') + if os.path.sep == '\\' then + local p2 = path:rfind('\\') + if pos == nil and p2 ~= nil then + pos = p2 + elseif pos ~= nil and p2 ~= nil then + pos = (pos < p2) and pos or p2 + end + if path:match('^%a:[/\\]') and pos == nil then + return path:sub(1, 2), path:sub(3) + end + end + if pos == nil then + if windows then + local drive = path:match('^%a:') and path:sub(1, 2) or '' + if drive ~= '' then + return path:sub(1, 2), path:sub(3) + end + end + return '', path + elseif pos == 1 then + return path:sub(1, 1), path:sub(2) + elseif windows then + local drive = path:match('^%a:') and path:sub(1, 2) or '' + if pos == 3 and drive ~= '' then + return path:sub(1, 3), path:sub(4) + end + end + local head = path:sub(1, pos) + local tail = path:sub(pos + 1) + if not windows then + local test = string.rep('/', head:len()) + if head ~= test then + head = head:gsub('/+$', '') + end + else + local t1 = string.rep('/', head:len()) + local t2 = string.rep('\\', head:len()) + if head ~= t1 and head ~= t2 then + head = head:gsub('[/\\]+$', '') + end + end + return head, tail +end + + +----------------------------------------------------------------------- +-- check subdir +----------------------------------------------------------------------- +function os.path.subdir(basename, subname) + if windows then + basename = basename:gsub('\\', '/') + subname = subname:gsub('\\', '/') + basename = basename:lower() + subname = subname:lower() + end + local last = basename:sub(-1, -1) + if last ~= '/' then + basename = basename .. '/' + end + if subname:find(basename, 0, true) == 1 then + return true + end + return false +end + + +----------------------------------------------------------------------- +-- check single name element +----------------------------------------------------------------------- +function os.path.single(path) + if string.match(path, '/') then + return false + end + if windows then + if string.match(path, '\\') then + return false + end + end + return true +end + + +----------------------------------------------------------------------- +-- expand user home +----------------------------------------------------------------------- +function os.path.expand(pathname) + if not pathname:find('~') then + return pathname + end + local home = '' + if windows then + home = os.getenv('USERPROFILE') + else + home = os.getenv('HOME') + end + if pathname == '~' then + return home + end + local head = pathname:sub(1, 2) + if windows then + if head == '~/' or head == '~\\' then + return home .. '\\' .. pathname:sub(3, -1) + end + elseif head == '~/' then + return home .. '/' .. pathname:sub(3, -1) + end + return pathname +end + + +----------------------------------------------------------------------- +-- search executable +----------------------------------------------------------------------- +function os.path.search(name) +end + + +----------------------------------------------------------------------- +-- get lua executable +----------------------------------------------------------------------- +function os.interpreter() + if os.argv == nil then + io.stderr:write("cannot get arguments (arg), recompiled your lua\n") + return nil + end + local lua = os.argv[-1] + if lua == nil then + io.stderr:write("cannot get executable name, recompiled your lua\n") + end + if os.path.single(lua) then + local path = os.path.which(lua) + if not os.path.isabs(path) then + return os.path.abspath(path) + end + return path + end + return os.path.abspath(lua) +end + + +----------------------------------------------------------------------- +-- get script name +----------------------------------------------------------------------- +function os.scriptname() + if os.argv == nil then + io.stderr:write("cannot get arguments (arg), recompiled your lua\n") + return nil + end + local script = os.argv[0] + if script == nil then + io.stderr:write("cannot get script name, recompiled your lua\n") + end + return os.path.abspath(script) +end + + +----------------------------------------------------------------------- +-- get environ +----------------------------------------------------------------------- +function os.environ(name, default) + local value = os.getenv(name) + if os.envmap ~= nil and type(os.envmap) == 'table' then + local t = os.envmap[name] + value = (t ~= nil and type(t) == 'string') and t or value + end + if value == nil then + return default + elseif type(default) == 'boolean' then + value = value:lower() + if value == '0' or value == '' or value == 'no' then + return false + elseif value == 'false' or value == 'n' or value == 'f' then + return false + else + return true + end + elseif type(default) == 'number' then + value = tonumber(value) + if value == nil then + return default + else + return value + end + elseif type(default) == 'string' then + return value + elseif type(default) == 'table' then + return value:sep(',') + end +end + + +----------------------------------------------------------------------- +-- parse option +----------------------------------------------------------------------- +function os.getopt(argv) + local args = {} + local options = {} + argv = argv ~= nil and argv or os.argv + if argv == nil then + return nil, nil + elseif (#argv) == 0 then + return options, args + end + local count = #argv + local index = 1 + while index <= count do + local arg = argv[index] + local head = arg:sub(1, 1) + if arg ~= '' then + if head ~= '-' then + break + end + if arg == '-' then + options['-'] = '' + elseif arg == '--' then + options['-'] = '-' + elseif arg:match('^-%d+$') then + options['-'] = arg:sub(2) + else + local part = arg:split('=') + options[part[1]] = part[2] ~= nil and part[2] or '' + end + end + index = index + 1 + end + while index <= count do + table.insert(args, argv[index]) + index = index + 1 + end + return options, args +end + + +----------------------------------------------------------------------- +-- generate random seed +----------------------------------------------------------------------- +function math.random_init() + -- random seed from os.time() + local seed = tostring(os.time() * 1000) + seed = seed .. tostring(math.random(99999999)) + if os.argv ~= nil then + for _, key in ipairs(os.argv) do + seed = seed .. '/' .. key + end + end + local ppid = os.getenv('PPID') + seed = (ppid ~= nil) and (seed .. '/' .. ppid) or seed + -- random seed from socket.gettime() + local status, socket = pcall(require, 'socket') + if status then + seed = seed .. tostring(socket.gettime()) + end + -- random seed from _ZL_RANDOM + local rnd = os.getenv('_ZL_RANDOM') + if rnd ~= nil then + seed = seed .. rnd + end + seed = seed .. tostring(os.clock() * 10000000) + if os.native and os.native.tickcount then + seed = seed .. tostring(os.native.tickcount()) + end + local number = 0 + for i = 1, seed:len() do + local k = string.byte(seed:sub(i, i)) + number = ((number * 127) % 0x7fffffff) + k + end + math.randomseed(number) +end + + +----------------------------------------------------------------------- +-- math random string +----------------------------------------------------------------------- +function math.random_string(N) + local text = '' + for i = 1, N do + local k = math.random(0, 26 * 2 + 10 - 1) + if k < 26 then + text = text .. string.char(0x41 + k) + elseif k < 26 * 2 then + text = text .. string.char(0x61 + k - 26) + elseif k < 26 * 2 + 10 then + text = text .. string.char(0x30 + k - 26 * 2) + else + end + end + return text +end + + +----------------------------------------------------------------------- +-- returns true for path is insensitive +----------------------------------------------------------------------- +function path_case_insensitive() + if windows then + return true + end + local eos = os.getenv('OS') + eos = eos ~= nil and eos or '' + eos = eos:lower() + if eos:sub(1, 7) == 'windows' then + return true + end + return false +end + + +----------------------------------------------------------------------- +-- load and split data +----------------------------------------------------------------------- +function data_load(filename) + local M = {} + local N = {} + local insensitive = path_case_insensitive() + local fp = io.open(os.path.expand(filename), 'r') + if fp == nil then + return {} + end + for line in fp:lines() do + local part = string.split(line, '|') + local item = {} + if part and part[1] and part[2] and part[3] then + local key = insensitive and part[1]:lower() or part[1] + part[2] = part[2]:gsub(",", ".") + item.name = part[1] + item.rank = tonumber(part[2]) + item.time = tonumber(part[3]) + 0 + item.frecent = item.rank + if string.len(part[3]) < 12 then + if item.rank ~= nil and item.time ~= nil then + if N[key] == nil then + table.insert(M, item) + N[key] = 1 + end + end + end + end + end + fp:close() + return M +end + + +----------------------------------------------------------------------- +-- save data +----------------------------------------------------------------------- +function data_save(filename, M) + local fp = nil + local tmpname = nil + local i + filename = os.path.expand(filename) + math.random_init() + while true do + tmpname = filename .. '.' .. tostring(os.time()) + if os.native and os.native.tickcount then + local key = os.native.tickcount() % 1000 + tmpname = tmpname .. string.format('%03d', key) + tmpname = tmpname .. math.random_string(5) + else + tmpname = tmpname .. math.random_string(8) + end + if not os.path.exists(tmpname) then + -- print('tmpname: '..tmpname) + break + end + end + if windows then + if os.native and os.native.ReplaceFile then + fp = io.open(tmpname, 'w') + else + fp = io.open(filename, 'w') + tmpname = nil + end + else + fp = io.open(tmpname, 'w') + end + if fp == nil then + return false + end + for i = 1, #M do + local item = M[i] + local text = item.name .. '|' .. item.rank .. '|' .. item.time + fp:write(text .. '\n') + end + fp:close() + if tmpname ~= nil then + if windows then + local ok, err, code = os.rename(tmpname, filename) + if not ok then + os.native.ReplaceFile(filename, tmpname) + end + else + os.rename(tmpname, filename) + end + os.remove(tmpname) + end + return true +end + + +----------------------------------------------------------------------- +-- filter out bad dirname +----------------------------------------------------------------------- +function data_filter(M) + local N = {} + local i + M = M ~= nil and M or {} + for i = 1, #M do + local item = M[i] + if os.path.isdir(item.name) then + table.insert(N, item) + end + end + return N +end + + +----------------------------------------------------------------------- +-- insert item +----------------------------------------------------------------------- +function data_insert(M, filename) + local i = 1 + local sumscore = 0 + for i = 1, #M do + local item = M[i] + sumscore = sumscore + item.rank + end + if sumscore >= MAX_AGE then + local X = {} + for i = 1, #M do + local item = M[i] + item.rank = item.rank * 0.9 + if item.rank >= 1.0 then + table.insert(X, item) + end + end + M = X + end + local nocase = path_case_insensitive() + local name = filename + local key = nocase and string.lower(name) or name + local find = false + local current = os.time() + for i = 1, #M do + local item = M[i] + if not nocase then + if name == item.name then + item.rank = item.rank + 1 + item.time = current + find = true + break + end + else + if key == string.lower(item.name) then + item.rank = item.rank + 1 + item.time = current + find = true + break + end + end + end + if not find then + local item = {} + item.name = name + item.rank = 1 + item.time = current + item.frecent = item.rank + table.insert(M, item) + end + return M +end + + +----------------------------------------------------------------------- +-- change database +----------------------------------------------------------------------- +function data_file_set(name) + DATA_FILE = name +end + + +----------------------------------------------------------------------- +-- change pattern +----------------------------------------------------------------------- +function case_insensitive_pattern(pattern) + -- find an optional '%' (group 1) followed by any character (group 2) + local p = pattern:gsub("(%%?)(.)", function(percent, letter) + + if percent ~= "" or not letter:match("%a") then + -- if the '%' matched, or `letter` is not a letter, return "as is" + return percent .. letter + else + -- else, return a case-insensitive character class of the matched letter + return string.format("[%s%s]", letter:lower(), letter:upper()) + end + end) + return p +end + + +----------------------------------------------------------------------- +-- pathmatch +----------------------------------------------------------------------- +function path_match(pathname, patterns, matchlast) + local pos = 1 + local i = 0 + local matchlast = matchlast ~= nil and matchlast or false + for i = 1, #patterns do + local pat = patterns[i] + local start, endup = pathname:find(pat, pos) + if start == nil or endup == nil then + return false + end + pos = endup + 1 + end + if matchlast and #patterns > 0 then + local last = '' + local index = #patterns + local pat = patterns[index] + if not windows then + last = string.match(pathname, ".*(/.*)") + else + last = string.match(pathname, ".*([/\\].*)") + end + if last then + local start, endup = last:find(pat, 1) + if start == nil or endup == nil then + return false + end + end + end + return true +end + + +----------------------------------------------------------------------- +-- select matched pathnames +----------------------------------------------------------------------- +function data_select(M, patterns, matchlast) + local N = {} + local i = 1 + local pats = {} + for i = 1, #patterns do + local p = patterns[i] + if Z_HYPHEN then + p = p:gsub('-', '%%-') + end + table.insert(pats, case_insensitive_pattern(p)) + end + for i = 1, #M do + local item = M[i] + if path_match(item.name, pats, matchlast) then + table.insert(N, item) + end + end + return N +end + + +----------------------------------------------------------------------- +-- update frecent +----------------------------------------------------------------------- +function data_update_frecent(M) + local current = os.time() + local i + for i = 1, #M do + local item = M[i] + local dx = current - item.time + if dx < 3600 then + item.frecent = item.rank * 4 + elseif dx < 86400 then + item.frecent = item.rank * 2 + elseif dx < 604800 then + item.frecent = item.rank * 0.5 + else + item.frecent = item.rank * 0.25 + end + end + return M +end + + +----------------------------------------------------------------------- +-- add path +----------------------------------------------------------------------- +function z_add(path) + local paths = {} + local count = 0 + if type(path) == 'table' then + paths = path + elseif type(path) == 'string' then + paths[1] = path + end + if table.length(paths) == 0 then + return false + end + local H = os.getenv('HOME') + local M = data_load(DATA_FILE) + local nc = os.getenv('_ZL_NO_CHECK') + if nc == nil or nc == '' or nc == '0' then + M = data_filter(M) + end + -- insert paths + for _, path in pairs(paths) do + if os.path.isdir(path) and os.path.isabs(path) then + local skip = false + local test = path + path = os.path.norm(path) + -- check ignore + if windows then + if path:len() == 3 and path:sub(2, 2) == ':' then + local tail = path:sub(3, 3) + if tail == '/' or tail == '\\' then + skip = true + end + end + test = os.path.norm(path:lower()) + else + if H == path then + skip = true + end + end + -- check exclude + if not skip then + for _, exclude in ipairs(Z_EXCLUDE) do + if test:startswith(exclude) then + skip = true + break + end + end + end + if not skip then + if windows then + if os.native and os.native.GetRealPathName then + local ts = os.native.GetRealPathName(path) + if ts then + path = ts + end + end + end + M = data_insert(M, path) + count = count + 1 + end + end + end + if count > 0 then + data_save(DATA_FILE, M) + end + return true +end + + +----------------------------------------------------------------------- +-- remove path +----------------------------------------------------------------------- +function z_remove(path) + local paths = {} + local count = 0 + local remove = {} + if type(path) == 'table' then + paths = path + elseif type(path) == 'string' then + paths[1] = path + end + if table.length(paths) == 0 then + return false + end + local H = os.getenv('HOME') + local M = data_load(DATA_FILE) + local X = {} + M = data_filter(M) + local insensitive = path_case_insensitive() + for _, path in pairs(paths) do + path = os.path.abspath(path) + if not insensitive then + remove[path] = 1 + else + remove[path:lower()] = 1 + end + end + for i = 1, #M do + local item = M[i] + if not insensitive then + if not remove[item.name] then + table.insert(X, item) + end + else + if not remove[item.name:lower()] then + table.insert(X, item) + end + end + end + data_save(DATA_FILE, X) +end + + +----------------------------------------------------------------------- +-- match method: frecent, rank, time +----------------------------------------------------------------------- +function z_match(patterns, method, subdir) + patterns = patterns ~= nil and patterns or {} + method = method ~= nil and method or 'frecent' + subdir = subdir ~= nil and subdir or false + local M = data_load(DATA_FILE) + M = data_select(M, patterns, false) + M = data_filter(M) + if Z_MATCHNAME then + local N = data_select(M, patterns, true) + N = data_filter(N) + if #N > 0 then + M = N + end + end + M = data_update_frecent(M) + if method == 'time' then + current = os.time() + for _, item in pairs(M) do + item.score = item.time - current + end + elseif method == 'rank' then + for _, item in pairs(M) do + item.score = item.rank + end + else + for _, item in pairs(M) do + item.score = item.frecent + end + end + table.sort(M, function (a, b) return a.score > b.score end) + local pwd = (PWD == nil or PWD == '') and os.getenv('PWD') or PWD + if pwd == nil or pwd == '' then + pwd = os.pwd() + end + if pwd ~= '' and pwd ~= nil then + if subdir then + local N = {} + for _, item in pairs(M) do + if os.path.subdir(pwd, item.name) then + table.insert(N, item) + end + end + M = N + end + if Z_SKIPPWD then + local N = {} + local key = windows and string.lower(pwd) or pwd + for _, item in pairs(M) do + local match = false + local name = windows and string.lower(item.name) or item.name + if name ~= key then + table.insert(N, item) + end + end + M = N + end + end + return M +end + + +----------------------------------------------------------------------- +-- pretty print +----------------------------------------------------------------------- +function z_print(M, weight, number) + local N = {} + local maxsize = 9 + local numsize = string.len(tostring(#M)) + for _, item in pairs(M) do + local record = {} + record.score = string.format('%.2f', item.score) + record.name = item.name + table.insert(N, record) + if record.score:len() > maxsize then + maxsize = record.score:len() + end + end + local fp = io.stdout + if PRINT_MODE == '' then + fp = io.stdout + elseif PRINT_MODE == '' then + fp = io.stderr + else + fp = io.open(PRINT_MODE, 'w') + end + for i = #N, 1, -1 do + local record = N[i] + local line = record.score + while true do + local tail = line:sub(-1, -1) + if tail ~= '0' and tail ~= '.' then + break + end + line = line:sub(1, -2) + if tail == '.' then + break + end + end + local dx = maxsize - line:len() + if dx > 0 then + line = line .. string.rep(' ', dx) + end + if weight then + line = line .. ' ' .. record.name + else + line = record.name + end + if number then + local head = tostring(i) + if head:len() < numsize then + head = string.rep(' ', numsize - head:len()) .. head + end + line = head .. ': ' .. line + end + if fp ~= nil then + fp:write(line .. '\n') + end + end + if PRINT_MODE:sub(1, 1) ~= '<' then + if fp ~= nil then fp:close() end + end +end + + +----------------------------------------------------------------------- +-- calculate jump dir +----------------------------------------------------------------------- +function z_cd(patterns) + if patterns == nil then + return nil + end + if #patterns == 0 then + return nil + end + local last = patterns[#patterns] + if last == '~' or last == '~/' then + return os.path.expand('~') + elseif windows and last == '~\\' then + return os.path.expand('~') + end + if os.path.isabs(last) and os.path.isdir(last) then + local size = #patterns + if size <= 1 then + return os.path.norm(last) + elseif last ~= '/' and last ~= '\\' then + return os.path.norm(last) + end + end + local M = z_match(patterns, Z_METHOD, Z_SUBDIR) + if M == nil then + return nil + end + if #M == 0 then + return nil + elseif #M == 1 then + return M[1].name + elseif Z_INTERACTIVE == 0 then + return M[1].name + end + if os.environ('_ZL_INT_SORT', false) then + table.sort(M, function (a, b) return a.name < b.name end) + end + local retval = nil + if Z_INTERACTIVE == 1 then + PRINT_MODE = '' + z_print(M, true, true) + io.stderr:write('> ') + io.stderr:flush() + local input = io.read('*l') + if input == nil or input == '' then + return nil + end + local index = tonumber(input) + if index == nil then + return nil + end + if index < 1 or index > #M then + return nil + end + retval = M[index].name + elseif Z_INTERACTIVE == 2 then + local fzf = os.environ('_ZL_FZF', 'fzf') + local tmpname = '/tmp/zlua.txt' + local cmd = '--nth 2.. --reverse --info=inline --tac ' + local flag = os.environ('_ZL_FZF_FLAG', '') + flag = (flag == '' or flag == nil) and '+s -e' or flag + cmd = ((fzf == '') and 'fzf' or fzf) .. ' ' .. cmd .. ' ' .. flag + if not windows then + tmpname = os.tmpname() + local height = os.environ('_ZL_FZF_HEIGHT', '35%') + if height ~= nil and height ~= '' and height ~= '0' then + cmd = cmd .. ' --height ' .. height + end + cmd = cmd .. ' < "' .. tmpname .. '"' + else + tmpname = os.tmpname():gsub('\\', ''):gsub('%.', '') + tmpname = os.environ('TMP', '') .. '\\zlua_' .. tmpname .. '.txt' + cmd = 'type "' .. tmpname .. '" | ' .. cmd + end + PRINT_MODE = tmpname + z_print(M, true, false) + retval = os.call(cmd) + -- io.stderr:write('<'..cmd..'>\n') + os.remove(tmpname) + if retval == '' or retval == nil then + return nil + end + local pos = retval:find(' ') + if not pos then + return nil + end + retval = retval:sub(pos, -1):gsub('^%s*', '') + end + return (retval ~= '' and retval or nil) +end + + +----------------------------------------------------------------------- +-- purge invalid paths +----------------------------------------------------------------------- +function z_purge() + local M = data_load(DATA_FILE) + local N = data_filter(M) + local x = #M + local y = #N + if x == y then + return x, y + end + data_save(DATA_FILE, N) + return x, y +end + + +----------------------------------------------------------------------- +-- find_vcs_root +----------------------------------------------------------------------- +function find_vcs_root(path) + local markers = os.getenv('_ZL_ROOT_MARKERS') + local markers = markers and markers or '.git,.svn,.hg,.root' + local markers = string.split(markers, ',') + path = os.path.absolute(path) + while true do + for _, marker in ipairs(markers) do + local test = os.path.join(path, marker) + if os.path.exists(test) then + return path + end + end + local parent, _ = os.path.split(path) + if path == parent then break end + path = parent + end + return nil +end + + +----------------------------------------------------------------------- +-- cd to parent directories which contains keyword +-- #args == 0 -> returns to vcs root +-- #args == 1 -> returns to parent dir starts with args[1] +-- #args == 2 -> returns string.replace($PWD, args[1], args[2]) +----------------------------------------------------------------------- +function cd_backward(args, options, pwd) + local nargs = #args + local pwd = (pwd ~= nil) and pwd or os.pwd() + if nargs == 0 then + return find_vcs_root(pwd) + elseif nargs == 1 and args[1]:sub(1, 2) == '..' then + local size = args[1]:len() - 1 + if args[1]:match('^%.%.+$') then + size = args[1]:len() - 1 + elseif args[1]:match('^%.%.%d+$') then + size = tonumber(args[1]:sub(3)) + else + return nil + end + local path = pwd + for index = 1, size do + path = os.path.join(path, '..') + end + return os.path.normpath(path) + elseif nargs == 1 then + pwd = os.path.split(pwd) + local test = windows and pwd:gsub('\\', '/') or pwd + local key = windows and args[1]:lower() or args[1] + if not key:match('%u') then + test = test:lower() + end + local pos, ends = test:rfind('/' .. key) + if pos then + ends = test:find('/', pos + key:len() + 1, true) + ends = ends and ends or test:len() + return os.path.normpath(pwd:sub(1, ends)) + elseif windows and test:startswith(key) then + ends = test:find('/', key:len(), true) + ends = ends and ends or test:len() + return os.path.normpath(pwd:sub(1, ends)) + end + pos = test:rfind(key) + if pos then + ends = test:find('/', pos + key:len(), true) + ends = ends and ends or test:len() + return os.path.normpath(pwd:sub(1, ends)) + end + return nil + elseif nargs == 2 then + local test = windows and pwd:gsub('\\', '/') or pwd + local src = args[1] + local dst = args[2] + if not src:match('%u') then + test = test:lower() + end + local start, ends = test:rfind(src) + if not start then + return pwd + end + + local lhs = pwd:sub(1, start - 1) + local rhs = pwd:sub(ends + 1) + local newpath = lhs .. dst .. rhs + if os.path.isdir(newpath) then + return newpath + end + + -- Get rid of the entire path component that matched `src`. + lhs = lhs:gsub("[^/]*$", "") + rhs = rhs:gsub("^[^/]*", "") + return z_cd({lhs, dst, rhs}) + -- In the future, it would make sense to have `z -b -c from to to2` + -- to z_cd({lhs, dst[1], dst[2]}). Without `-c`, we probably still + -- want to support only 2 argumets. + end + + io.stderr:write("Error: " .. Z_CMD .. " -b takes at most 2 arguments.\n") + return nil +end + + +----------------------------------------------------------------------- +-- cd minus: "z -", "z --", "z -2" +----------------------------------------------------------------------- +function cd_minus(args, options) + Z_SKIPPWD = true + local M = z_match({}, 'time', Z_SUBDIR) + local size = #M + if options['-'] == '-' then + for i, item in ipairs(M) do + if i > 10 then break end + io.stderr:write(' ' .. tostring(i - 1) .. ' ' .. item.name .. '\n') + end + else + local level = 0 + local num = options['-'] + if num and num ~= '' then + level = tonumber(num) + end + if level >= 0 and level < size then + return M[level + 1].name + end + end + return nil +end + + +----------------------------------------------------------------------- +-- cd breadcrumbs: z -b -i, z -b -I +----------------------------------------------------------------------- +function cd_breadcrumbs(pwd, interactive) + local pwd = (pwd == nil or pwd == '') and os.pwd() or pwd + local pwd = os.path.normpath(pwd) + local path, _ = os.path.split(pwd) + local elements = {} + local interactive = interactive and interactive or 1 + local fullname = os.environ('_ZL_FULL_PATH', false) + while true do + local head, name = os.path.split(path) + if head == path then -- reached root + table.insert(elements, {head, head}) + break + elseif name ~= '' then + table.insert(elements, {name, path}) + else + break + end + path = head + end + local tmpname = '/tmp/zlua.txt' + local fp = io.stderr + if interactive == 2 then + if not windows then + tmpname = os.tmpname() + else + tmpname = os.tmpname():gsub('\\', ''):gsub('%.', '') + tmpname = os.environ('TMP', '') .. '\\zlua_' .. tmpname .. '.txt' + end + fp = io.open(tmpname, 'w') + end + -- print table + local maxsize = string.len(tostring(#elements)) + for i = #elements, 1, -1 do + local item = elements[i] + local name = item[1] + local text = string.rep(' ', maxsize - string.len(i)) .. tostring(i) + text = text .. ': ' .. (fullname and item[2] or item[1]) + fp:write(text .. '\n') + end + if fp ~= io.stderr then + fp:close() + end + local retval = '' + -- select from stdin or fzf + if interactive == 1 then + io.stderr:write('> ') + io.stderr:flush() + retval = io.read('*l') + elseif interactive == 2 then + local fzf = os.environ('_ZL_FZF', 'fzf') + local cmd = '--reverse --info=inline --tac ' + local flag = os.environ('_ZL_FZF_FLAG', '') + flag = (flag == '' or flag == nil) and '+s -e' or flag + cmd = ((fzf == '') and 'fzf' or fzf) .. ' ' .. cmd .. ' ' .. flag + if not windows then + local height = os.environ('_ZL_FZF_HEIGHT', '35%') + if height ~= nil and height ~= '' and height ~= '0' then + cmd = cmd .. ' --height ' .. height + end + cmd = cmd .. '< "' .. tmpname .. '"' + else + cmd = 'type "' .. tmpname .. '" | ' .. cmd + end + retval = os.call(cmd) + os.remove(tmpname) + if retval == '' or retval == nil then + return nil + end + local pos = retval:find(':') + if not pos then + return nil + end + retval = retval:sub(1, pos - 1):gsub('^%s*', '') + end + local index = tonumber(retval) + if index == nil or index < 1 or index > #elements then + return nil + end + return elements[index][2] +end + + +----------------------------------------------------------------------- +-- main entry +----------------------------------------------------------------------- +function main(argv) + local options, args = os.getopt(argv) + os.log("main()") + if options == nil then + return false + elseif table.length(args) == 0 and table.length(options) == 0 then + print(os.argv[0] .. ': missing arguments') + help = os.argv[-1] .. ' ' .. os.argv[0] .. ' --help' + print('Try \'' .. help .. '\' for more information') + return false + end + if true then + os.log("options: " .. dump(options)) + os.log("args: " .. dump(args)) + end + if options['-c'] then + Z_SUBDIR = true + end + if options['-r'] then + Z_METHOD = 'rank' + elseif options['-t'] then + Z_METHOD = 'time' + end + if options['-i'] then + Z_INTERACTIVE = 1 + elseif options['-I'] then + Z_INTERACTIVE = 2 + end + if options['--cd'] or options['-e'] then + local path = '' + if options['-b'] then + if #args > 0 or Z_INTERACTIVE == 0 then + path = cd_backward(args, options) + else + path = cd_breadcrumbs('', Z_INTERACTIVE) + end + elseif options['-'] then + path = cd_minus(args, options) + elseif #args == 0 then + path = nil + else + path = z_cd(args) + if path == nil and Z_MATCHMODE ~= 0 then + local last = args[#args] + if os.path.isdir(last) then + path = os.path.abspath(last) + path = os.path.norm(path) + end + end + end + if path ~= nil then + io.write(path .. (options['-e'] and "\n" or "")) + end + elseif options['--add'] then + -- print('data: ' .. DATA_FILE) + z_add(args) + elseif options['-x'] then + z_remove(args) + elseif options['--purge'] then + local src, dst = z_purge() + local fp = io.stderr + fp:write('purge: ' .. tostring(src) .. ' record(s) remaining, ') + fp:write(tostring(src - dst) .. ' invalid record(s) removed.\n') + elseif options['--init'] then + local opts = {} + for _, key in ipairs(args) do + opts[key] = 1 + end + if windows then + z_windows_init(opts) + elseif opts.fish then + z_fish_init(opts) + elseif opts.powershell then + z_windows_init(opts) + else + z_shell_init(opts) + end + elseif options['-l'] then + local M = z_match(args and args or {}, Z_METHOD, Z_SUBDIR) + if options['-s'] then + z_print(M, false, false) + else + z_print(M, true, false) + end + elseif options['--complete'] then + local line = args[1] and args[1] or '' + local head = line:sub(Z_CMD:len()+1):gsub('^%s+', '') + local M = z_match({head}, Z_METHOD, Z_SUBDIR) + for _, item in pairs(M) do + print(item.name) + end + elseif options['--help'] or options['-h'] then + z_help() + end + return true +end + + +----------------------------------------------------------------------- +-- initialize from environment variable +----------------------------------------------------------------------- +function z_init() + local _zl_data = os.getenv('_ZL_DATA') + local _zl_maxage = os.getenv('_ZL_MAXAGE') + local _zl_exclude = os.getenv('_ZL_EXCLUDE_DIRS') + local _zl_cmd = os.getenv('_ZL_CMD') + local _zl_matchname = os.getenv('_ZL_MATCH_NAME') + local _zl_skippwd = os.getenv('_ZL_SKIP_PWD') + local _zl_matchmode = os.getenv('_ZL_MATCH_MODE') + local _zl_hyphen = os.getenv('_ZL_HYPHEN') + if _zl_data ~= nil and _zl_data ~= "" then + if windows then + DATA_FILE = _zl_data + else + -- avoid windows environments affect cygwin & msys + if not string.match(_zl_data, '^%a:[/\\]') then + DATA_FILE = _zl_data + end + end + end + if _zl_maxage ~= nil and _zl_maxage ~= "" then + _zl_maxage = tonumber(_zl_maxage) + if _zl_maxage ~= nil and _zl_maxage > 0 then + MAX_AGE = _zl_maxage + end + end + if _zl_exclude ~= nil and _zl_exclude ~= "" then + local part = _zl_exclude:split(',') + local insensitive = path_case_insensitive() + for _, name in ipairs(part) do + if insensitive then + name = name:lower() + end + if windows then + name = os.path.norm(name) + end + table.insert(Z_EXCLUDE, name) + end + end + if _zl_cmd ~= nil and _zl_cmd ~= '' then + Z_CMD = _zl_cmd + end + if _zl_matchname ~= nil then + local m = string.lower(_zl_matchname) + if (m == '1' or m == 'yes' or m == 'true' or m == 't') then + Z_MATCHNAME = true + end + end + if _zl_skippwd ~= nil then + local m = string.lower(_zl_skippwd) + if (m == '1' or m == 'yes' or m == 'true' or m == 't') then + Z_SKIPPWD = true + end + end + if _zl_matchmode ~= nil then + local m = tonumber(_zl_matchmode) + Z_MATCHMODE = m + if (m == 1) then + Z_MATCHNAME = true + Z_SKIPPWD = true + end + end + if _zl_hyphen ~= nil then + local m = string.lower(_zl_hyphen) + if (m == '1' or m == 'yes' or m == 'true' or m == 't') then + Z_HYPHEN = true + end + end +end + + +----------------------------------------------------------------------- +-- initialize clink hooks +----------------------------------------------------------------------- +function z_clink_init() + local once = os.environ("_ZL_ADD_ONCE", false) + local _zl_clink_prompt_priority = os.environ('_ZL_CLINK_PROMPT_PRIORITY', 99) + local previous = '' + function z_add_to_database() + pwd = clink.get_cwd() + if once then + if previous == pwd then + return + end + previous = pwd + end + z_add(clink.get_cwd()) + end + clink.prompt.register_filter(z_add_to_database, _zl_clink_prompt_priority) + function z_match_completion(word) + local M = z_match({word}, Z_METHOD, Z_SUBDIR) + for _, item in pairs(M) do + clink.add_match(item.name) + end + return {} + end + local dirmatchfunc = function (word) + clink.matches_are_files(1) + return clink.match_files(word..'*', true, clink.find_dirs) + end + local dirmatchparser = clink.arg.new_parser():set_arguments({ dirmatchfunc }) + local z_parser = clink.arg.new_parser() + z_parser:set_arguments({ z_match_completion }) + z_parser:set_flags("-r", "-i", "-I", "-t", "-l", "-c", "-e", "-b", "-x"..dirmatchparser, "-h") + if z_parser.adddescriptions then + z_parser:adddescriptions({ + ['-r'] = "cd to highest ranked dir matching", + ['-i'] = "cd with interactive selection", + ['-I'] = "cd with interactive selection using fzf", + ['-t'] = "cd to most recently accessed dir matching", + ['-l'] = "list matches instead of cd", + ['-c'] = "restrict matches to subdirs of cwd (or %PWD% if set)", + ['-e'] = "echo the best match, don't cd", + ['-b'] = "jump backwards to given dir or to project root", + ['-x'] = { " dir", "remove path from history" }, + ['-h'] = "show help", + }) + end + clink.arg.register_parser("z", z_parser) +end + + +----------------------------------------------------------------------- +-- shell scripts +----------------------------------------------------------------------- +local script_zlua = [[ +_zlua() { + local arg_mode="" + local arg_type="" + local arg_subdir="" + local arg_inter="" + local arg_strip="" + if [ "$1" = "--add" ]; then + shift + _ZL_RANDOM="$RANDOM" "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" --add "$@" + return + elif [ "$1" = "--complete" ]; then + shift + "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" --complete "$@" + return + fi + while [ "$1" ]; do + case "$1" in + -l) local arg_mode="-l" ;; + -e) local arg_mode="-e" ;; + -x) local arg_mode="-x" ;; + -t) local arg_type="-t" ;; + -r) local arg_type="-r" ;; + -c) local arg_subdir="-c" ;; + -s) local arg_strip="-s" ;; + -i) local arg_inter="-i" ;; + -I) local arg_inter="-I" ;; + -h|--help) local arg_mode="-h" ;; + --purge) local arg_mode="--purge" ;; + *) break ;; + esac + shift + done + if [ "$arg_mode" = "-h" ] || [ "$arg_mode" = "--purge" ]; then + "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" $arg_mode + elif [ "$arg_mode" = "-l" ] || [ "$#" -eq 0 ]; then + "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" -l $arg_subdir $arg_type $arg_strip "$@" + elif [ -n "$arg_mode" ]; then + "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" $arg_mode $arg_subdir $arg_type $arg_inter "$@" + else + local zdest=$("$ZLUA_LUAEXE" "$ZLUA_SCRIPT" --cd $arg_type $arg_subdir $arg_inter "$@") + if [ -n "$zdest" ] && [ -d "$zdest" ]; then + if [ -z "$_ZL_CD" ]; then + builtin cd "$zdest" + else + $_ZL_CD "$zdest" + fi + if [ -n "$_ZL_ECHO" ]; then pwd; fi + fi + fi +} +# alias ${_ZL_CMD:-z}='_zlua 2>&1' +alias ${_ZL_CMD:-z}='_zlua' +]] + +local script_init_bash = [[ +case "$PROMPT_COMMAND" in + *_zlua?--add*) ;; + *) PROMPT_COMMAND="(_zlua --add \"\$(command pwd 2>/dev/null)\" &)${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;; +esac +]] + +local script_init_bash_fast = [[ +case "$PROMPT_COMMAND" in + *_zlua?--add*) ;; + *) PROMPT_COMMAND="(_zlua --add \"\$PWD\" &)${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;; +esac +]] + +local script_init_bash_once = [[ +_zlua_precmd() { + [ "$_ZL_PREVIOUS_PWD" = "$PWD" ] && return + _ZL_PREVIOUS_PWD="$PWD" + (_zlua --add "$PWD" 2> /dev/null &) +} +case "$PROMPT_COMMAND" in + *_zlua_precmd*) ;; + *) PROMPT_COMMAND="_zlua_precmd${PROMPT_COMMAND:+;$PROMPT_COMMAND}" ;; +esac +]] + +local script_init_posix = [[ +case "$PS1" in + *_zlua?--add*) ;; + *) PS1="\$(_zlua --add \"\$(command pwd 2>/dev/null)\" &)$PS1" +esac +]] + +local script_init_posix_once = [[ +_zlua_precmd() { + [ "$_ZL_PREVIOUS_PWD" = "$PWD" ] && return + _ZL_PREVIOUS_PWD="$PWD" + (_zlua --add "$PWD" 2> /dev/null &) +} +case "$PS1" in + *_zlua_precmd*) ;; + *) PS1="\$(_zlua_precmd)$PS1" +esac +]] + +local script_init_zsh = [[ +_zlua_precmd() { + (_zlua --add "${PWD:a}" &) +} +typeset -ga precmd_functions +[ -n "${precmd_functions[(r)_zlua_precmd]}" ] || { + precmd_functions[$(($#precmd_functions+1))]=_zlua_precmd +} +]] + +local script_init_zsh_once = [[ +_zlua_precmd() { + (_zlua --add "${PWD:a}" &) +} +typeset -ga chpwd_functions +[ -n "${chpwd_functions[(r)_zlua_precmd]}" ] || { + chpwd_functions[$(($#chpwd_functions+1))]=_zlua_precmd +} +]] + +local script_complete_bash = [[ +if [ -n "$BASH_VERSION" ]; then + complete -o filenames -C '_zlua --complete "$COMP_LINE"' ${_ZL_CMD:-z} +fi +]] + +local script_fzf_complete_bash = [[ +if [ "$TERM" != "dumb" ] && command -v fzf >/dev/null 2>&1; then + # To redraw line after fzf closes (printf '\e[5n') + bind '"\e[0n": redraw-current-line' + _zlua_fzf_complete() { + local selected=$(_zlua -l "${COMP_WORDS[@]:1}" | sed "s|$HOME|\~|" | $zlua_fzf | sed 's/^[0-9,.]* *//') + if [ -n "$selected" ]; then + COMPREPLY=( "$selected" ) + fi + printf '\e[5n' + } + complete -o bashdefault -o nospace -F _zlua_fzf_complete ${_ZL_CMD:-z} +fi +]] + +local script_complete_zsh = [[ +_zlua_zsh_tab_completion() { + # tab completion + (( $+compstate )) && compstate[insert]=menu # no expand + local -a tmp=(${(f)"$(_zlua --complete "${words/_zlua/z}")"}) + _describe "directory" tmp -U +} +if [ "${+functions[compdef]}" -ne 0 ]; then + compdef _zlua_zsh_tab_completion _zlua 2> /dev/null + compdef ${_ZL_CMD:-z}=_zlua +fi +]] + +local script_fzf_complete_zsh = [[ +if command -v fzf >/dev/null 2>&1; then + # To redraw line after fzf closes (printf '\e[5n') + bindkey '\e[0n' kill-whole-line + _zlua_zsh_fzf_complete() { + local list=$(_zlua -l ${words[2,-1]}) + + if [ -n "$list" ]; then + local selected=$(print $list | ${=zlua_fzf} | sed 's/^[0-9,.]* *//') + + if [ -n "$selected" ]; then + cd ${selected} + printf '\e[5n' + fi + fi + } + + if [ "${+functions[compdef]}" -ne 0 ]; then + compdef _zlua_zsh_fzf_complete _zlua > /dev/null 2>&1 + compdef ${_ZL_CMD:-z}=_zlua + fi +fi +]] + + +----------------------------------------------------------------------- +-- initialize bash/zsh +---------------------------------------------------------------------- +function z_shell_init(opts) + print('ZLUA_SCRIPT="' .. os.scriptname() .. '"') + print('ZLUA_LUAEXE="' .. os.interpreter() .. '"') + print('') + if not opts.posix then + print(script_zlua) + elseif not opts.legacy then + local script = script_zlua:gsub('builtin ', '') + print(script) + else + local script = script_zlua:gsub('local ', ''):gsub('builtin ', '') + print(script) + end + + local prompt_hook = (not os.environ("_ZL_NO_PROMPT_COMMAND", false)) + local once = os.environ("_ZL_ADD_ONCE", false) or opts.once ~= nil + + if opts.clean ~= nil then + prompt_hook = false + end + + if opts.bash ~= nil then + if prompt_hook then + if once then + print(script_init_bash_once) + elseif opts.fast then + print(script_init_bash_fast) + else + print(script_init_bash) + end + end + print(script_complete_bash) + if opts.fzf ~= nil then + local fzf_cmd = "fzf --nth 2.. --reverse --info=inline --tac " + local height = os.environ('_ZL_FZF_HEIGHT', '35%') + if height ~= nil and height ~= '' and height ~= '0' then + fzf_cmd = fzf_cmd .. ' --height ' .. height .. ' ' + end + local flag = os.environ('_ZL_FZF_FLAG', '') + flag = (flag == '' or flag == nil) and '+s -e' or flag + fzf_cmd = fzf_cmd .. ' ' .. flag .. ' ' + print('zlua_fzf="' .. fzf_cmd .. '"') + print(script_fzf_complete_bash) + end + elseif opts.zsh ~= nil then + if prompt_hook then + print(once and script_init_zsh_once or script_init_zsh) + end + print(script_complete_zsh) + if opts.fzf ~= nil then + local fzf_cmd = "fzf --nth 2.. --reverse --info=inline --tac " + local height = os.environ('_ZL_FZF_HEIGHT', '35%') + if height ~= nil and height ~= '' and height ~= '0' then + fzf_cmd = fzf_cmd .. ' --height ' .. height .. ' ' + end + local flag = os.environ('_ZL_FZF_FLAG', '') + flag = (flag == '' or flag == nil) and '+s -e' or flag + fzf_cmd = fzf_cmd .. ' ' .. flag .. ' ' + print('zlua_fzf="' .. fzf_cmd .. '"') + print(script_fzf_complete_zsh) + end + elseif opts.posix ~= nil then + if prompt_hook then + local script = script_init_posix + if once then script = script_init_posix_once end + if opts.legacy then + script = script:gsub('%&%)', ')') + end + print(script) + end + else + if prompt_hook then + print('if [ -n "$BASH_VERSION" ]; then') + if opts.once then + print(script_init_bash_once) + elseif opts.fast then + print(script_init_bash_fast) + else + print(script_init_bash) + end + print(script_complete_bash) + print('elif [ -n "$ZSH_VERSION" ]; then') + print(once and script_init_zsh_once or script_init_zsh) + -- print(script_complete_zsh) + print('else') + print(once and script_init_posix_once or script_init_posix) + print('builtin() { cd "$2"; }') + print('fi') + end + end + if opts.enhanced ~= nil then + print('export _ZL_MATCH_MODE=1') + end + if opts.nc then + print('export _ZL_NO_CHECK=1') + end + if opts.echo then + print('_ZL_ECHO=1') + end +end + + +----------------------------------------------------------------------- +-- Fish shell init +----------------------------------------------------------------------- +local script_zlua_fish = [[ +function _zlua + set -l arg_mode "" + set -l arg_type "" + set -l arg_subdir "" + set -l arg_inter "" + set -l arg_strip "" + function _zlua_call; eval (string escape -- $argv); end + if test "$argv[1]" = "--add" + set -e argv[1] + set -x _ZL_RANDOM (random) + _zlua_call "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" --add $argv + return + else if test "$argv[1]" = "--complete" + set -e argv[1] + _zlua_call "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" --complete $argv + return + end + while true + switch "$argv[1]" + case "-l"; set arg_mode "-l" + case "-e"; set arg_mode "-e" + case "-x"; set arg_mode "-x" + case "-t"; set arg_type "-t" + case "-r"; set arg_type "-r" + case "-c"; set arg_subdir "-c" + case "-s"; set arg_strip "-s" + case "-i"; set arg_inter "-i" + case "-I"; set arg_inter "-I" + case "-h"; set arg_mode "-h" + case "--help"; set arg_mode "-h" + case "--purge"; set arg_mode "--purge" + case '*'; break + end + set -e argv[1] + end + if test "$arg_mode" = "-h" + _zlua_call "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" -h + else if test "$arg_mode" = "--purge" + _zlua_call "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" --purge + else if test "$arg_mode" = "-l" + _zlua_call "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" -l $arg_subdir $arg_type $arg_strip $argv + else if test (count $argv) -eq 0 + _zlua_call "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" -l $arg_subdir $arg_type $arg_strip $argv + else if test -n "$arg_mode" + _zlua_call "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" $arg_mode $arg_subdir $arg_type $arg_inter $argv + else + set -l dest (_zlua_call "$ZLUA_LUAEXE" "$ZLUA_SCRIPT" --cd $arg_type $arg_subdir $arg_inter $argv) + if test -n "$dest" -a -d "$dest" + if test -z "$_ZL_CD" + builtin cd "$dest" + else + _zlua_call "$_ZL_CD" "$dest" + end + if test -n "$_ZL_ECHO"; pwd; end + end + end +end + +if test -z "$_ZL_CMD"; set -x _ZL_CMD z; end +function $_ZL_CMD -w _zlua -d "alias $_ZL_CMD=_zlua" + _zlua $argv +end +]] + +script_init_fish = [[ +function _zlua_precmd --on-event fish_prompt + _zlua --add "$PWD" 2> /dev/null & +end +]] + +script_init_fish_once = [[ +function _zlua_precmd --on-variable PWD + _zlua --add "$PWD" 2> /dev/null & +end +]] + +script_complete_fish = [[ +function _z_complete + eval "$_ZL_CMD" --complete (commandline -t) +end + +complete -c $_ZL_CMD -f -a '(_z_complete)' +complete -c $_ZL_CMD -s 'r' -d 'cd to highest ranked dir matching' +complete -c $_ZL_CMD -s 'i' -d 'cd with interactive selection' +complete -c $_ZL_CMD -s 'I' -d 'cd with interactive selection using fzf' +complete -c $_ZL_CMD -s 't' -d 'cd to most recently accessed dir matching' +complete -c $_ZL_CMD -s 'l' -d 'list matches instead of cd' +complete -c $_ZL_CMD -s 'c' -d 'restrict matches to subdirs of $PWD' +complete -c $_ZL_CMD -s 'e' -d 'echo the best match, don''t cd' +complete -c $_ZL_CMD -s 'b' -d 'jump backwards to given dir or to project root' +complete -c $_ZL_CMD -s 'x' -x -d 'remove path from history' -a '(_z_complete)' +]] + + +function z_fish_init(opts) + print('set -x ZLUA_SCRIPT "' .. os.scriptname() .. '"') + print('set -x ZLUA_LUAEXE "' .. os.interpreter() .. '"') + local once = (os.getenv("_ZL_ADD_ONCE") ~= nil) or opts.once ~= nil + local prompt_hook = (not os.environ("_ZL_NO_PROMPT_COMMAND", false)) + if opts.clean ~= nil then + prompt_hook = false + end + print(script_zlua_fish) + if prompt_hook then + if once then + print(script_init_fish_once) + else + print(script_init_fish) + end + end + print(script_complete_fish) + if opts.enhanced ~= nil then + print('set -x _ZL_MATCH_MODE 1') + end + if opts.echo then + print('set -g _ZL_ECHO 1') + end + if opts.nc then + print('set -x _ZL_NO_CHECK 1') + end +end + + +----------------------------------------------------------------------- +-- windows .cmd script +----------------------------------------------------------------------- +local script_init_cmd = [[ +set "MatchType=-n" +set "StrictSub=-n" +set "RunMode=-n" +set "StripMode=" +set "InterMode=" +if /i not "%_ZL_LUA_EXE%"=="" ( + set "LuaExe=%_ZL_LUA_EXE%" +) +:parse +if /i "%1"=="-r" ( + set "MatchType=-r" + shift /1 + goto parse +) +if /i "%1"=="-t" ( + set "MatchType=-t" + shift /1 + goto parse +) +if /i "%1"=="-c" ( + set "StrictSub=-c" + shift /1 + goto parse +) +if /i "%1"=="-l" ( + set "RunMode=-l" + shift /1 + goto parse +) +if /i "%1"=="-e" ( + set "RunMode=-e" + shift /1 + goto parse +) +if /i "%1"=="-x" ( + set "RunMode=-x" + shift /1 + goto parse +) +if /i "%1"=="--add" ( + set "RunMode=--add" + shift /1 + goto parse +) +if "%1"=="-i" ( + set "InterMode=-i" + shift /1 + goto parse +) +if "%1"=="-I" ( + set "InterMode=-I" + shift /1 + goto parse +) +if /i "%1"=="-s" ( + set "StripMode=-s" + shift /1 + goto parse +) +if /i "%1"=="-h" ( + call "%LuaExe%" "%LuaScript%" -h + goto end +) +if /i "%1"=="--purge" ( + call "%LuaExe%" "%LuaScript%" --purge + goto end +) +:check +if /i "%1"=="" ( + set "RunMode=-l" +) +for /f "delims=" %%i in ('cd') do set "PWD=%%i" +if /i "%RunMode%"=="-n" ( + for /f "delims=" %%i in ('call "%LuaExe%" "%LuaScript%" --cd %MatchType% %StrictSub% %InterMode% %*') do set "NewPath=%%i" + if not "!NewPath!"=="" ( + if exist !NewPath!\nul ( + if /i not "%_ZL_ECHO%"=="" ( + echo !NewPath! + ) + pushd !NewPath! + pushd !NewPath! + endlocal + goto popdir + ) + ) +) else ( + call "%LuaExe%" "%LuaScript%" "%RunMode%" %MatchType% %StrictSub% %InterMode% %StripMode% %* +) +goto end +:popdir +popd +setlocal +set "NewPath=%CD%" +set "CDCmd=cd /d" +if /i not "%_ZL_CD%"=="" ( + set "CDCmd=%_ZL_CD%" +) +endlocal & popd & %CDCmd% "%NewPath%" +:end +]] + + +----------------------------------------------------------------------- +-- powershell +----------------------------------------------------------------------- +local script_zlua_powershell = [[ +function global:_zlua { + $arg_mode = "" + $arg_type = "" + $arg_subdir = "" + $arg_inter = "" + $arg_strip = "" + if ($args[0] -eq "--add") { + $_, $rest = $args + $env:_ZL_RANDOM = Get-Random + & $script:ZLUA_LUAEXE $script:ZLUA_SCRIPT --add $rest + return + } elseif ($args[0] -eq "--complete") { + $_, $rest = $args + & $script:ZLUA_LUAEXE $script:ZLUA_SCRIPT --complete $rest + return + } elseif ($args[0] -eq "--update") { + $str_pwd = ([string] $PWD) + if ((!$env:_ZL_ADD_ONCE) -or + ($env:_ZL_ADD_ONCE -and ($script:_zlua_previous -ne $str_pwd))) { + $script:_zlua_previous = $str_pwd + _zlua --add $str_pwd + } + return + } + :loop while ($args) { + switch -casesensitive ($args[0]) { + "-l" { $arg_mode = "-l"; break } + "-e" { $arg_mode = "-e"; break } + "-x" { $arg_mode = "-x"; break } + "-t" { $arg_type = "-t"; break } + "-r" { $arg_type = "-r"; break } + "-c" { $arg_subdir="-c"; break } + "-s" { $arg_strip="-s"; break } + "-i" { $arg_inter="-i"; break } + "-I" { $arg_inter="-I"; break } + "-h" { $arg_mode="-h"; break } + "--help" { $arg_mode="-h"; break } + "--purge" { $arg_mode="--purge"; break } + Default { break loop } + } + $_, $args = $args + if (!$args) { break loop } + } + $env:PWD = ([string] $PWD) + if ($arg_mode -eq "-h" -or $arg_mode -eq "--purge") { + & $script:ZLUA_LUAEXE $script:ZLUA_SCRIPT $arg_mode + } elseif ($arg_mode -eq "-l" -or $args.Length -eq 0) { + & $script:ZLUA_LUAEXE $script:ZLUA_SCRIPT -l $arg_subdir $arg_type $arg_strip $args + } elseif ($arg_mode -ne "") { + & $script:ZLUA_LUAEXE $script:ZLUA_SCRIPT $arg_mode $arg_subdir $arg_type $arg_inter $args + } else { + $dest = & $script:ZLUA_LUAEXE $script:ZLUA_SCRIPT --cd $arg_type $arg_subdir $arg_inter $args + if ($dest) { + if ($env:_ZL_CD) { & $env:_ZL_CD "$dest" } + else { & "Push-Location" "$dest" } + if ($env:_ZL_ECHO) { Write-Host $PWD } + } + } +} + +if ($env:_ZL_CMD) { Set-Alias $env:_ZL_CMD _zlua -Scope Global } +else { Set-Alias z _zlua -Scope Global } +]] + +local script_init_powershell = [[ +if (!$env:_ZL_NO_PROMPT_COMMAND -and (!$global:_zlua_inited)) { + $script:_zlua_orig_prompt = ([ref] $function:prompt) + $global:_zlua_inited = $True + function global:prompt { + & $script:_zlua_orig_prompt.value + _zlua --update + } +} +]] + + +----------------------------------------------------------------------- +-- initialize cmd/powershell +----------------------------------------------------------------------- +function z_windows_init(opts) + local prompt_hook = (not os.environ("_ZL_NO_PROMPT_COMMAND", false)) + if opts.clean ~= nil then + prompt_hook = false + end + if opts.powershell ~= nil then + print('$script:ZLUA_LUAEXE = "' .. os.interpreter() .. '"') + print('$script:ZLUA_SCRIPT = "' .. os.scriptname() .. '"') + print(script_zlua_powershell) + if opts.enhanced ~= nil then + print('$env:_ZL_MATCH_MODE = 1') + end + if opts.once ~= nil then + print('$env:_ZL_ADD_ONCE = 1') + end + if opts.echo ~= nil then + print('$env:_ZL_ECHO = 1') + end + if opts.nc ~= nil then + print('$env:_ZL_NO_CHECK = 1') + end + if prompt_hook then + print(script_init_powershell) + end + else + print('@echo off') + print('setlocal EnableDelayedExpansion') + print('set "LuaExe=' .. os.interpreter() .. '"') + print('set "LuaScript=' .. os.scriptname() .. '"') + print(script_init_cmd) + if opts.newline then + print('echo.') + end + end +end + + +----------------------------------------------------------------------- +-- help +----------------------------------------------------------------------- +function z_help() + local cmd = Z_CMD .. ' ' + print(cmd .. 'foo # cd to most frecent dir matching foo') + print(cmd .. 'foo bar # cd to most frecent dir matching foo and bar') + print(cmd .. '-r foo # cd to highest ranked dir matching foo') + print(cmd .. '-t foo # cd to most recently accessed dir matching foo') + print(cmd .. '-l foo # list matches instead of cd') + print(cmd .. '-c foo # restrict matches to subdirs of $PWD') + print(cmd .. '-e foo # echo the best match, don\'t cd') + print(cmd .. '-x path # remove path from history') + print(cmd .. '-i foo # cd with interactive selection') + print(cmd .. '-I foo # cd with interactive selection using fzf') + print(cmd .. '-b foo # cd to the parent directory starting with foo') + print(cmd .. '-b foo bar # replace foo with bar in cwd and cd there') +end + + +----------------------------------------------------------------------- +-- LFS optimize +----------------------------------------------------------------------- +os.lfs = {} +os.lfs.enable = os.getenv('_ZL_USE_LFS') +os.lfs.enable = '1' +if os.lfs.enable ~= nil then + local m = string.lower(os.lfs.enable) + if (m == '1' or m == 'yes' or m == 'true' or m == 't') then + os.lfs.status, os.lfs.pkg = pcall(require, 'lfs') + if os.lfs.status then + local lfs = os.lfs.pkg + os.path.exists = function (name) + return lfs.attributes(name) and true or false + end + os.path.isdir = function (name) + local mode = lfs.attributes(name) + if not mode then + return false + end + return (mode.mode == 'directory') and true or false + end + end + end +end + + +----------------------------------------------------------------------- +-- program entry +----------------------------------------------------------------------- +if not pcall(debug.getlocal, 4, 1) then + -- main script + z_init() + if windows and type(clink) == 'table' and clink.prompt ~= nil then + z_clink_init() + else + main() + end +end + +-- vim: set ts=4 sw=4 tw=0 noet : + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/z.lua.plugin.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/z.lua.plugin.zsh new file mode 100644 index 00000000..f4bcbc05 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/z.lua/z.lua.plugin.zsh @@ -0,0 +1,35 @@ +#! /usr/bin/env zsh + +ZLUA_SCRIPT="${0:A:h}/z.lua" + +if [[ -n "$ZLUA_EXEC" ]] && ! which "$ZLUA_EXEC" &>/dev/null; then + echo "$ZLUA_EXEC not found" + ZLUA_EXEC="" +fi + +# search lua executable +if [[ -z "$ZLUA_EXEC" ]]; then + for lua in lua luajit lua5.4 lua5.3 lua5.2 lua5.1; do + ZLUA_EXEC="$(command -v "$lua")" + [[ -n "$ZLUA_EXEC" ]] && break + done + if [[ -z "$ZLUA_EXEC" ]]; then + echo "Not find lua in your $PATH, please install it." + return + fi +fi + +export _ZL_FZF_FLAG=${_ZL_FZF_FLAG:-"-e"} + +eval "$($ZLUA_EXEC $ZLUA_SCRIPT --init zsh once enhanced fzf)" + +if [[ -z "$_ZL_NO_ALIASES" ]]; then + alias zz='z -i' + alias zc='z -c' + alias zf='z -I' + alias zb='z -b' + alias zbi='z -b -i' + alias zbf='z -b -I' + alias zh='z -I -t .' + alias zzc='zz -c' +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.circleci/config.yml b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.circleci/config.yml new file mode 100644 index 00000000..d95fa98b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.circleci/config.yml @@ -0,0 +1,15 @@ +version: 2 +jobs: + build: + parallelism: 4 + shell: /bin/bash --login + docker: + - image: ericfreese/zsh-autosuggestions-test:latest + steps: + - checkout + - run: + name: Running tests + command: | + for v in $(grep "^[^#]" ZSH_VERSIONS | awk "(NR + $CIRCLE_NODE_INDEX) % $CIRCLE_NODE_TOTAL == 0"); do + TEST_ZSH_BIN=zsh-$v make test || exit 1 + done diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.editorconfig b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.editorconfig new file mode 100644 index 00000000..ddabb17b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.editorconfig @@ -0,0 +1,18 @@ +[*] +charset = utf-8 +end_of_line = lf +insert_final_newline = true +trim_trailing_whitespace = true +indent_style = tab +indent_size = 4 + +[*.md] +indent_style = space + +[*.rb] +indent_style = space +indent_size = 2 + +[*.yml] +indent_style = space +indent_size = 2 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.github/ISSUE_TEMPLATE/bug-report.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.github/ISSUE_TEMPLATE/bug-report.md new file mode 100644 index 00000000..7663df69 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.github/ISSUE_TEMPLATE/bug-report.md @@ -0,0 +1,36 @@ +--- +name: Bug report +about: Create a report to help us improve +title: '' +labels: bug +assignees: '' + +--- + +### Describe the bug + + +### To Reproduce +Steps to reproduce the behavior: + + + +```sh +% zsh -df +% source path/to/zsh-autosuggestions.zsh +% ... # what do you do to reproduce? +``` + +### Expected behavior + + +### Screenshots + + +### Desktop + - OS + distribution: + - Zsh version: + - Plugin version: + +### Additional context + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.github/ISSUE_TEMPLATE/feature_request.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.github/ISSUE_TEMPLATE/feature_request.md new file mode 100644 index 00000000..58746253 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.github/ISSUE_TEMPLATE/feature_request.md @@ -0,0 +1,20 @@ +--- +name: Feature request +about: Suggest an idea for this project +title: '' +labels: enhancement +assignees: '' + +--- + +### Is your feature request related to a problem? Please describe. + + +### Describe the solution you'd like + + +### Describe alternatives you've considered + + +### Additional context + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.gitignore b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.gitignore new file mode 100644 index 00000000..d8decde3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.gitignore @@ -0,0 +1,2 @@ +# zsh word code files +*.zwc diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.rspec b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.rspec new file mode 100644 index 00000000..43ae2036 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.rspec @@ -0,0 +1,3 @@ +--color +--require spec_helper +--format documentation diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.rubocop.yml b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.rubocop.yml new file mode 100644 index 00000000..97facac8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.rubocop.yml @@ -0,0 +1,30 @@ +# Rails: +# Enabled: true + +AllCops: + TargetRubyVersion: 2.3 + Include: + - '**/Rakefile' + - '**/config.ru' + - '**/Gemfile' + +Metrics/LineLength: + Max: 120 + +Style/Documentation: + Enabled: false + +Style/DotPosition: + EnforcedStyle: trailing + +Style/FrozenStringLiteralComment: + Enabled: false + +Style/Lambda: + Enabled: false + +Style/MultilineMethodCallIndentation: + EnforcedStyle: indented + +Style/TrailingUnderscoreVariable: + Enabled: false diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.ruby-version b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.ruby-version new file mode 100644 index 00000000..aedc15bb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/.ruby-version @@ -0,0 +1 @@ +2.5.3 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/CHANGELOG.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/CHANGELOG.md new file mode 100644 index 00000000..15d65a98 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/CHANGELOG.md @@ -0,0 +1,117 @@ +# Changelog + +## v0.7.0 +- Enable asynchronous mode by default (#498) +- No longer wrap user widgets starting with `autosuggest-` prefix (#496) +- Fix a bug wrapping widgets that modify the buffer (#541) + + +## v0.6.4 +- Fix `vi-forward-char` triggering a bell when using it to accept a suggestion (#488) +- New configuration option to skip completion suggestions when buffer matches a pattern (#487) +- New configuration option to ignore history entries matching a pattern (#456) + +## v0.6.3 +- Fixed bug moving cursor to end of buffer after accepting suggestion (#453) + +## v0.6.2 +- Fixed bug deleting the last character in the buffer in vi mode (#450) +- Degrade gracefully when user doesn't have `zsh/system` module installed (#447) + +## v0.6.1 +- Fixed bug occurring when `_complete` had been aliased (#443) + +## v0.6.0 +- Added `completion` suggestion strategy powered by completion system (#111) +- Allow setting `ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE` to an empty string (#422) +- Don't fetch suggestions after copy-earlier-word (#439) +- Allow users to unignore zle-\* widgets (e.g. zle-line-init) (#432) + + +## v0.5.2 +- Allow disabling automatic widget re-binding for better performance (#418) +- Fix async suggestions when `SH_WORD_SPLIT` is set +- Refactor async mode to use process substitution instead of zpty (#417) + +## v0.5.1 +- Speed up widget rebinding (#413) +- Clean up global variable creations (#403) +- Respect user's set options when running original widget (#402) + +## v0.5.0 +- Don't overwrite config with default values (#335) +- Support fallback strategies by supplying array to suggestion config var +- Rename "default" suggestion strategy to "history" to name it based on what it actually does +- Reset opts in some functions affected by `GLOB_SUBST` (#334) +- Support widgets starting with dashes (ex: `-a-widget`) (#337) +- Skip async tests in zsh versions less than 5.0.8 because of reliability issues +- Fix handling of newline + carriage return in async pty (#333) + + +## v0.4.3 +- Avoid bell when accepting suggestions with `autosuggest-accept` (#228) +- Don't fetch suggestions after [up,down]-line-or-beginning-search (#227, #241) +- We are now running CI against new 5.5.1 version +- Fix partial-accept in vi mode (#188) +- Fix suggestion disappearing on fast movement after switching to `vicmd` mode (#290) +- Fix issue rotating through kill ring with `yank-pop` (#301) +- Fix issue creating new pty for async mode when previous pty is not properly cleaned up (#249) + +## v0.4.2 +- Fix bug in zsh versions older than 5.0.8 (#296) +- Officially support back to zsh v4.3.11 + +## v0.4.1 +- Switch to [[ and (( conditionals instead of [ (#257) +- Avoid warnnestedvar warnings with `typeset -g` (#275) +- Replace tabs with spaces in yaml (#268) +- Clean up and fix escaping of special characters (#267) +- Add `emacs-forward-word` to default list of partial accept widgets (#246) + +## v0.4.0 +- High-level integration tests using RSpec and tmux +- Add continuous integration with Circle CI +- Experimental support for asynchronous suggestions (#170) +- Fix problems with multi-line suggestions (#225) +- Optimize case where manually typing in suggestion +- Avoid wrapping any zle-\* widgets (#206) +- Remove support for deprecated options from v0.0.x +- Handle history entries that begin with dashes +- Gracefully handle being sourced multiple times (#126) +- Add enable/disable/toggle widgets to disable/enable suggestions (#219) + + +## v0.3.3 +- Switch from $history array to fc builtin for better performance with large HISTFILEs (#164) +- Fix tilde handling when extended_glob is set (#168) +- Add config option for maximum buffer length to fetch suggestions for (#178) +- Add config option for list of widgets to ignore (#184) +- Don't fetch a new suggestion unless a modification widget actually modifies the buffer (#183) + +## v0.3.2 +- Test runner now supports running specific tests and choosing zsh binary +- Return code from original widget is now correctly passed through (#135) +- Add `vi-add-eol` to list of accept widgets (#143) +- Escapes widget names within evals to fix problems with irregular widget names (#152) +- Plugin now clears suggestion while within a completion menu (#149) +- .plugin file no longer relies on symbolic link support, fixing issues on Windows (#156) + +## v0.3.1 + +- Fixes issue with `vi-next-char` not accepting suggestion (#137). +- Fixes global variable warning when WARN_CREATE_GLOBAL option enabled (#133). +- Split out a separate test file for each widget. + +## v0.3.0 + +- Adds `autosuggest-execute` widget (PR #124). +- Adds concept of suggestion "strategies" for different ways of fetching suggestions. +- Adds "match_prev_cmd" strategy (PR #131). +- Uses git submodules for testing dependencies. +- Lots of test cleanup. +- Various bug fixes for zsh 5.0.x and `sh_word_split` option. + + +## v0.2.17 + +Start of changelog. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/DESCRIPTION b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/DESCRIPTION new file mode 100644 index 00000000..b69200fc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/DESCRIPTION @@ -0,0 +1 @@ +Fish-like fast/unobtrusive autosuggestions for zsh. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/Dockerfile b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/Dockerfile new file mode 100644 index 00000000..0d51407c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/Dockerfile @@ -0,0 +1,20 @@ +FROM ruby:2.5.3-alpine + +RUN apk add --no-cache autoconf +RUN apk add --no-cache libtool +RUN apk add --no-cache libcap-dev +RUN apk add --no-cache pcre-dev +RUN apk add --no-cache curl +RUN apk add --no-cache build-base +RUN apk add --no-cache ncurses-dev +RUN apk add --no-cache tmux + +WORKDIR /zsh-autosuggestions + +ADD ZSH_VERSIONS /zsh-autosuggestions/ZSH_VERSIONS +ADD install_test_zsh.sh /zsh-autosuggestions/install_test_zsh.sh +RUN ./install_test_zsh.sh + +ADD Gemfile /zsh-autosuggestions/Gemfile +ADD Gemfile.lock /zsh-autosuggestions/Gemfile.lock +RUN bundle install diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/Gemfile b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/Gemfile new file mode 100644 index 00000000..8b5deecf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/Gemfile @@ -0,0 +1,5 @@ +source 'https://rubygems.org' + +gem 'rspec' +gem 'rspec-wait' +gem 'pry-byebug' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/Gemfile.lock b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/Gemfile.lock new file mode 100644 index 00000000..63ee778a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/Gemfile.lock @@ -0,0 +1,41 @@ +GEM + remote: https://rubygems.org/ + specs: + byebug (9.0.5) + coderay (1.1.1) + diff-lcs (1.3) + method_source (0.8.2) + pry (0.10.4) + coderay (~> 1.1.0) + method_source (~> 0.8.1) + slop (~> 3.4) + pry-byebug (3.4.0) + byebug (~> 9.0) + pry (~> 0.10) + rspec (3.5.0) + rspec-core (~> 3.5.0) + rspec-expectations (~> 3.5.0) + rspec-mocks (~> 3.5.0) + rspec-core (3.5.4) + rspec-support (~> 3.5.0) + rspec-expectations (3.5.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.5.0) + rspec-mocks (3.5.0) + diff-lcs (>= 1.2.0, < 2.0) + rspec-support (~> 3.5.0) + rspec-support (3.5.0) + rspec-wait (0.0.9) + rspec (>= 3, < 4) + slop (3.6.0) + +PLATFORMS + ruby + +DEPENDENCIES + pry-byebug + rspec + rspec-wait + +BUNDLED WITH + 1.13.6 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/INSTALL.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/INSTALL.md new file mode 100644 index 00000000..7b32af1b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/INSTALL.md @@ -0,0 +1,81 @@ +# Installation + +* [Packages](#packages) +* [Antigen](#antigen) +* [Oh My Zsh](#oh-my-zsh) +* [HomeBrew](#homebrew) +* [Manual](#manual-git-clone) + +## Packages + +| System | Package | +| ------------- | ------------- | +| Alpine Linux | [zsh-autosuggestions](https://pkgs.alpinelinux.org/packages?name=zsh-autosuggestions) | +| Debian / Ubuntu | [zsh-autosuggestions OBS repository](https://software.opensuse.org/download.html?project=shells%3Azsh-users%3Azsh-autosuggestions&package=zsh-autosuggestions) | +| Fedora / CentOS / RHEL / Scientific Linux | [zsh-autosuggestions OBS repository](https://software.opensuse.org/download.html?project=shells%3Azsh-users%3Azsh-autosuggestions&package=zsh-autosuggestions) | +| OpenSUSE / SLE | [zsh-autosuggestions OBS repository](https://software.opensuse.org/download.html?project=shells%3Azsh-users%3Azsh-autosuggestions&package=zsh-autosuggestions) | +| Arch Linux / Manjaro / Antergos / Hyperbola | [zsh-autosuggestions](https://www.archlinux.org/packages/zsh-autosuggestions), [zsh-autosuggestions-git](https://aur.archlinux.org/packages/zsh-autosuggestions-git) | +| NixOS | [zsh-autosuggestions](https://github.com/NixOS/nixpkgs/blob/master/pkgs/shells/zsh/zsh-autosuggestions/default.nix) | +| Void Linux | [zsh-autosuggestions](https://github.com/void-linux/void-packages/blob/master/srcpkgs/zsh-autosuggestions/template) | +| Mac OS | [homebrew](https://github.com/Homebrew/homebrew-core/blob/master/Formula/z/zsh-autosuggestions.rb) | +| NetBSD | [pkgsrc](http://ftp.netbsd.org/pub/pkgsrc/current/pkgsrc/shells/zsh-autosuggestions/README.html) | + +## Antigen + +1. Add the following to your `.zshrc`: + + ```sh + antigen bundle zsh-users/zsh-autosuggestions + ``` + +2. Start a new terminal session. + +## Oh My Zsh + +1. Clone this repository into `$ZSH_CUSTOM/plugins` (by default `~/.oh-my-zsh/custom/plugins`) + + ```sh + git clone https://github.com/zsh-users/zsh-autosuggestions ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-autosuggestions + ``` + +2. Add the plugin to the list of plugins for Oh My Zsh to load (inside `~/.zshrc`): + + ```sh + plugins=( + # other plugins... + zsh-autosuggestions + ) + ``` + +3. Start a new terminal session. + +## Homebrew + +1. Install command: + ```sh + brew install zsh-autosuggestions + ``` + +2. To activate the autosuggestions, add the following at the end of your .zshrc: + + ```sh + source $(brew --prefix)/share/zsh-autosuggestions/zsh-autosuggestions.zsh + ``` + +3. Start a new terminal session. + +## Manual (Git Clone) + +1. Clone this repository somewhere on your machine. This guide will assume `~/.zsh/zsh-autosuggestions`. + + ```sh + git clone https://github.com/zsh-users/zsh-autosuggestions ~/.zsh/zsh-autosuggestions + ``` + +2. Add the following to your `.zshrc`: + + ```sh + source ~/.zsh/zsh-autosuggestions/zsh-autosuggestions.zsh + ``` + +3. Start a new terminal session. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/LICENSE b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/LICENSE new file mode 100644 index 00000000..7ea78cc6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/LICENSE @@ -0,0 +1,23 @@ +Copyright (c) 2013 Thiago de Arruda +Copyright (c) 2016-2021 Eric Freese + +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. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/Makefile b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/Makefile new file mode 100644 index 00000000..6f5431e7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/Makefile @@ -0,0 +1,35 @@ +SRC_DIR := ./src + +SRC_FILES := \ + $(SRC_DIR)/config.zsh \ + $(SRC_DIR)/util.zsh \ + $(SRC_DIR)/bind.zsh \ + $(SRC_DIR)/highlight.zsh \ + $(SRC_DIR)/widgets.zsh \ + $(SRC_DIR)/strategies/*.zsh \ + $(SRC_DIR)/fetch.zsh \ + $(SRC_DIR)/async.zsh \ + $(SRC_DIR)/start.zsh + +HEADER_FILES := \ + DESCRIPTION \ + URL \ + VERSION \ + LICENSE + +PLUGIN_TARGET := zsh-autosuggestions.zsh + +all: $(PLUGIN_TARGET) + +$(PLUGIN_TARGET): $(HEADER_FILES) $(SRC_FILES) + cat $(HEADER_FILES) | sed -e 's/^/# /g' > $@ + cat $(SRC_FILES) >> $@ + +.PHONY: clean +clean: + rm $(PLUGIN_TARGET) + +.PHONY: test +test: all + @test -n "$$TEST_ZSH_BIN" && echo "Testing zsh binary: $(TEST_ZSH_BIN)" || true + bundle exec rspec $(TESTS) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/README.md new file mode 100644 index 00000000..94e0b58c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/README.md @@ -0,0 +1,191 @@ +# zsh-autosuggestions + +_[Fish](http://fishshell.com/)-like fast/unobtrusive autosuggestions for zsh._ + +It suggests commands as you type based on history and completions. + +Requirements: Zsh v4.3.11 or later + +[![CircleCI](https://img.shields.io/circleci/build/github/zsh-users/zsh-autosuggestions.svg)](https://circleci.com/gh/zsh-users/zsh-autosuggestions) +[![Chat on Gitter](https://img.shields.io/gitter/room/zsh-users/zsh-autosuggestions.svg)](https://gitter.im/zsh-users/zsh-autosuggestions) + + + + +## Installation + +See [INSTALL.md](INSTALL.md). + + +## Usage + +As you type commands, you will see a completion offered after the cursor in a muted gray color. This color can be changed by setting the `ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE` variable. See [configuration](#configuration). + +If you press the key (`forward-char` widget) or End (`end-of-line` widget) with the cursor at the end of the buffer, it will accept the suggestion, replacing the contents of the command line buffer with the suggestion. + +If you invoke the `forward-word` widget, it will partially accept the suggestion up to the point that the cursor moves to. + + +## Configuration + +You may want to override the default global config variables. Default values of these variables can be found [here](src/config.zsh). + +**Note:** If you are using Oh My Zsh, you can put this configuration in a file in the `$ZSH_CUSTOM` directory. See their comments on [overriding internals](https://github.com/robbyrussell/oh-my-zsh/wiki/Customization#overriding-internals). + + +### Suggestion Highlight Style + +Set `ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE` to configure the style that the suggestion is shown with. The default is `fg=8`, which will set the foreground color to color 8 from the [256-color palette](https://upload.wikimedia.org/wikipedia/commons/1/15/Xterm_256color_chart.svg). If your terminal only supports 8 colors, you will need to use a number between 0 and 7. + +Background color can also be set, and the suggestion can be styled bold, underlined, or standout. For example, this would show suggestions with bold, underlined, pink text on a cyan background: + +```sh +ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE="fg=#ff00ff,bg=cyan,bold,underline" +``` + +For more info, read the Character Highlighting section of the zsh manual: `man zshzle` or [online](http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting). + +**Note:** Some iTerm2 users have reported [not being able to see the suggestions](https://github.com/zsh-users/zsh-autosuggestions/issues/416#issuecomment-486516333). If this affects you, the problem is likely caused by incorrect color settings. In order to correct this, go into iTerm2's setting, navigate to profile > colors and make sure that the colors for Basic Colors > Background and ANSI Colors > Bright Black are **different**. + + +### Suggestion Strategy + +`ZSH_AUTOSUGGEST_STRATEGY` is an array that specifies how suggestions should be generated. The strategies in the array are tried successively until a suggestion is found. There are currently three built-in strategies to choose from: + +- `history`: Chooses the most recent match from history. +- `completion`: Chooses a suggestion based on what tab-completion would suggest. (requires `zpty` module, which is included with zsh since 4.0.1) +- `match_prev_cmd`: Like `history`, but chooses the most recent match whose preceding history item matches the most recently executed command ([more info](src/strategies/match_prev_cmd.zsh)). Note that this strategy won't work as expected with ZSH options that don't preserve the history order such as `HIST_IGNORE_ALL_DUPS` or `HIST_EXPIRE_DUPS_FIRST`. + +For example, setting `ZSH_AUTOSUGGEST_STRATEGY=(history completion)` will first try to find a suggestion from your history, but, if it can't find a match, will find a suggestion from the completion engine. + + +### Widget Mapping + +This plugin works by triggering custom behavior when certain [zle widgets](http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Zle-Widgets) are invoked. You can add and remove widgets from these arrays to change the behavior of this plugin: + +- `ZSH_AUTOSUGGEST_CLEAR_WIDGETS`: Widgets in this array will clear the suggestion when invoked. +- `ZSH_AUTOSUGGEST_ACCEPT_WIDGETS`: Widgets in this array will accept the suggestion when invoked. +- `ZSH_AUTOSUGGEST_EXECUTE_WIDGETS`: Widgets in this array will execute the suggestion when invoked. +- `ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS`: Widgets in this array will partially accept the suggestion when invoked. +- `ZSH_AUTOSUGGEST_IGNORE_WIDGETS`: Widgets in this array will not trigger any custom behavior. + +Widgets that modify the buffer and are not found in any of these arrays will fetch a new suggestion after they are invoked. + +**Note:** A widget shouldn't belong to more than one of the above arrays. + + +### Disabling suggestion for large buffers + +Set `ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE` to an integer value to disable autosuggestion for large buffers. The default is unset, which means that autosuggestion will be tried for any buffer size. Recommended value is 20. +This can be useful when pasting large amount of text in the terminal, to avoid triggering autosuggestion for strings that are too long. + +### Asynchronous Mode + +Suggestions are fetched asynchronously by default in zsh versions 5.0.8 and greater. To disable asynchronous suggestions and fetch them synchronously instead, `unset ZSH_AUTOSUGGEST_USE_ASYNC` after sourcing the plugin. + +Alternatively, if you are using a version of zsh older than 5.0.8 and want to enable asynchronous mode, set the `ZSH_AUTOSUGGEST_USE_ASYNC` variable after sourcing the plugin (it can be set to anything). Note that there is [a bug](https://github.com/zsh-users/zsh-autosuggestions/issues/364#issuecomment-481423232) in versions of zsh older than 5.0.8 where ctrl + c will fail to reset the prompt immediately after fetching a suggestion asynchronously. + +### Disabling automatic widget re-binding + +Set `ZSH_AUTOSUGGEST_MANUAL_REBIND` (it can be set to anything) to disable automatic widget re-binding on each precmd. This can be a big boost to performance, but you'll need to handle re-binding yourself if any of the widget lists change or if you or another plugin wrap any of the autosuggest widgets. To re-bind widgets, run `_zsh_autosuggest_bind_widgets`. + +### Ignoring history suggestions that match a pattern + +Set `ZSH_AUTOSUGGEST_HISTORY_IGNORE` to a [glob pattern](http://zsh.sourceforge.net/Doc/Release/Expansion.html#Glob-Operators) to prevent offering suggestions for history entries that match the pattern. For example, set it to `"cd *"` to never suggest any `cd` commands from history. Or set to `"?(#c50,)"` to never suggest anything 50 characters or longer. + +**Note:** This only affects the `history` and `match_prev_cmd` suggestion strategies. + +### Skipping completion suggestions for certain cases + +Set `ZSH_AUTOSUGGEST_COMPLETION_IGNORE` to a [glob pattern](http://zsh.sourceforge.net/Doc/Release/Expansion.html#Glob-Operators) to prevent offering completion suggestions when the buffer matches that pattern. For example, set it to `"git *"` to disable completion suggestions for git subcommands. + +**Note:** This only affects the `completion` suggestion strategy. + + +### Key Bindings + +This plugin provides a few widgets that you can use with `bindkey`: + +1. `autosuggest-accept`: Accepts the current suggestion. +2. `autosuggest-execute`: Accepts and executes the current suggestion. +3. `autosuggest-clear`: Clears the current suggestion. +4. `autosuggest-fetch`: Fetches a suggestion (works even when suggestions are disabled). +5. `autosuggest-disable`: Disables suggestions. +6. `autosuggest-enable`: Re-enables suggestions. +7. `autosuggest-toggle`: Toggles between enabled/disabled suggestions. + +For example, this would bind ctrl + space to accept the current suggestion. + +```sh +bindkey '^ ' autosuggest-accept +``` + + +## Troubleshooting + +If you have a problem, please search through [the list of issues on GitHub](https://github.com/zsh-users/zsh-autosuggestions/issues?q=) to see if someone else has already reported it. + +### Reporting an Issue + +Before reporting an issue, please try temporarily disabling sections of your configuration and other plugins that may be conflicting with this plugin to isolate the problem. + +When reporting an issue, please include: + +- The smallest, simplest `.zshrc` configuration that will reproduce the problem. See [this comment](https://github.com/zsh-users/zsh-autosuggestions/issues/102#issuecomment-180944764) for a good example of what this means. +- The version of zsh you're using (`zsh --version`) +- Which operating system you're running + + +## Uninstallation + +1. Remove the code referencing this plugin from `~/.zshrc`. + +2. Remove the git repository from your hard drive + + ```sh + rm -rf ~/.zsh/zsh-autosuggestions # Or wherever you installed + ``` + + +## Development + +### Build Process + +Edit the source files in `src/`. Run `make` to build `zsh-autosuggestions.zsh` from those source files. + + +### Pull Requests + +Pull requests are welcome! If you send a pull request, please: + +- Request to merge into the `develop` branch (*NOT* `master`) +- Match the existing coding conventions. +- Include helpful comments to keep the barrier-to-entry low for people new to the project. +- Write tests that cover your code as much as possible. + + +### Testing + +Tests are written in ruby using the [`rspec`](http://rspec.info/) framework. They use [`tmux`](https://tmux.github.io/) to drive a pseudoterminal, sending simulated keystrokes and making assertions on the terminal content. + +Test files live in `spec/`. To run the tests, run `make test`. To run a specific test, run `TESTS=spec/some_spec.rb make test`. You can also specify a `zsh` binary to use by setting the `TEST_ZSH_BIN` environment variable (ex: `TEST_ZSH_BIN=/bin/zsh make test`). + +A docker image for testing is available [on docker hub](https://hub.docker.com/r/ericfreese/zsh-autosuggestions-test). It comes with ruby, the bundler dependencies, and all supported versions of zsh installed. + +Pull the docker image with: + +```sh +docker pull ericfreese/zsh-autosuggestions-test +``` + +To run the tests for a specific version of zsh (where `` below is substituted with the contents of a line from the [`ZSH_VERSIONS`](ZSH_VERSIONS) file): + +```sh +docker run -it -e TEST_ZSH_BIN=zsh- -v $PWD:/zsh-autosuggestions zsh-autosuggestions-test make test +``` + + +## License + +This project is licensed under [MIT license](http://opensource.org/licenses/MIT). +For the full text of the license, see the [LICENSE](LICENSE) file. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/URL b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/URL new file mode 100644 index 00000000..4e2bd941 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/URL @@ -0,0 +1 @@ +https://github.com/zsh-users/zsh-autosuggestions diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/VERSION b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/VERSION new file mode 100644 index 00000000..8b20e485 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/VERSION @@ -0,0 +1 @@ +v0.7.0 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/ZSH_VERSIONS b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/ZSH_VERSIONS new file mode 100644 index 00000000..18ed7a62 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/ZSH_VERSIONS @@ -0,0 +1,17 @@ +# Zsh releases to run tests against +# See https://github.com/zsh-users/zsh/releases +# +# When modifying this file, rebuild and push docker image: +# $ docker build -t ericfreese/zsh-autosuggestions-test . +# $ docker push ericfreese/zsh-autosuggestions-test +4.3.11 +5.0.2 +5.0.8 +5.1.1 +5.2 +5.3.1 +5.4.2 +5.5.1 +5.6.2 +5.7.1 +5.8 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/install_test_zsh.sh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/install_test_zsh.sh new file mode 100755 index 00000000..40dc4c56 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/install_test_zsh.sh @@ -0,0 +1,26 @@ +#!/bin/sh + +set -ex + +for v in $(grep "^[^#]" ZSH_VERSIONS); do + mkdir zsh-$v + cd zsh-$v + + curl -L https://api.github.com/repos/zsh-users/zsh/tarball/zsh-$v | tar xz --strip=1 + + ./Util/preconfig + ./configure --enable-pcre \ + --enable-cap \ + --enable-multibyte \ + --with-term-lib='ncursesw tinfo' \ + --with-tcsetpgrp \ + --program-suffix="-$v" + + make install.bin + make install.modules + make install.fns + + cd .. + + rm -rf zsh-$v +done diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/async_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/async_spec.rb new file mode 100644 index 00000000..0af72329 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/async_spec.rb @@ -0,0 +1,70 @@ +context 'with asynchronous suggestions enabled' do + let(:options) { ["ZSH_AUTOSUGGEST_USE_ASYNC="] } + + describe '`up-line-or-beginning-search`' do + let(:before_sourcing) do + -> do + session. + run_command('autoload -U up-line-or-beginning-search'). + run_command('zle -N up-line-or-beginning-search'). + send_string('bindkey "'). + send_keys('C-v').send_keys('up'). + send_string('" up-line-or-beginning-search'). + send_keys('enter') + end + end + + it 'should show previous history entries' do + with_history( + 'echo foo', + 'echo bar', + 'echo baz' + ) do + session.clear_screen + 3.times { session.send_keys('up') } + wait_for { session.content }.to eq("echo foo") + end + end + end + + describe '`copy-earlier-word`' do + let(:before_sourcing) do + -> do + session. + run_command('autoload -Uz copy-earlier-word'). + run_command('zle -N copy-earlier-word'). + run_command('bindkey "^N" copy-earlier-word') + end + end + + it 'should cycle through previous words in the buffer' do + session.clear_screen + session.send_string('foo bar baz') + sleep 0.5 + session.send_keys('C-n') + wait_for { session.content }.to eq('foo bar bazbaz') + session.send_keys('C-n') + wait_for { session.content }.to eq('foo bar bazbar') + session.send_keys('C-n') + wait_for { session.content }.to eq('foo bar bazfoo') + end + end + + describe 'pressing ^C after fetching a suggestion' do + before do + skip 'Workaround does not work below v5.0.8' if session.zsh_version < Gem::Version.new('5.0.8') + end + + it 'terminates the prompt and begins a new one' do + session.send_keys('e') + sleep 0.5 + session.send_keys('C-c') + sleep 0.5 + session.send_keys('echo') + + wait_for { session.content }.to eq("e\necho") + end + end +end + + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/auto_cd_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/auto_cd_spec.rb new file mode 100644 index 00000000..94bd24b0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/auto_cd_spec.rb @@ -0,0 +1,14 @@ +describe 'with `AUTO_CD` option set' do + let(:after_sourcing) do + -> { + session.run_command('setopt AUTO_CD') + session.run_command('autoload compinit && compinit') + } + end + + it 'directory names are still completed' do + session.send_string('sr') + session.send_keys('C-i') + wait_for { session.content }.to eq('src/') + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/bracketed_paste_magic_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/bracketed_paste_magic_spec.rb new file mode 100644 index 00000000..41ff2676 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/bracketed_paste_magic_spec.rb @@ -0,0 +1,43 @@ +describe 'pasting using bracketed-paste-magic' do + let(:before_sourcing) do + -> do + session. + run_command('autoload -Uz bracketed-paste-magic'). + run_command('zle -N bracketed-paste bracketed-paste-magic') + end + end + + context 'with suggestions disabled while pasting' do + before do + session. + run_command('bpm_init() { zle autosuggest-disable }'). + run_command('bpm_finish() { zle autosuggest-enable }'). + run_command('zstyle :bracketed-paste-magic paste-init bpm_init'). + run_command('zstyle :bracketed-paste-magic paste-finish bpm_finish') + end + + it 'does not show an incorrect suggestion' do + with_history('echo hello') do + session.paste_string("echo #{'a' * 60}") + sleep 1 + expect(session.content).to eq("echo #{'a' * 60}") + end + end + end + + context 'with `bracketed-paste` added to the list of widgets that clear the suggestion' do + let(:options) { ['ZSH_AUTOSUGGEST_CLEAR_WIDGETS+=(bracketed-paste)'] } + + it 'does not retain an old suggestion' do + with_history ('echo foo') do + session.send_string('echo ') + wait_for { session.content }.to eq('echo foo') + session.paste_string('bar') + wait_for { session.content }.to eq('echo bar') + session.send_keys('C-a') # Any cursor movement works + sleep 1 + expect(session.content).to eq('echo bar') + end + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/client_zpty_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/client_zpty_spec.rb new file mode 100644 index 00000000..b8abb375 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/client_zpty_spec.rb @@ -0,0 +1,14 @@ +describe 'a running zpty command' do + let(:before_sourcing) { -> { session.run_command('zmodload zsh/zpty && zpty -b kitty cat') } } + + context 'when using `completion` strategy' do + let(:options) { ["ZSH_AUTOSUGGEST_STRATEGY=completion"] } + + it 'is not affected' do + session.send_keys('a').send_keys('C-h') + session.run_command('zpty -t kitty; echo $?') + + wait_for { session.content }.to end_with("\n0") + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/glob_subst_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/glob_subst_spec.rb new file mode 100644 index 00000000..c3dd671c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/glob_subst_spec.rb @@ -0,0 +1,12 @@ +describe 'with `GLOB_SUBST` option set' do + let(:after_sourcing) do + -> { + session.run_command('setopt GLOB_SUBST') + } + end + + it 'error messages are not printed' do + session.send_string('[[') + wait_for { session.content }.to eq('[[') + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/rebound_bracket_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/rebound_bracket_spec.rb new file mode 100644 index 00000000..8b420f06 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/rebound_bracket_spec.rb @@ -0,0 +1,13 @@ +describe 'rebinding [' do + context 'initialized before sourcing the plugin' do + before do + session.run_command("function [ { $commands[\\[] \"$@\" }") + session.clear_screen + end + + it 'executes the custom behavior and the built-in behavior' do + session.send_string('asdf') + wait_for { session.content }.to eq('asdf') + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/vi_mode_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/vi_mode_spec.rb new file mode 100644 index 00000000..0a295c23 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/vi_mode_spec.rb @@ -0,0 +1,80 @@ +describe 'when using vi mode' do + let(:before_sourcing) do + -> do + session.run_command('bindkey -v') + end + end + + describe 'moving the cursor after exiting insert mode' do + it 'should not clear the current suggestion' do + with_history('foobar foo') do + session. + send_string('foo'). + send_keys('escape'). + send_keys('h') + + wait_for { session.content }.to eq('foobar foo') + end + end + end + + describe '`vi-forward-word-end`' do + it 'should accept through the end of the current word' do + with_history('foobar foo') do + session. + send_string('foo'). + send_keys('escape'). + send_keys('e'). # vi-forward-word-end + send_keys('a'). # vi-add-next + send_string('baz') + + wait_for { session.content }.to eq('foobarbaz') + end + end + end + + describe '`vi-forward-word`' do + it 'should accept through the first character of the next word' do + with_history('foobar foo') do + session. + send_string('foo'). + send_keys('escape'). + send_keys('w'). # vi-forward-word + send_keys('a'). # vi-add-next + send_string('az') + + wait_for { session.content }.to eq('foobar faz') + end + end + end + + describe '`vi-find-next-char`' do + it 'should accept through the next occurrence of the character' do + with_history('foobar foo') do + session. + send_string('foo'). + send_keys('escape'). + send_keys('f'). # vi-find-next-char + send_keys('o'). + send_keys('a'). # vi-add-next + send_string('b') + + wait_for { session.content }.to eq('foobar fob') + end + end + end + + describe '`vi-delete`' do + it 'should be able to remove the last character in the buffer' do + skip 'deleting last char did not work below zsh version 5.0.8' if session.zsh_version < Gem::Version.new('5.0.8') + + session. + send_string('echo foo'). + send_keys('escape'). + send_keys('d'). + send_keys('l') + + wait_for { session.content }.to eq('echo fo') + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/wrapped_widget_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/wrapped_widget_spec.rb new file mode 100644 index 00000000..61dfc2dc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/wrapped_widget_spec.rb @@ -0,0 +1,39 @@ +describe 'a wrapped widget' do + let(:widget) { 'backward-delete-char' } + + context 'initialized before sourcing the plugin' do + let(:before_sourcing) do + -> do + session. + run_command("_orig_#{widget}() { zle .#{widget} }"). + run_command("zle -N orig-#{widget} _orig_#{widget}"). + run_command("#{widget}-magic() { zle orig-#{widget}; BUFFER+=b }"). + run_command("zle -N #{widget} #{widget}-magic") + end + end + + it 'executes the custom behavior and the built-in behavior' do + with_history('foobar', 'foodar') do + session.send_string('food').send_keys('C-h') + wait_for { session.content }.to eq('foobar') + end + end + end + + context 'initialized after sourcing the plugin' do + before do + session. + run_command("zle -N orig-#{widget} ${widgets[#{widget}]#*:}"). + run_command("#{widget}-magic() { zle orig-#{widget}; BUFFER+=b }"). + run_command("zle -N #{widget} #{widget}-magic"). + clear_screen + end + + it 'executes the custom behavior and the built-in behavior' do + with_history('foobar', 'foodar') do + session.send_string('food').send_keys('C-h') + wait_for { session.content }.to eq('foobar') + end + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/zle_input_stack_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/zle_input_stack_spec.rb new file mode 100644 index 00000000..12cfbc7b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/integrations/zle_input_stack_spec.rb @@ -0,0 +1,24 @@ +describe 'using `zle -U`' do + let(:before_sourcing) do + -> do + session. + run_command('_zsh_autosuggest_strategy_test() { sleep 1; _zsh_autosuggest_strategy_history "$1" }'). + run_command('foo() { zle -U - "echo hello" }; zle -N foo; bindkey ^B foo') + end + end + + let(:options) { ['unset ZSH_AUTOSUGGEST_USE_ASYNC', 'ZSH_AUTOSUGGEST_STRATEGY=test'] } + + # TODO: This is only possible with the $KEYS_QUEUED_COUNT widget parameter, coming soon... + xit 'does not fetch a suggestion for every inserted character' do + session.send_keys('C-b') + wait_for { session.content }.to eq('echo hello') + end + + it 'shows a suggestion when the widget completes' do + with_history('echo hello world') do + session.send_keys('C-b') + wait_for { session.content(esc_seqs: true) }.to match(/\Aecho hello\e\[[0-9]+m world/) + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/kill_ring_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/kill_ring_spec.rb new file mode 100644 index 00000000..4d0178f9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/kill_ring_spec.rb @@ -0,0 +1,23 @@ +context 'with some items in the kill ring' do + before do + session. + send_string('echo foo'). + send_keys('C-u'). + send_string('echo bar'). + send_keys('C-u') + end + + describe '`yank-pop`' do + it 'should cycle through all items in the kill ring' do + session.send_keys('C-y') + wait_for { session.content }.to eq('echo bar') + + session.send_keys('escape').send_keys('y') + wait_for { session.content }.to eq('echo foo') + + session.send_keys('escape').send_keys('y') + wait_for { session.content }.to eq('echo bar') + end + end +end + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/line_init_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/line_init_spec.rb new file mode 100644 index 00000000..826277fc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/line_init_spec.rb @@ -0,0 +1,17 @@ +context 'with zle-line-init unignored' do + let(:after_sourcing) do + -> do + session. + run_command('setopt extendedglob'). + run_command('ZSH_AUTOSUGGEST_IGNORE_WIDGETS=(${(@)ZSH_AUTOSUGGEST_IGNORE_WIDGETS:#zle-\*} zle-\^line-init)'). + run_command('zle-line-init() { BUFFER="echo" }') + end + end + + it 'should fetch a suggestion on each line initialization' do + with_history('echo foo') do + session.run_command('zle -N zle-line-init') + wait_for { session.content }.to end_with('echo foo') + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/multi_line_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/multi_line_spec.rb new file mode 100644 index 00000000..364780a2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/multi_line_spec.rb @@ -0,0 +1,8 @@ +describe 'a multi-line suggestion' do + it 'should be displayed on multiple lines' do + with_history("echo \"\n\"") do + session.send_keys('e') + wait_for { session.content }.to eq("echo \"\n\"") + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/buffer_max_size_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/buffer_max_size_spec.rb new file mode 100644 index 00000000..29ca8bc4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/buffer_max_size_spec.rb @@ -0,0 +1,30 @@ +describe 'a suggestion' do + let(:term_opts) { { width: 200 } } + let(:long_command) { "echo #{'a' * 100}" } + + around do |example| + with_history(long_command) { example.run } + end + + it 'is provided for any buffer length' do + session.send_string(long_command[0...-1]) + wait_for { session.content }.to eq(long_command) + end + + context 'when ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE is specified' do + let(:buffer_max_size) { 10 } + let(:options) { ["ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE=#{buffer_max_size}"] } + + it 'is provided when the buffer is shorter than the specified length' do + session.send_string(long_command[0...(buffer_max_size - 1)]) + wait_for { session.content }.to eq(long_command) + end + + it 'is provided when the buffer is equal to the specified length' do + session.send_string(long_command[0...(buffer_max_size)]) + wait_for { session.content }.to eq(long_command) + end + + it 'is not provided when the buffer is longer than the specified length' + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/highlight_style_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/highlight_style_spec.rb new file mode 100644 index 00000000..a7e39b34 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/highlight_style_spec.rb @@ -0,0 +1,7 @@ +describe 'a displayed suggestion' do + it 'is shown in the default style' + + describe 'when ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE is set to a zle_highlight string' do + it 'is shown in the specified style' + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/original_widget_prefix_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/original_widget_prefix_spec.rb new file mode 100644 index 00000000..a4b6e983 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/original_widget_prefix_spec.rb @@ -0,0 +1,7 @@ +describe 'an original zle widget' do + context 'is accessible with the default prefix' + + context 'when ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX is set' do + it 'is accessible with the specified prefix' + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/strategy_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/strategy_spec.rb new file mode 100644 index 00000000..58562d0c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/strategy_spec.rb @@ -0,0 +1,55 @@ +describe 'a suggestion for a given prefix' do + let(:history_strategy) { '_zsh_autosuggest_strategy_history() { suggestion="history" }' } + let(:foobar_strategy) { '_zsh_autosuggest_strategy_foobar() { [[ "foobar baz" = $1* ]] && suggestion="foobar baz" }' } + let(:foobaz_strategy) { '_zsh_autosuggest_strategy_foobaz() { [[ "foobaz bar" = $1* ]] && suggestion="foobaz bar" }' } + + let(:after_sourcing) do + -> do + session.run_command(history_strategy) + end + end + + it 'by default is determined by calling the `history` strategy function' do + session.send_string('h') + wait_for { session.content }.to eq('history') + end + + context 'when ZSH_AUTOSUGGEST_STRATEGY is set to an array' do + let(:after_sourcing) do + -> do + session. + run_command(foobar_strategy). + run_command(foobaz_strategy). + run_command('ZSH_AUTOSUGGEST_STRATEGY=(foobar foobaz)') + end + end + + it 'is determined by the first strategy function to return a suggestion' do + session.send_string('foo') + wait_for { session.content }.to eq('foobar baz') + + session.send_string('baz') + wait_for { session.content }.to eq('foobaz bar') + end + end + + context 'when ZSH_AUTOSUGGEST_STRATEGY is set to a string' do + let(:after_sourcing) do + -> do + session. + run_command(foobar_strategy). + run_command(foobaz_strategy). + run_command('ZSH_AUTOSUGGEST_STRATEGY="foobar foobaz"') + end + end + + it 'is determined by the first strategy function to return a suggestion' do + session.send_string('foo') + wait_for { session.content }.to eq('foobar baz') + + session.send_string('baz') + wait_for { session.content }.to eq('foobaz bar') + end + end +end + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/widget_lists_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/widget_lists_spec.rb new file mode 100644 index 00000000..421b84e4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/options/widget_lists_spec.rb @@ -0,0 +1,121 @@ +describe 'a zle widget' do + let(:widget) { 'my-widget' } + let(:before_sourcing) { -> { session.run_command("#{widget}() {}; zle -N #{widget}; bindkey ^B #{widget}") } } + + context 'when added to ZSH_AUTOSUGGEST_ACCEPT_WIDGETS' do + let(:options) { ["ZSH_AUTOSUGGEST_ACCEPT_WIDGETS+=(#{widget})"] } + + it 'accepts the suggestion and moves the cursor to the end of the buffer when invoked' do + with_history('echo hello') do + session.send_string('e') + wait_for { session.content }.to eq('echo hello') + session.send_keys('C-b') + wait_for { session.content(esc_seqs: true) }.to eq('echo hello') + wait_for { session.cursor }.to eq([10, 0]) + end + end + end + + context 'when added to ZSH_AUTOSUGGEST_CLEAR_WIDGETS' do + let(:options) { ["ZSH_AUTOSUGGEST_CLEAR_WIDGETS+=(#{widget})"] } + + it 'clears the suggestion when invoked' do + with_history('echo hello') do + session.send_string('e') + wait_for { session.content }.to eq('echo hello') + session.send_keys('C-b') + wait_for { session.content }.to eq('e') + end + end + end + + context 'when added to ZSH_AUTOSUGGEST_EXECUTE_WIDGETS' do + let(:options) { ["ZSH_AUTOSUGGEST_EXECUTE_WIDGETS+=(#{widget})"] } + + it 'executes the suggestion when invoked' do + with_history('echo hello') do + session.send_string('e') + wait_for { session.content }.to eq('echo hello') + session.send_keys('C-b') + wait_for { session.content }.to end_with("\nhello") + end + end + end + + context 'when added to ZSH_AUTOSUGGEST_IGNORE_WIDGETS' do + let(:options) { ["ZSH_AUTOSUGGEST_IGNORE_WIDGETS=(#{widget})"] } + + it 'should not be wrapped with an autosuggest widget' do + session.run_command("echo $widgets[#{widget}]") + wait_for { session.content }.to end_with("\nuser:#{widget}") + end + end + + context 'that moves the cursor forward' do + before { session.run_command("#{widget}() { zle forward-char }") } + + context 'when added to ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS' do + let(:options) { ["ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS=(#{widget})"] } + + it 'accepts the suggestion as far as the cursor is moved when invoked' do + with_history('echo hello') do + session.send_string('e') + wait_for { session.content }.to start_with('echo hello') + session.send_keys('C-b') + wait_for { session.content(esc_seqs: true) }.to match(/\Aec\e\[[0-9]+mho hello/) + end + end + end + end + + context 'that modifies the buffer' do + before { session.run_command("#{widget}() { BUFFER=\"foo\" }") } + + context 'when not added to any of the widget lists' do + it 'modifies the buffer and fetches a new suggestion' do + with_history('foobar') do + session.send_keys('C-b') + wait_for { session.content }.to eq('foobar') + end + end + end + end +end + +describe 'a modification to the widget lists' do + let(:widget) { 'my-widget' } + let(:before_sourcing) { -> { session.run_command("#{widget}() {}; zle -N #{widget}; bindkey ^B #{widget}") } } + before { session.run_command("ZSH_AUTOSUGGEST_ACCEPT_WIDGETS+=(#{widget})") } + + it 'takes effect on the next cmd line' do + with_history('echo hello') do + session.send_string('e') + wait_for { session.content }.to eq('echo hello') + session.send_keys('C-b') + wait_for { session.content(esc_seqs: true) }.to eq('echo hello') + end + end + + context 'when manual rebind is enabled' do + let(:options) { ["ZSH_AUTOSUGGEST_MANUAL_REBIND=true"] } + + it 'does not take effect until bind command is re-run' do + with_history('echo hello') do + session.send_string('e') + wait_for { session.content }.to eq('echo hello') + session.send_keys('C-b') + sleep 1 + expect(session.content(esc_seqs: true)).not_to eq('echo hello') + + session.send_keys('C-c') + session.run_command('_zsh_autosuggest_bind_widgets').clear_screen + wait_for { session.content }.to eq('') + + session.send_string('e') + wait_for { session.content }.to eq('echo hello') + session.send_keys('C-b') + wait_for { session.content(esc_seqs: true) }.to eq('echo hello') + end + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/spec_helper.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/spec_helper.rb new file mode 100644 index 00000000..dc1abb0a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/spec_helper.rb @@ -0,0 +1,54 @@ +require 'pry' +require 'rspec/wait' +require 'terminal_session' +require 'tempfile' + +RSpec.shared_context 'terminal session' do + let(:term_opts) { {} } + let(:session) { TerminalSession.new(term_opts) } + let(:before_sourcing) { -> {} } + let(:after_sourcing) { -> {} } + let(:options) { [] } + + around do |example| + before_sourcing.call + session.run_command(['source zsh-autosuggestions.zsh', *options].join('; ')) + after_sourcing.call + session.clear_screen + + example.run + + session.destroy + end + + def with_history(*commands, &block) + Tempfile.create do |f| + f.write(commands.map{|c| c.gsub("\n", "\\\n")}.join("\n")) + f.flush + + session.run_command('fc -p') + session.run_command("fc -R #{f.path}") + + session.clear_screen + + yield block + + session.send_keys('C-c') + session.run_command('fc -P') + end + end +end + +RSpec.configure do |config| + config.expect_with :rspec do |expectations| + expectations.include_chain_clauses_in_custom_matcher_descriptions = true + end + + config.mock_with :rspec do |mocks| + mocks.verify_partial_doubles = true + end + + config.wait_timeout = 2 + + config.include_context 'terminal session' +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/strategies/completion_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/strategies/completion_spec.rb new file mode 100644 index 00000000..92794d6a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/strategies/completion_spec.rb @@ -0,0 +1,72 @@ +describe 'the `completion` suggestion strategy' do + let(:options) { ['ZSH_AUTOSUGGEST_STRATEGY=completion'] } + let(:before_sourcing) do + -> do + session. + run_command('autoload compinit && compinit'). + run_command('_foo() { compadd bar; compadd bat }'). + run_command('_num() { compadd two; compadd three }'). + run_command('compdef _foo baz'). + run_command('compdef _num one') + end + end + + it 'suggests the first completion result' do + session.send_string('baz ') + wait_for { session.content }.to eq('baz bar') + end + + it 'does not add extra carriage returns when prefix has a line feed' do + skip '`stty` does not work inside zpty below zsh version 5.0.3' if session.zsh_version < Gem::Version.new('5.0.3') + session.send_string('baz \\').send_keys('C-v', 'C-j') + wait_for { session.content }.to eq("baz \\\nbar") + end + + context 'when `_complete` is aliased' do + let(:before_sourcing) do + -> do + session. + run_command('autoload compinit && compinit'). + run_command('_foo() { compadd bar; compadd bat }'). + run_command('compdef _foo baz'). + run_command('alias _complete=_complete') + end + end + + it 'suggests the first completion result' do + session.send_string('baz ') + wait_for { session.content }.to eq('baz bar') + end + end + + context 'when ZSH_AUTOSUGGEST_COMPLETION_IGNORE is set to a pattern' do + let(:options) { ['ZSH_AUTOSUGGEST_STRATEGY=completion', 'ZSH_AUTOSUGGEST_COMPLETION_IGNORE="one *"'] } + + it 'makes suggestions when the buffer does not match the pattern' do + session.send_string('baz ') + wait_for { session.content }.to eq('baz bar') + end + + it 'does not make suggestions when the buffer matches the pattern' do + session.send_string('one t') + sleep 1 + expect(session.content).to eq('one t') + end + end + + context 'when async mode is enabled' do + let(:options) { ['ZSH_AUTOSUGGEST_USE_ASYNC=true', 'ZSH_AUTOSUGGEST_STRATEGY=completion'] } + + it 'suggests the first completion result' do + session.send_string('baz ') + wait_for { session.content }.to eq('baz bar') + end + + it 'does not add extra carriage returns when prefix has a line feed' do + skip '`stty` does not work inside zpty below zsh version 5.0.3' if session.zsh_version < Gem::Version.new('5.0.3') + session.send_string('baz \\').send_keys('C-v', 'C-j') + wait_for { session.content }.to eq("baz \\\nbar") + end + end +end + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/strategies/history_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/strategies/history_spec.rb new file mode 100644 index 00000000..eee8efdf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/strategies/history_spec.rb @@ -0,0 +1,23 @@ +require 'strategies/special_characters_helper' + +describe 'the `history` suggestion strategy' do + it 'suggests the last matching history entry' do + with_history('ls foo', 'ls bar', 'echo baz') do + session.send_string('ls') + wait_for { session.content }.to eq('ls bar') + end + end + + context 'when ZSH_AUTOSUGGEST_HISTORY_IGNORE is set to a pattern' do + let(:options) { ['ZSH_AUTOSUGGEST_HISTORY_IGNORE="* bar"'] } + + it 'does not make suggestions that match the pattern' do + with_history('ls foo', 'ls bar', 'echo baz') do + session.send_string('ls') + wait_for { session.content }.to eq('ls foo') + end + end + end + + include_examples 'special characters' +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/strategies/match_prev_cmd_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/strategies/match_prev_cmd_spec.rb new file mode 100644 index 00000000..c435f162 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/strategies/match_prev_cmd_spec.rb @@ -0,0 +1,34 @@ +require 'strategies/special_characters_helper' + +describe 'the `match_prev_cmd` strategy' do + let(:options) { ['ZSH_AUTOSUGGEST_STRATEGY=match_prev_cmd'] } + + let(:history) { [ + 'echo what', + 'ls foo', + 'echo what', + 'ls bar', + 'ls baz', + 'echo what' + ] } + + it 'suggests the last matching history entry after the previous command' do + with_history(*history) do + session.send_string('ls') + wait_for { session.content }.to eq('ls bar') + end + end + + context 'when ZSH_AUTOSUGGEST_HISTORY_IGNORE is set to a pattern' do + let(:options) { ['ZSH_AUTOSUGGEST_STRATEGY=match_prev_cmd', 'ZSH_AUTOSUGGEST_HISTORY_IGNORE="* bar"'] } + + it 'does not make suggestions that match the pattern' do + with_history(*history) do + session.send_string('ls') + wait_for { session.content }.to eq('ls foo') + end + end + end + + include_examples 'special characters' +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/strategies/special_characters_helper.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/strategies/special_characters_helper.rb new file mode 100644 index 00000000..eb1f0cdd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/strategies/special_characters_helper.rb @@ -0,0 +1,75 @@ +shared_examples 'special characters' do + describe 'a special character in the buffer should be treated like any other character' do + it 'asterisk' do + with_history('echo "hello*"', 'echo "hello."') do + session.send_string('echo "hello*') + wait_for { session.content }.to eq('echo "hello*"') + end + end + + it 'question mark' do + with_history('echo "hello?"', 'echo "hello."') do + session.send_string('echo "hello?') + wait_for { session.content }.to eq('echo "hello?"') + end + end + + it 'backslash' do + with_history('echo "hello\nworld"') do + session.send_string('echo "hello\\') + wait_for { session.content }.to eq('echo "hello\nworld"') + end + end + + it 'double backslash' do + with_history('echo "\\\\"') do + session.send_string('echo "\\\\') + wait_for { session.content }.to eq('echo "\\\\"') + end + end + + it 'tilde' do + with_history('echo ~/foo') do + session.send_string('echo ~') + wait_for { session.content }.to eq('echo ~/foo') + end + end + + it 'parentheses' do + with_history('echo "$(ls foo)"') do + session.send_string('echo "$(') + wait_for { session.content }.to eq('echo "$(ls foo)"') + end + end + + it 'square bracket' do + with_history('echo "$history[123]"') do + session.send_string('echo "$history[') + wait_for { session.content }.to eq('echo "$history[123]"') + session.send_string('123]') + wait_for { session.content }.to eq('echo "$history[123]"') + end + end + + it 'octothorpe' do + with_history('echo "#yolo"') do + session.send_string('echo "#') + wait_for { session.content }.to eq('echo "#yolo"') + end + end + + it 'caret' do + with_history('echo "^A"', 'echo "^B"') do + session.send_string('echo "^A') + wait_for { session.content }.to eq('echo "^A"') + end + end + + it 'dash' do + with_history('-foo() {}') do + session.send_string('-') + wait_for { session.content }.to eq('-foo() {}') + end + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/terminal_session.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/terminal_session.rb new file mode 100644 index 00000000..f91ee6cd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/terminal_session.rb @@ -0,0 +1,99 @@ +require 'securerandom' + +class TerminalSession + ZSH_BIN = ENV['TEST_ZSH_BIN'] || 'zsh' + + def initialize(opts = {}) + opts = { + width: 80, + height: 24, + prompt: '', + term: 'xterm-256color', + zsh_bin: ZSH_BIN + }.merge(opts) + + @opts = opts + + cmd="PS1=\"#{opts[:prompt]}\" TERM=#{opts[:term]} #{ZSH_BIN} -f" + tmux_command("new-session -d -x #{opts[:width]} -y #{opts[:height]} '#{cmd}'") + end + + def zsh_version + @zsh_version ||= Gem::Version.new(`#{ZSH_BIN} -c 'echo -n $ZSH_VERSION'`) + end + + def tmux_socket_name + @tmux_socket_name ||= SecureRandom.hex(6) + end + + def run_command(command) + send_string(command) + send_keys('enter') + + self + end + + def send_string(str) + tmux_command("send-keys -t 0 -l -- '#{str.gsub("'", "\\'")}'") + + self + end + + def send_keys(*keys) + tmux_command("send-keys -t 0 #{keys.join(' ')}") + + self + end + + def paste_string(str) + tmux_command("set-buffer -- '#{str}'") + tmux_command("paste-buffer -dpr -t 0") + + self + end + + def content(esc_seqs: false) + cmd = 'capture-pane -p -t 0' + cmd += ' -e' if esc_seqs + tmux_command(cmd).strip + end + + def clear_screen + send_keys('C-l') + + i = 0 + until content == opts[:prompt] || i > 20 do + sleep(0.1) + i = i + 1 + end + + self + end + + def destroy + tmux_command('kill-session') + end + + def cursor + tmux_command("display-message -t 0 -p '\#{cursor_x},\#{cursor_y}'"). + strip. + split(','). + map(&:to_i) + end + + def attach! + tmux_command('attach-session') + end + + private + + attr_reader :opts + + def tmux_command(cmd) + out = `tmux -u -L #{tmux_socket_name} #{cmd}` + + raise("tmux error running: '#{cmd}'") unless $?.success? + + out + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/widgets/disable_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/widgets/disable_spec.rb new file mode 100644 index 00000000..b387a590 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/widgets/disable_spec.rb @@ -0,0 +1,19 @@ +describe 'the `autosuggest-disable` widget' do + before do + session.run_command('bindkey ^B autosuggest-disable') + end + + it 'disables suggestions and clears the suggestion' do + with_history('echo hello') do + session.send_string('echo') + wait_for { session.content }.to eq('echo hello') + + session.send_keys('C-b') + wait_for { session.content }.to eq('echo') + + session.send_string(' h') + sleep 1 + expect(session.content).to eq('echo h') + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/widgets/enable_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/widgets/enable_spec.rb new file mode 100644 index 00000000..3ad35a8c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/widgets/enable_spec.rb @@ -0,0 +1,42 @@ +describe 'the `autosuggest-enable` widget' do + before do + session. + run_command('typeset -g _ZSH_AUTOSUGGEST_DISABLED'). + run_command('bindkey ^B autosuggest-enable') + end + + it 'enables suggestions and fetches a suggestion' do + with_history('echo hello') do + session.send_string('e') + sleep 1 + expect(session.content).to eq('e') + + session.send_keys('C-b') + session.send_string('c') + wait_for { session.content }.to eq('echo hello') + end + end + + context 'invoked on an empty buffer' do + it 'does not fetch a suggestion' do + with_history('echo hello') do + session.send_keys('C-b') + sleep 1 + expect(session.content).to eq('') + end + end + end + + context 'invoked on a non-empty buffer' do + it 'fetches a suggestion' do + with_history('echo hello') do + session.send_string('e') + sleep 1 + expect(session.content).to eq('e') + + session.send_keys('C-b') + wait_for { session.content }.to eq('echo hello') + end + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/widgets/fetch_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/widgets/fetch_spec.rb new file mode 100644 index 00000000..eb8f2ba5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/widgets/fetch_spec.rb @@ -0,0 +1,24 @@ +describe 'the `autosuggest-fetch` widget' do + context 'when suggestions are disabled' do + before do + session. + run_command('bindkey ^B autosuggest-disable'). + run_command('bindkey ^F autosuggest-fetch'). + send_keys('C-b') + end + + it 'will fetch and display a suggestion' do + with_history('echo hello') do + session.send_string('echo h') + sleep 1 + expect(session.content).to eq('echo h') + + session.send_keys('C-f') + wait_for { session.content }.to eq('echo hello') + + session.send_string('e') + wait_for { session.content }.to eq('echo hello') + end + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/widgets/toggle_spec.rb b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/widgets/toggle_spec.rb new file mode 100644 index 00000000..8f9f3c3d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/spec/widgets/toggle_spec.rb @@ -0,0 +1,26 @@ +describe 'the `autosuggest-toggle` widget' do + before do + session.run_command('bindkey ^B autosuggest-toggle') + end + + it 'toggles suggestions' do + with_history('echo world', 'echo hello') do + session.send_string('echo') + wait_for { session.content }.to eq('echo hello') + + session.send_keys('C-b') + wait_for { session.content }.to eq('echo') + + session.send_string(' h') + sleep 1 + expect(session.content).to eq('echo h') + + session.send_keys('C-b') + wait_for { session.content }.to eq('echo hello') + + session.send_keys('C-h') + session.send_string('w') + wait_for { session.content }.to eq('echo world') + end + end +end diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/async.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/async.zsh new file mode 100644 index 00000000..218eb269 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/async.zsh @@ -0,0 +1,76 @@ + +#--------------------------------------------------------------------# +# Async # +#--------------------------------------------------------------------# + +_zsh_autosuggest_async_request() { + zmodload zsh/system 2>/dev/null # For `$sysparams` + + typeset -g _ZSH_AUTOSUGGEST_ASYNC_FD _ZSH_AUTOSUGGEST_CHILD_PID + + # If we've got a pending request, cancel it + if [[ -n "$_ZSH_AUTOSUGGEST_ASYNC_FD" ]] && { true <&$_ZSH_AUTOSUGGEST_ASYNC_FD } 2>/dev/null; then + # Close the file descriptor and remove the handler + exec {_ZSH_AUTOSUGGEST_ASYNC_FD}<&- + zle -F $_ZSH_AUTOSUGGEST_ASYNC_FD + + # We won't know the pid unless the user has zsh/system module installed + if [[ -n "$_ZSH_AUTOSUGGEST_CHILD_PID" ]]; then + # Zsh will make a new process group for the child process only if job + # control is enabled (MONITOR option) + if [[ -o MONITOR ]]; then + # Send the signal to the process group to kill any processes that may + # have been forked by the suggestion strategy + kill -TERM -$_ZSH_AUTOSUGGEST_CHILD_PID 2>/dev/null + else + # Kill just the child process since it wasn't placed in a new process + # group. If the suggestion strategy forked any child processes they may + # be orphaned and left behind. + kill -TERM $_ZSH_AUTOSUGGEST_CHILD_PID 2>/dev/null + fi + fi + fi + + # Fork a process to fetch a suggestion and open a pipe to read from it + exec {_ZSH_AUTOSUGGEST_ASYNC_FD}< <( + # Tell parent process our pid + echo $sysparams[pid] + + # Fetch and print the suggestion + local suggestion + _zsh_autosuggest_fetch_suggestion "$1" + echo -nE "$suggestion" + ) + + # There's a weird bug here where ^C stops working unless we force a fork + # See https://github.com/zsh-users/zsh-autosuggestions/issues/364 + autoload -Uz is-at-least + is-at-least 5.8 || command true + + # Read the pid from the child process + read _ZSH_AUTOSUGGEST_CHILD_PID <&$_ZSH_AUTOSUGGEST_ASYNC_FD + + # When the fd is readable, call the response handler + zle -F "$_ZSH_AUTOSUGGEST_ASYNC_FD" _zsh_autosuggest_async_response +} + +# Called when new data is ready to be read from the pipe +# First arg will be fd ready for reading +# Second arg will be passed in case of error +_zsh_autosuggest_async_response() { + emulate -L zsh + + local suggestion + + if [[ -z "$2" || "$2" == "hup" ]]; then + # Read everything from the fd and give it as a suggestion + IFS='' read -rd '' -u $1 suggestion + zle autosuggest-suggest -- "$suggestion" + + # Close the fd + exec {1}<&- + fi + + # Always remove the handler + zle -F "$1" +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/bind.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/bind.zsh new file mode 100644 index 00000000..1dde137c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/bind.zsh @@ -0,0 +1,106 @@ + +#--------------------------------------------------------------------# +# Widget Helpers # +#--------------------------------------------------------------------# + +_zsh_autosuggest_incr_bind_count() { + typeset -gi bind_count=$((_ZSH_AUTOSUGGEST_BIND_COUNTS[$1]+1)) + _ZSH_AUTOSUGGEST_BIND_COUNTS[$1]=$bind_count +} + +# Bind a single widget to an autosuggest widget, saving a reference to the original widget +_zsh_autosuggest_bind_widget() { + typeset -gA _ZSH_AUTOSUGGEST_BIND_COUNTS + + local widget=$1 + local autosuggest_action=$2 + local prefix=$ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX + + local -i bind_count + + # Save a reference to the original widget + case $widgets[$widget] in + # Already bound + user:_zsh_autosuggest_(bound|orig)_*) + bind_count=$((_ZSH_AUTOSUGGEST_BIND_COUNTS[$widget])) + ;; + + # User-defined widget + user:*) + _zsh_autosuggest_incr_bind_count $widget + zle -N $prefix$bind_count-$widget ${widgets[$widget]#*:} + ;; + + # Built-in widget + builtin) + _zsh_autosuggest_incr_bind_count $widget + eval "_zsh_autosuggest_orig_${(q)widget}() { zle .${(q)widget} }" + zle -N $prefix$bind_count-$widget _zsh_autosuggest_orig_$widget + ;; + + # Completion widget + completion:*) + _zsh_autosuggest_incr_bind_count $widget + eval "zle -C $prefix$bind_count-${(q)widget} ${${(s.:.)widgets[$widget]}[2,3]}" + ;; + esac + + # Pass the original widget's name explicitly into the autosuggest + # function. Use this passed in widget name to call the original + # widget instead of relying on the $WIDGET variable being set + # correctly. $WIDGET cannot be trusted because other plugins call + # zle without the `-w` flag (e.g. `zle self-insert` instead of + # `zle self-insert -w`). + eval "_zsh_autosuggest_bound_${bind_count}_${(q)widget}() { + _zsh_autosuggest_widget_$autosuggest_action $prefix$bind_count-${(q)widget} \$@ + }" + + # Create the bound widget + zle -N -- $widget _zsh_autosuggest_bound_${bind_count}_$widget +} + +# Map all configured widgets to the right autosuggest widgets +_zsh_autosuggest_bind_widgets() { + emulate -L zsh + + local widget + local ignore_widgets + + ignore_widgets=( + .\* + _\* + ${_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS/#/autosuggest-} + $ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX\* + $ZSH_AUTOSUGGEST_IGNORE_WIDGETS + ) + + # Find every widget we might want to bind and bind it appropriately + for widget in ${${(f)"$(builtin zle -la)"}:#${(j:|:)~ignore_widgets}}; do + if [[ -n ${ZSH_AUTOSUGGEST_CLEAR_WIDGETS[(r)$widget]} ]]; then + _zsh_autosuggest_bind_widget $widget clear + elif [[ -n ${ZSH_AUTOSUGGEST_ACCEPT_WIDGETS[(r)$widget]} ]]; then + _zsh_autosuggest_bind_widget $widget accept + elif [[ -n ${ZSH_AUTOSUGGEST_EXECUTE_WIDGETS[(r)$widget]} ]]; then + _zsh_autosuggest_bind_widget $widget execute + elif [[ -n ${ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS[(r)$widget]} ]]; then + _zsh_autosuggest_bind_widget $widget partial_accept + else + # Assume any unspecified widget might modify the buffer + _zsh_autosuggest_bind_widget $widget modify + fi + done +} + +# Given the name of an original widget and args, invoke it, if it exists +_zsh_autosuggest_invoke_original_widget() { + # Do nothing unless called with at least one arg + (( $# )) || return 0 + + local original_widget_name="$1" + + shift + + if (( ${+widgets[$original_widget_name]} )); then + zle $original_widget_name -- $@ + fi +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/config.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/config.zsh new file mode 100644 index 00000000..5a0ebd85 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/config.zsh @@ -0,0 +1,93 @@ + +#--------------------------------------------------------------------# +# Global Configuration Variables # +#--------------------------------------------------------------------# + +# Color to use when highlighting suggestion +# Uses format of `region_highlight` +# More info: http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Zle-Widgets +(( ! ${+ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE} )) && +typeset -g ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=8' + +# Prefix to use when saving original versions of bound widgets +(( ! ${+ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX} )) && +typeset -g ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX=autosuggest-orig- + +# Strategies to use to fetch a suggestion +# Will try each strategy in order until a suggestion is returned +(( ! ${+ZSH_AUTOSUGGEST_STRATEGY} )) && { + typeset -ga ZSH_AUTOSUGGEST_STRATEGY + ZSH_AUTOSUGGEST_STRATEGY=(history) +} + +# Widgets that clear the suggestion +(( ! ${+ZSH_AUTOSUGGEST_CLEAR_WIDGETS} )) && { + typeset -ga ZSH_AUTOSUGGEST_CLEAR_WIDGETS + ZSH_AUTOSUGGEST_CLEAR_WIDGETS=( + history-search-forward + history-search-backward + history-beginning-search-forward + history-beginning-search-backward + history-substring-search-up + history-substring-search-down + up-line-or-beginning-search + down-line-or-beginning-search + up-line-or-history + down-line-or-history + accept-line + copy-earlier-word + ) +} + +# Widgets that accept the entire suggestion +(( ! ${+ZSH_AUTOSUGGEST_ACCEPT_WIDGETS} )) && { + typeset -ga ZSH_AUTOSUGGEST_ACCEPT_WIDGETS + ZSH_AUTOSUGGEST_ACCEPT_WIDGETS=( + forward-char + end-of-line + vi-forward-char + vi-end-of-line + vi-add-eol + ) +} + +# Widgets that accept the entire suggestion and execute it +(( ! ${+ZSH_AUTOSUGGEST_EXECUTE_WIDGETS} )) && { + typeset -ga ZSH_AUTOSUGGEST_EXECUTE_WIDGETS + ZSH_AUTOSUGGEST_EXECUTE_WIDGETS=( + ) +} + +# Widgets that accept the suggestion as far as the cursor moves +(( ! ${+ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS} )) && { + typeset -ga ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS + ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS=( + forward-word + emacs-forward-word + vi-forward-word + vi-forward-word-end + vi-forward-blank-word + vi-forward-blank-word-end + vi-find-next-char + vi-find-next-char-skip + ) +} + +# Widgets that should be ignored (globbing supported but must be escaped) +(( ! ${+ZSH_AUTOSUGGEST_IGNORE_WIDGETS} )) && { + typeset -ga ZSH_AUTOSUGGEST_IGNORE_WIDGETS + ZSH_AUTOSUGGEST_IGNORE_WIDGETS=( + orig-\* + beep + run-help + set-local-history + which-command + yank + yank-pop + zle-\* + ) +} + +# Pty name for capturing completions for completion suggestion strategy +(( ! ${+ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME} )) && +typeset -g ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME=zsh_autosuggest_completion_pty diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/fetch.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/fetch.zsh new file mode 100644 index 00000000..fef27152 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/fetch.zsh @@ -0,0 +1,27 @@ + +#--------------------------------------------------------------------# +# Fetch Suggestion # +#--------------------------------------------------------------------# +# Loops through all specified strategies and returns a suggestion +# from the first strategy to provide one. +# + +_zsh_autosuggest_fetch_suggestion() { + typeset -g suggestion + local -a strategies + local strategy + + # Ensure we are working with an array + strategies=(${=ZSH_AUTOSUGGEST_STRATEGY}) + + for strategy in $strategies; do + # Try to get a suggestion from this strategy + _zsh_autosuggest_strategy_$strategy "$1" + + # Ensure the suggestion matches the prefix + [[ "$suggestion" != "$1"* ]] && unset suggestion + + # Break once we've found a valid suggestion + [[ -n "$suggestion" ]] && break + done +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/highlight.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/highlight.zsh new file mode 100644 index 00000000..273c03d5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/highlight.zsh @@ -0,0 +1,26 @@ + +#--------------------------------------------------------------------# +# Highlighting # +#--------------------------------------------------------------------# + +# If there was a highlight, remove it +_zsh_autosuggest_highlight_reset() { + typeset -g _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT + + if [[ -n "$_ZSH_AUTOSUGGEST_LAST_HIGHLIGHT" ]]; then + region_highlight=("${(@)region_highlight:#$_ZSH_AUTOSUGGEST_LAST_HIGHLIGHT}") + unset _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT + fi +} + +# If there's a suggestion, highlight it +_zsh_autosuggest_highlight_apply() { + typeset -g _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT + + if (( $#POSTDISPLAY )); then + typeset -g _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT="$#BUFFER $(($#BUFFER + $#POSTDISPLAY)) $ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE" + region_highlight+=("$_ZSH_AUTOSUGGEST_LAST_HIGHLIGHT") + else + unset _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT + fi +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/start.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/start.zsh new file mode 100644 index 00000000..5d4ee521 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/start.zsh @@ -0,0 +1,33 @@ + +#--------------------------------------------------------------------# +# Start # +#--------------------------------------------------------------------# + +# Start the autosuggestion widgets +_zsh_autosuggest_start() { + # By default we re-bind widgets on every precmd to ensure we wrap other + # wrappers. Specifically, highlighting breaks if our widgets are wrapped by + # zsh-syntax-highlighting widgets. This also allows modifications to the + # widget list variables to take effect on the next precmd. However this has + # a decent performance hit, so users can set ZSH_AUTOSUGGEST_MANUAL_REBIND + # to disable the automatic re-binding. + if (( ${+ZSH_AUTOSUGGEST_MANUAL_REBIND} )); then + add-zsh-hook -d precmd _zsh_autosuggest_start + fi + + _zsh_autosuggest_bind_widgets +} + +# Mark for auto-loading the functions that we use +autoload -Uz add-zsh-hook is-at-least + +# Automatically enable asynchronous mode in newer versions of zsh. Disable for +# older versions because there is a bug when using async mode where ^C does not +# work immediately after fetching a suggestion. +# See https://github.com/zsh-users/zsh-autosuggestions/issues/364 +if is-at-least 5.0.8; then + typeset -g ZSH_AUTOSUGGEST_USE_ASYNC= +fi + +# Start the autosuggestion widgets on the next precmd +add-zsh-hook precmd _zsh_autosuggest_start diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/strategies/completion.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/strategies/completion.zsh new file mode 100644 index 00000000..e2d114c8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/strategies/completion.zsh @@ -0,0 +1,137 @@ + +#--------------------------------------------------------------------# +# Completion Suggestion Strategy # +#--------------------------------------------------------------------# +# Fetches a suggestion from the completion engine +# + +_zsh_autosuggest_capture_postcompletion() { + # Always insert the first completion into the buffer + compstate[insert]=1 + + # Don't list completions + unset 'compstate[list]' +} + +_zsh_autosuggest_capture_completion_widget() { + # Add a post-completion hook to be called after all completions have been + # gathered. The hook can modify compstate to affect what is done with the + # gathered completions. + local -a +h comppostfuncs + comppostfuncs=(_zsh_autosuggest_capture_postcompletion) + + # Only capture completions at the end of the buffer + CURSOR=$#BUFFER + + # Run the original widget wrapping `.complete-word` so we don't + # recursively try to fetch suggestions, since our pty is forked + # after autosuggestions is initialized. + zle -- ${(k)widgets[(r)completion:.complete-word:_main_complete]} + + if is-at-least 5.0.3; then + # Don't do any cr/lf transformations. We need to do this immediately before + # output because if we do it in setup, onlcr will be re-enabled when we enter + # vared in the async code path. There is a bug in zpty module in older versions + # where the tty is not properly attached to the pty slave, resulting in stty + # getting stopped with a SIGTTOU. See zsh-workers thread 31660 and upstream + # commit f75904a38 + stty -onlcr -ocrnl -F /dev/tty + fi + + # The completion has been added, print the buffer as the suggestion + echo -nE - $'\0'$BUFFER$'\0' +} + +zle -N autosuggest-capture-completion _zsh_autosuggest_capture_completion_widget + +_zsh_autosuggest_capture_setup() { + # There is a bug in zpty module in older zsh versions by which a + # zpty that exits will kill all zpty processes that were forked + # before it. Here we set up a zsh exit hook to SIGKILL the zpty + # process immediately, before it has a chance to kill any other + # zpty processes. + if ! is-at-least 5.4; then + zshexit() { + # The zsh builtin `kill` fails sometimes in older versions + # https://unix.stackexchange.com/a/477647/156673 + kill -KILL $$ 2>&- || command kill -KILL $$ + + # Block for long enough for the signal to come through + sleep 1 + } + fi + + # Try to avoid any suggestions that wouldn't match the prefix + zstyle ':completion:*' matcher-list '' + zstyle ':completion:*' path-completion false + zstyle ':completion:*' max-errors 0 not-numeric + + bindkey '^I' autosuggest-capture-completion +} + +_zsh_autosuggest_capture_completion_sync() { + _zsh_autosuggest_capture_setup + + zle autosuggest-capture-completion +} + +_zsh_autosuggest_capture_completion_async() { + _zsh_autosuggest_capture_setup + + zmodload zsh/parameter 2>/dev/null || return # For `$functions` + + # Make vared completion work as if for a normal command line + # https://stackoverflow.com/a/7057118/154703 + autoload +X _complete + functions[_original_complete]=$functions[_complete] + function _complete() { + unset 'compstate[vared]' + _original_complete "$@" + } + + # Open zle with buffer set so we can capture completions for it + vared 1 +} + +_zsh_autosuggest_strategy_completion() { + # Reset options to defaults and enable LOCAL_OPTIONS + emulate -L zsh + + # Enable extended glob for completion ignore pattern + setopt EXTENDED_GLOB + + typeset -g suggestion + local line REPLY + + # Exit if we don't have completions + whence compdef >/dev/null || return + + # Exit if we don't have zpty + zmodload zsh/zpty 2>/dev/null || return + + # Exit if our search string matches the ignore pattern + [[ -n "$ZSH_AUTOSUGGEST_COMPLETION_IGNORE" ]] && [[ "$1" == $~ZSH_AUTOSUGGEST_COMPLETION_IGNORE ]] && return + + # Zle will be inactive if we are in async mode + if zle; then + zpty $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME _zsh_autosuggest_capture_completion_sync + else + zpty $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME _zsh_autosuggest_capture_completion_async "\$1" + zpty -w $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME $'\t' + fi + + { + # The completion result is surrounded by null bytes, so read the + # content between the first two null bytes. + zpty -r $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME line '*'$'\0''*'$'\0' + + # Extract the suggestion from between the null bytes. On older + # versions of zsh (older than 5.3), we sometimes get extra bytes after + # the second null byte, so trim those off the end. + # See http://www.zsh.org/mla/workers/2015/msg03290.html + suggestion="${${(@0)line}[2]}" + } always { + # Destroy the pty + zpty -d $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME + } +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/strategies/history.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/strategies/history.zsh new file mode 100644 index 00000000..0672a136 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/strategies/history.zsh @@ -0,0 +1,32 @@ + +#--------------------------------------------------------------------# +# History Suggestion Strategy # +#--------------------------------------------------------------------# +# Suggests the most recent history item that matches the given +# prefix. +# + +_zsh_autosuggest_strategy_history() { + # Reset options to defaults and enable LOCAL_OPTIONS + emulate -L zsh + + # Enable globbing flags so that we can use (#m) and (x~y) glob operator + setopt EXTENDED_GLOB + + # Escape backslashes and all of the glob operators so we can use + # this string as a pattern to search the $history associative array. + # - (#m) globbing flag enables setting references for match data + # TODO: Use (b) flag when we can drop support for zsh older than v5.0.8 + local prefix="${1//(#m)[\\*?[\]<>()|^~#]/\\$MATCH}" + + # Get the history items that match the prefix, excluding those that match + # the ignore pattern + local pattern="$prefix*" + if [[ -n $ZSH_AUTOSUGGEST_HISTORY_IGNORE ]]; then + pattern="($pattern)~($ZSH_AUTOSUGGEST_HISTORY_IGNORE)" + fi + + # Give the first history item matching the pattern as the suggestion + # - (r) subscript flag makes the pattern match on values + typeset -g suggestion="${history[(r)$pattern]}" +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/strategies/match_prev_cmd.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/strategies/match_prev_cmd.zsh new file mode 100644 index 00000000..b7097837 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/strategies/match_prev_cmd.zsh @@ -0,0 +1,66 @@ + +#--------------------------------------------------------------------# +# Match Previous Command Suggestion Strategy # +#--------------------------------------------------------------------# +# Suggests the most recent history item that matches the given +# prefix and whose preceding history item also matches the most +# recently executed command. +# +# For example, suppose your history has the following entries: +# - pwd +# - ls foo +# - ls bar +# - pwd +# +# Given the history list above, when you type 'ls', the suggestion +# will be 'ls foo' rather than 'ls bar' because your most recently +# executed command (pwd) was previously followed by 'ls foo'. +# +# Note that this strategy won't work as expected with ZSH options that don't +# preserve the history order such as `HIST_IGNORE_ALL_DUPS` or +# `HIST_EXPIRE_DUPS_FIRST`. + +_zsh_autosuggest_strategy_match_prev_cmd() { + # Reset options to defaults and enable LOCAL_OPTIONS + emulate -L zsh + + # Enable globbing flags so that we can use (#m) and (x~y) glob operator + setopt EXTENDED_GLOB + + # TODO: Use (b) flag when we can drop support for zsh older than v5.0.8 + local prefix="${1//(#m)[\\*?[\]<>()|^~#]/\\$MATCH}" + + # Get the history items that match the prefix, excluding those that match + # the ignore pattern + local pattern="$prefix*" + if [[ -n $ZSH_AUTOSUGGEST_HISTORY_IGNORE ]]; then + pattern="($pattern)~($ZSH_AUTOSUGGEST_HISTORY_IGNORE)" + fi + + # Get all history event numbers that correspond to history + # entries that match the pattern + local history_match_keys + history_match_keys=(${(k)history[(R)$~pattern]}) + + # By default we use the first history number (most recent history entry) + local histkey="${history_match_keys[1]}" + + # Get the previously executed command + local prev_cmd="$(_zsh_autosuggest_escape_command "${history[$((HISTCMD-1))]}")" + + # Iterate up to the first 200 history event numbers that match $prefix + for key in "${(@)history_match_keys[1,200]}"; do + # Stop if we ran out of history + [[ $key -gt 1 ]] || break + + # See if the history entry preceding the suggestion matches the + # previous command, and use it if it does + if [[ "${history[$((key - 1))]}" == "$prev_cmd" ]]; then + histkey="$key" + break + fi + done + + # Give back the matched history entry + typeset -g suggestion="$history[$histkey]" +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/util.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/util.zsh new file mode 100644 index 00000000..1f55d363 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/util.zsh @@ -0,0 +1,11 @@ + +#--------------------------------------------------------------------# +# Utility Functions # +#--------------------------------------------------------------------# + +_zsh_autosuggest_escape_command() { + setopt localoptions EXTENDED_GLOB + + # Escape special chars in the string (requires EXTENDED_GLOB) + echo -E "${1//(#m)[\"\'\\()\[\]|*?~]/\\$MATCH}" +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/widgets.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/widgets.zsh new file mode 100644 index 00000000..bd616669 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/src/widgets.zsh @@ -0,0 +1,231 @@ + +#--------------------------------------------------------------------# +# Autosuggest Widget Implementations # +#--------------------------------------------------------------------# + +# Disable suggestions +_zsh_autosuggest_disable() { + typeset -g _ZSH_AUTOSUGGEST_DISABLED + _zsh_autosuggest_clear +} + +# Enable suggestions +_zsh_autosuggest_enable() { + unset _ZSH_AUTOSUGGEST_DISABLED + + if (( $#BUFFER )); then + _zsh_autosuggest_fetch + fi +} + +# Toggle suggestions (enable/disable) +_zsh_autosuggest_toggle() { + if (( ${+_ZSH_AUTOSUGGEST_DISABLED} )); then + _zsh_autosuggest_enable + else + _zsh_autosuggest_disable + fi +} + +# Clear the suggestion +_zsh_autosuggest_clear() { + # Remove the suggestion + unset POSTDISPLAY + + _zsh_autosuggest_invoke_original_widget $@ +} + +# Modify the buffer and get a new suggestion +_zsh_autosuggest_modify() { + local -i retval + + # Only available in zsh >= 5.4 + local -i KEYS_QUEUED_COUNT + + # Save the contents of the buffer/postdisplay + local orig_buffer="$BUFFER" + local orig_postdisplay="$POSTDISPLAY" + + # Clear suggestion while waiting for next one + unset POSTDISPLAY + + # Original widget may modify the buffer + _zsh_autosuggest_invoke_original_widget $@ + retval=$? + + emulate -L zsh + + # Don't fetch a new suggestion if there's more input to be read immediately + if (( $PENDING > 0 || $KEYS_QUEUED_COUNT > 0 )); then + POSTDISPLAY="$orig_postdisplay" + return $retval + fi + + # Optimize if manually typing in the suggestion or if buffer hasn't changed + if [[ "$BUFFER" = "$orig_buffer"* && "$orig_postdisplay" = "${BUFFER:$#orig_buffer}"* ]]; then + POSTDISPLAY="${orig_postdisplay:$(($#BUFFER - $#orig_buffer))}" + return $retval + fi + + # Bail out if suggestions are disabled + if (( ${+_ZSH_AUTOSUGGEST_DISABLED} )); then + return $? + fi + + # Get a new suggestion if the buffer is not empty after modification + if (( $#BUFFER > 0 )); then + if [[ -z "$ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE" ]] || (( $#BUFFER <= $ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE )); then + _zsh_autosuggest_fetch + fi + fi + + return $retval +} + +# Fetch a new suggestion based on what's currently in the buffer +_zsh_autosuggest_fetch() { + if (( ${+ZSH_AUTOSUGGEST_USE_ASYNC} )); then + _zsh_autosuggest_async_request "$BUFFER" + else + local suggestion + _zsh_autosuggest_fetch_suggestion "$BUFFER" + _zsh_autosuggest_suggest "$suggestion" + fi +} + +# Offer a suggestion +_zsh_autosuggest_suggest() { + emulate -L zsh + + local suggestion="$1" + + if [[ -n "$suggestion" ]] && (( $#BUFFER )); then + POSTDISPLAY="${suggestion#$BUFFER}" + else + unset POSTDISPLAY + fi +} + +# Accept the entire suggestion +_zsh_autosuggest_accept() { + local -i retval max_cursor_pos=$#BUFFER + + # When vicmd keymap is active, the cursor can't move all the way + # to the end of the buffer + if [[ "$KEYMAP" = "vicmd" ]]; then + max_cursor_pos=$((max_cursor_pos - 1)) + fi + + # If we're not in a valid state to accept a suggestion, just run the + # original widget and bail out + if (( $CURSOR != $max_cursor_pos || !$#POSTDISPLAY )); then + _zsh_autosuggest_invoke_original_widget $@ + return + fi + + # Only accept if the cursor is at the end of the buffer + # Add the suggestion to the buffer + BUFFER="$BUFFER$POSTDISPLAY" + + # Remove the suggestion + unset POSTDISPLAY + + # Run the original widget before manually moving the cursor so that the + # cursor movement doesn't make the widget do something unexpected + _zsh_autosuggest_invoke_original_widget $@ + retval=$? + + # Move the cursor to the end of the buffer + if [[ "$KEYMAP" = "vicmd" ]]; then + CURSOR=$(($#BUFFER - 1)) + else + CURSOR=$#BUFFER + fi + + return $retval +} + +# Accept the entire suggestion and execute it +_zsh_autosuggest_execute() { + # Add the suggestion to the buffer + BUFFER="$BUFFER$POSTDISPLAY" + + # Remove the suggestion + unset POSTDISPLAY + + # Call the original `accept-line` to handle syntax highlighting or + # other potential custom behavior + _zsh_autosuggest_invoke_original_widget "accept-line" +} + +# Partially accept the suggestion +_zsh_autosuggest_partial_accept() { + local -i retval cursor_loc + + # Save the contents of the buffer so we can restore later if needed + local original_buffer="$BUFFER" + + # Temporarily accept the suggestion. + BUFFER="$BUFFER$POSTDISPLAY" + + # Original widget moves the cursor + _zsh_autosuggest_invoke_original_widget $@ + retval=$? + + # Normalize cursor location across vi/emacs modes + cursor_loc=$CURSOR + if [[ "$KEYMAP" = "vicmd" ]]; then + cursor_loc=$((cursor_loc + 1)) + fi + + # If we've moved past the end of the original buffer + if (( $cursor_loc > $#original_buffer )); then + # Set POSTDISPLAY to text right of the cursor + POSTDISPLAY="${BUFFER[$(($cursor_loc + 1)),$#BUFFER]}" + + # Clip the buffer at the cursor + BUFFER="${BUFFER[1,$cursor_loc]}" + else + # Restore the original buffer + BUFFER="$original_buffer" + fi + + return $retval +} + +() { + typeset -ga _ZSH_AUTOSUGGEST_BUILTIN_ACTIONS + + _ZSH_AUTOSUGGEST_BUILTIN_ACTIONS=( + clear + fetch + suggest + accept + execute + enable + disable + toggle + ) + + local action + for action in $_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS modify partial_accept; do + eval "_zsh_autosuggest_widget_$action() { + local -i retval + + _zsh_autosuggest_highlight_reset + + _zsh_autosuggest_$action \$@ + retval=\$? + + _zsh_autosuggest_highlight_apply + + zle -R + + return \$retval + }" + done + + for action in $_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS; do + zle -N autosuggest-$action _zsh_autosuggest_widget_$action + done +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/zsh-autosuggestions.plugin.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/zsh-autosuggestions.plugin.zsh new file mode 100644 index 00000000..16c22563 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/zsh-autosuggestions.plugin.zsh @@ -0,0 +1 @@ +source ${0:A:h}/zsh-autosuggestions.zsh diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/zsh-autosuggestions.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/zsh-autosuggestions.zsh new file mode 100644 index 00000000..b19cac73 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-autosuggestions/zsh-autosuggestions.zsh @@ -0,0 +1,864 @@ +# Fish-like fast/unobtrusive autosuggestions for zsh. +# https://github.com/zsh-users/zsh-autosuggestions +# v0.7.0 +# Copyright (c) 2013 Thiago de Arruda +# Copyright (c) 2016-2021 Eric Freese +# +# 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. + +#--------------------------------------------------------------------# +# Global Configuration Variables # +#--------------------------------------------------------------------# + +# Color to use when highlighting suggestion +# Uses format of `region_highlight` +# More info: http://zsh.sourceforge.net/Doc/Release/Zsh-Line-Editor.html#Zle-Widgets +(( ! ${+ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE} )) && +typeset -g ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE='fg=8' + +# Prefix to use when saving original versions of bound widgets +(( ! ${+ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX} )) && +typeset -g ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX=autosuggest-orig- + +# Strategies to use to fetch a suggestion +# Will try each strategy in order until a suggestion is returned +(( ! ${+ZSH_AUTOSUGGEST_STRATEGY} )) && { + typeset -ga ZSH_AUTOSUGGEST_STRATEGY + ZSH_AUTOSUGGEST_STRATEGY=(history) +} + +# Widgets that clear the suggestion +(( ! ${+ZSH_AUTOSUGGEST_CLEAR_WIDGETS} )) && { + typeset -ga ZSH_AUTOSUGGEST_CLEAR_WIDGETS + ZSH_AUTOSUGGEST_CLEAR_WIDGETS=( + history-search-forward + history-search-backward + history-beginning-search-forward + history-beginning-search-backward + history-substring-search-up + history-substring-search-down + up-line-or-beginning-search + down-line-or-beginning-search + up-line-or-history + down-line-or-history + accept-line + copy-earlier-word + ) +} + +# Widgets that accept the entire suggestion +(( ! ${+ZSH_AUTOSUGGEST_ACCEPT_WIDGETS} )) && { + typeset -ga ZSH_AUTOSUGGEST_ACCEPT_WIDGETS + ZSH_AUTOSUGGEST_ACCEPT_WIDGETS=( + forward-char + end-of-line + vi-forward-char + vi-end-of-line + vi-add-eol + ) +} + +# Widgets that accept the entire suggestion and execute it +(( ! ${+ZSH_AUTOSUGGEST_EXECUTE_WIDGETS} )) && { + typeset -ga ZSH_AUTOSUGGEST_EXECUTE_WIDGETS + ZSH_AUTOSUGGEST_EXECUTE_WIDGETS=( + ) +} + +# Widgets that accept the suggestion as far as the cursor moves +(( ! ${+ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS} )) && { + typeset -ga ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS + ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS=( + forward-word + emacs-forward-word + vi-forward-word + vi-forward-word-end + vi-forward-blank-word + vi-forward-blank-word-end + vi-find-next-char + vi-find-next-char-skip + ) +} + +# Widgets that should be ignored (globbing supported but must be escaped) +(( ! ${+ZSH_AUTOSUGGEST_IGNORE_WIDGETS} )) && { + typeset -ga ZSH_AUTOSUGGEST_IGNORE_WIDGETS + ZSH_AUTOSUGGEST_IGNORE_WIDGETS=( + orig-\* + beep + run-help + set-local-history + which-command + yank + yank-pop + zle-\* + ) +} + +# Pty name for capturing completions for completion suggestion strategy +(( ! ${+ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME} )) && +typeset -g ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME=zsh_autosuggest_completion_pty + +#--------------------------------------------------------------------# +# Utility Functions # +#--------------------------------------------------------------------# + +_zsh_autosuggest_escape_command() { + setopt localoptions EXTENDED_GLOB + + # Escape special chars in the string (requires EXTENDED_GLOB) + echo -E "${1//(#m)[\"\'\\()\[\]|*?~]/\\$MATCH}" +} + +#--------------------------------------------------------------------# +# Widget Helpers # +#--------------------------------------------------------------------# + +_zsh_autosuggest_incr_bind_count() { + typeset -gi bind_count=$((_ZSH_AUTOSUGGEST_BIND_COUNTS[$1]+1)) + _ZSH_AUTOSUGGEST_BIND_COUNTS[$1]=$bind_count +} + +# Bind a single widget to an autosuggest widget, saving a reference to the original widget +_zsh_autosuggest_bind_widget() { + typeset -gA _ZSH_AUTOSUGGEST_BIND_COUNTS + + local widget=$1 + local autosuggest_action=$2 + local prefix=$ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX + + local -i bind_count + + # Save a reference to the original widget + case $widgets[$widget] in + # Already bound + user:_zsh_autosuggest_(bound|orig)_*) + bind_count=$((_ZSH_AUTOSUGGEST_BIND_COUNTS[$widget])) + ;; + + # User-defined widget + user:*) + _zsh_autosuggest_incr_bind_count $widget + zle -N $prefix$bind_count-$widget ${widgets[$widget]#*:} + ;; + + # Built-in widget + builtin) + _zsh_autosuggest_incr_bind_count $widget + eval "_zsh_autosuggest_orig_${(q)widget}() { zle .${(q)widget} }" + zle -N $prefix$bind_count-$widget _zsh_autosuggest_orig_$widget + ;; + + # Completion widget + completion:*) + _zsh_autosuggest_incr_bind_count $widget + eval "zle -C $prefix$bind_count-${(q)widget} ${${(s.:.)widgets[$widget]}[2,3]}" + ;; + esac + + # Pass the original widget's name explicitly into the autosuggest + # function. Use this passed in widget name to call the original + # widget instead of relying on the $WIDGET variable being set + # correctly. $WIDGET cannot be trusted because other plugins call + # zle without the `-w` flag (e.g. `zle self-insert` instead of + # `zle self-insert -w`). + eval "_zsh_autosuggest_bound_${bind_count}_${(q)widget}() { + _zsh_autosuggest_widget_$autosuggest_action $prefix$bind_count-${(q)widget} \$@ + }" + + # Create the bound widget + zle -N -- $widget _zsh_autosuggest_bound_${bind_count}_$widget +} + +# Map all configured widgets to the right autosuggest widgets +_zsh_autosuggest_bind_widgets() { + emulate -L zsh + + local widget + local ignore_widgets + + ignore_widgets=( + .\* + _\* + ${_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS/#/autosuggest-} + $ZSH_AUTOSUGGEST_ORIGINAL_WIDGET_PREFIX\* + $ZSH_AUTOSUGGEST_IGNORE_WIDGETS + ) + + # Find every widget we might want to bind and bind it appropriately + for widget in ${${(f)"$(builtin zle -la)"}:#${(j:|:)~ignore_widgets}}; do + if [[ -n ${ZSH_AUTOSUGGEST_CLEAR_WIDGETS[(r)$widget]} ]]; then + _zsh_autosuggest_bind_widget $widget clear + elif [[ -n ${ZSH_AUTOSUGGEST_ACCEPT_WIDGETS[(r)$widget]} ]]; then + _zsh_autosuggest_bind_widget $widget accept + elif [[ -n ${ZSH_AUTOSUGGEST_EXECUTE_WIDGETS[(r)$widget]} ]]; then + _zsh_autosuggest_bind_widget $widget execute + elif [[ -n ${ZSH_AUTOSUGGEST_PARTIAL_ACCEPT_WIDGETS[(r)$widget]} ]]; then + _zsh_autosuggest_bind_widget $widget partial_accept + else + # Assume any unspecified widget might modify the buffer + _zsh_autosuggest_bind_widget $widget modify + fi + done +} + +# Given the name of an original widget and args, invoke it, if it exists +_zsh_autosuggest_invoke_original_widget() { + # Do nothing unless called with at least one arg + (( $# )) || return 0 + + local original_widget_name="$1" + + shift + + if (( ${+widgets[$original_widget_name]} )); then + zle $original_widget_name -- $@ + fi +} + +#--------------------------------------------------------------------# +# Highlighting # +#--------------------------------------------------------------------# + +# If there was a highlight, remove it +_zsh_autosuggest_highlight_reset() { + typeset -g _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT + + if [[ -n "$_ZSH_AUTOSUGGEST_LAST_HIGHLIGHT" ]]; then + region_highlight=("${(@)region_highlight:#$_ZSH_AUTOSUGGEST_LAST_HIGHLIGHT}") + unset _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT + fi +} + +# If there's a suggestion, highlight it +_zsh_autosuggest_highlight_apply() { + typeset -g _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT + + if (( $#POSTDISPLAY )); then + typeset -g _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT="$#BUFFER $(($#BUFFER + $#POSTDISPLAY)) $ZSH_AUTOSUGGEST_HIGHLIGHT_STYLE" + region_highlight+=("$_ZSH_AUTOSUGGEST_LAST_HIGHLIGHT") + else + unset _ZSH_AUTOSUGGEST_LAST_HIGHLIGHT + fi +} + +#--------------------------------------------------------------------# +# Autosuggest Widget Implementations # +#--------------------------------------------------------------------# + +# Disable suggestions +_zsh_autosuggest_disable() { + typeset -g _ZSH_AUTOSUGGEST_DISABLED + _zsh_autosuggest_clear +} + +# Enable suggestions +_zsh_autosuggest_enable() { + unset _ZSH_AUTOSUGGEST_DISABLED + + if (( $#BUFFER )); then + _zsh_autosuggest_fetch + fi +} + +# Toggle suggestions (enable/disable) +_zsh_autosuggest_toggle() { + if (( ${+_ZSH_AUTOSUGGEST_DISABLED} )); then + _zsh_autosuggest_enable + else + _zsh_autosuggest_disable + fi +} + +# Clear the suggestion +_zsh_autosuggest_clear() { + # Remove the suggestion + unset POSTDISPLAY + + _zsh_autosuggest_invoke_original_widget $@ +} + +# Modify the buffer and get a new suggestion +_zsh_autosuggest_modify() { + local -i retval + + # Only available in zsh >= 5.4 + local -i KEYS_QUEUED_COUNT + + # Save the contents of the buffer/postdisplay + local orig_buffer="$BUFFER" + local orig_postdisplay="$POSTDISPLAY" + + # Clear suggestion while waiting for next one + unset POSTDISPLAY + + # Original widget may modify the buffer + _zsh_autosuggest_invoke_original_widget $@ + retval=$? + + emulate -L zsh + + # Don't fetch a new suggestion if there's more input to be read immediately + if (( $PENDING > 0 || $KEYS_QUEUED_COUNT > 0 )); then + POSTDISPLAY="$orig_postdisplay" + return $retval + fi + + # Optimize if manually typing in the suggestion or if buffer hasn't changed + if [[ "$BUFFER" = "$orig_buffer"* && "$orig_postdisplay" = "${BUFFER:$#orig_buffer}"* ]]; then + POSTDISPLAY="${orig_postdisplay:$(($#BUFFER - $#orig_buffer))}" + return $retval + fi + + # Bail out if suggestions are disabled + if (( ${+_ZSH_AUTOSUGGEST_DISABLED} )); then + return $? + fi + + # Get a new suggestion if the buffer is not empty after modification + if (( $#BUFFER > 0 )); then + if [[ -z "$ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE" ]] || (( $#BUFFER <= $ZSH_AUTOSUGGEST_BUFFER_MAX_SIZE )); then + _zsh_autosuggest_fetch + fi + fi + + return $retval +} + +# Fetch a new suggestion based on what's currently in the buffer +_zsh_autosuggest_fetch() { + if (( ${+ZSH_AUTOSUGGEST_USE_ASYNC} )); then + _zsh_autosuggest_async_request "$BUFFER" + else + local suggestion + _zsh_autosuggest_fetch_suggestion "$BUFFER" + _zsh_autosuggest_suggest "$suggestion" + fi +} + +# Offer a suggestion +_zsh_autosuggest_suggest() { + emulate -L zsh + + local suggestion="$1" + + if [[ -n "$suggestion" ]] && (( $#BUFFER )); then + POSTDISPLAY="${suggestion#$BUFFER}" + else + unset POSTDISPLAY + fi +} + +# Accept the entire suggestion +_zsh_autosuggest_accept() { + local -i retval max_cursor_pos=$#BUFFER + + # When vicmd keymap is active, the cursor can't move all the way + # to the end of the buffer + if [[ "$KEYMAP" = "vicmd" ]]; then + max_cursor_pos=$((max_cursor_pos - 1)) + fi + + # If we're not in a valid state to accept a suggestion, just run the + # original widget and bail out + if (( $CURSOR != $max_cursor_pos || !$#POSTDISPLAY )); then + _zsh_autosuggest_invoke_original_widget $@ + return + fi + + # Only accept if the cursor is at the end of the buffer + # Add the suggestion to the buffer + BUFFER="$BUFFER$POSTDISPLAY" + + # Remove the suggestion + unset POSTDISPLAY + + # Run the original widget before manually moving the cursor so that the + # cursor movement doesn't make the widget do something unexpected + _zsh_autosuggest_invoke_original_widget $@ + retval=$? + + # Move the cursor to the end of the buffer + if [[ "$KEYMAP" = "vicmd" ]]; then + CURSOR=$(($#BUFFER - 1)) + else + CURSOR=$#BUFFER + fi + + return $retval +} + +# Accept the entire suggestion and execute it +_zsh_autosuggest_execute() { + # Add the suggestion to the buffer + BUFFER="$BUFFER$POSTDISPLAY" + + # Remove the suggestion + unset POSTDISPLAY + + # Call the original `accept-line` to handle syntax highlighting or + # other potential custom behavior + _zsh_autosuggest_invoke_original_widget "accept-line" +} + +# Partially accept the suggestion +_zsh_autosuggest_partial_accept() { + local -i retval cursor_loc + + # Save the contents of the buffer so we can restore later if needed + local original_buffer="$BUFFER" + + # Temporarily accept the suggestion. + BUFFER="$BUFFER$POSTDISPLAY" + + # Original widget moves the cursor + _zsh_autosuggest_invoke_original_widget $@ + retval=$? + + # Normalize cursor location across vi/emacs modes + cursor_loc=$CURSOR + if [[ "$KEYMAP" = "vicmd" ]]; then + cursor_loc=$((cursor_loc + 1)) + fi + + # If we've moved past the end of the original buffer + if (( $cursor_loc > $#original_buffer )); then + # Set POSTDISPLAY to text right of the cursor + POSTDISPLAY="${BUFFER[$(($cursor_loc + 1)),$#BUFFER]}" + + # Clip the buffer at the cursor + BUFFER="${BUFFER[1,$cursor_loc]}" + else + # Restore the original buffer + BUFFER="$original_buffer" + fi + + return $retval +} + +() { + typeset -ga _ZSH_AUTOSUGGEST_BUILTIN_ACTIONS + + _ZSH_AUTOSUGGEST_BUILTIN_ACTIONS=( + clear + fetch + suggest + accept + execute + enable + disable + toggle + ) + + local action + for action in $_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS modify partial_accept; do + eval "_zsh_autosuggest_widget_$action() { + local -i retval + + _zsh_autosuggest_highlight_reset + + _zsh_autosuggest_$action \$@ + retval=\$? + + _zsh_autosuggest_highlight_apply + + zle -R + + return \$retval + }" + done + + for action in $_ZSH_AUTOSUGGEST_BUILTIN_ACTIONS; do + zle -N autosuggest-$action _zsh_autosuggest_widget_$action + done +} + +#--------------------------------------------------------------------# +# Completion Suggestion Strategy # +#--------------------------------------------------------------------# +# Fetches a suggestion from the completion engine +# + +_zsh_autosuggest_capture_postcompletion() { + # Always insert the first completion into the buffer + compstate[insert]=1 + + # Don't list completions + unset 'compstate[list]' +} + +_zsh_autosuggest_capture_completion_widget() { + # Add a post-completion hook to be called after all completions have been + # gathered. The hook can modify compstate to affect what is done with the + # gathered completions. + local -a +h comppostfuncs + comppostfuncs=(_zsh_autosuggest_capture_postcompletion) + + # Only capture completions at the end of the buffer + CURSOR=$#BUFFER + + # Run the original widget wrapping `.complete-word` so we don't + # recursively try to fetch suggestions, since our pty is forked + # after autosuggestions is initialized. + zle -- ${(k)widgets[(r)completion:.complete-word:_main_complete]} + + if is-at-least 5.0.3; then + # Don't do any cr/lf transformations. We need to do this immediately before + # output because if we do it in setup, onlcr will be re-enabled when we enter + # vared in the async code path. There is a bug in zpty module in older versions + # where the tty is not properly attached to the pty slave, resulting in stty + # getting stopped with a SIGTTOU. See zsh-workers thread 31660 and upstream + # commit f75904a38 + stty -onlcr -ocrnl -F /dev/tty + fi + + # The completion has been added, print the buffer as the suggestion + echo -nE - $'\0'$BUFFER$'\0' +} + +zle -N autosuggest-capture-completion _zsh_autosuggest_capture_completion_widget + +_zsh_autosuggest_capture_setup() { + # There is a bug in zpty module in older zsh versions by which a + # zpty that exits will kill all zpty processes that were forked + # before it. Here we set up a zsh exit hook to SIGKILL the zpty + # process immediately, before it has a chance to kill any other + # zpty processes. + if ! is-at-least 5.4; then + zshexit() { + # The zsh builtin `kill` fails sometimes in older versions + # https://unix.stackexchange.com/a/477647/156673 + kill -KILL $$ 2>&- || command kill -KILL $$ + + # Block for long enough for the signal to come through + sleep 1 + } + fi + + # Try to avoid any suggestions that wouldn't match the prefix + zstyle ':completion:*' matcher-list '' + zstyle ':completion:*' path-completion false + zstyle ':completion:*' max-errors 0 not-numeric + + bindkey '^I' autosuggest-capture-completion +} + +_zsh_autosuggest_capture_completion_sync() { + _zsh_autosuggest_capture_setup + + zle autosuggest-capture-completion +} + +_zsh_autosuggest_capture_completion_async() { + _zsh_autosuggest_capture_setup + + zmodload zsh/parameter 2>/dev/null || return # For `$functions` + + # Make vared completion work as if for a normal command line + # https://stackoverflow.com/a/7057118/154703 + autoload +X _complete + functions[_original_complete]=$functions[_complete] + function _complete() { + unset 'compstate[vared]' + _original_complete "$@" + } + + # Open zle with buffer set so we can capture completions for it + vared 1 +} + +_zsh_autosuggest_strategy_completion() { + # Reset options to defaults and enable LOCAL_OPTIONS + emulate -L zsh + + # Enable extended glob for completion ignore pattern + setopt EXTENDED_GLOB + + typeset -g suggestion + local line REPLY + + # Exit if we don't have completions + whence compdef >/dev/null || return + + # Exit if we don't have zpty + zmodload zsh/zpty 2>/dev/null || return + + # Exit if our search string matches the ignore pattern + [[ -n "$ZSH_AUTOSUGGEST_COMPLETION_IGNORE" ]] && [[ "$1" == $~ZSH_AUTOSUGGEST_COMPLETION_IGNORE ]] && return + + # Zle will be inactive if we are in async mode + if zle; then + zpty $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME _zsh_autosuggest_capture_completion_sync + else + zpty $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME _zsh_autosuggest_capture_completion_async "\$1" + zpty -w $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME $'\t' + fi + + { + # The completion result is surrounded by null bytes, so read the + # content between the first two null bytes. + zpty -r $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME line '*'$'\0''*'$'\0' + + # Extract the suggestion from between the null bytes. On older + # versions of zsh (older than 5.3), we sometimes get extra bytes after + # the second null byte, so trim those off the end. + # See http://www.zsh.org/mla/workers/2015/msg03290.html + suggestion="${${(@0)line}[2]}" + } always { + # Destroy the pty + zpty -d $ZSH_AUTOSUGGEST_COMPLETIONS_PTY_NAME + } +} + +#--------------------------------------------------------------------# +# History Suggestion Strategy # +#--------------------------------------------------------------------# +# Suggests the most recent history item that matches the given +# prefix. +# + +_zsh_autosuggest_strategy_history() { + # Reset options to defaults and enable LOCAL_OPTIONS + emulate -L zsh + + # Enable globbing flags so that we can use (#m) and (x~y) glob operator + setopt EXTENDED_GLOB + + # Escape backslashes and all of the glob operators so we can use + # this string as a pattern to search the $history associative array. + # - (#m) globbing flag enables setting references for match data + # TODO: Use (b) flag when we can drop support for zsh older than v5.0.8 + local prefix="${1//(#m)[\\*?[\]<>()|^~#]/\\$MATCH}" + + # Get the history items that match the prefix, excluding those that match + # the ignore pattern + local pattern="$prefix*" + if [[ -n $ZSH_AUTOSUGGEST_HISTORY_IGNORE ]]; then + pattern="($pattern)~($ZSH_AUTOSUGGEST_HISTORY_IGNORE)" + fi + + # Give the first history item matching the pattern as the suggestion + # - (r) subscript flag makes the pattern match on values + typeset -g suggestion="${history[(r)$pattern]}" +} + +#--------------------------------------------------------------------# +# Match Previous Command Suggestion Strategy # +#--------------------------------------------------------------------# +# Suggests the most recent history item that matches the given +# prefix and whose preceding history item also matches the most +# recently executed command. +# +# For example, suppose your history has the following entries: +# - pwd +# - ls foo +# - ls bar +# - pwd +# +# Given the history list above, when you type 'ls', the suggestion +# will be 'ls foo' rather than 'ls bar' because your most recently +# executed command (pwd) was previously followed by 'ls foo'. +# +# Note that this strategy won't work as expected with ZSH options that don't +# preserve the history order such as `HIST_IGNORE_ALL_DUPS` or +# `HIST_EXPIRE_DUPS_FIRST`. + +_zsh_autosuggest_strategy_match_prev_cmd() { + # Reset options to defaults and enable LOCAL_OPTIONS + emulate -L zsh + + # Enable globbing flags so that we can use (#m) and (x~y) glob operator + setopt EXTENDED_GLOB + + # TODO: Use (b) flag when we can drop support for zsh older than v5.0.8 + local prefix="${1//(#m)[\\*?[\]<>()|^~#]/\\$MATCH}" + + # Get the history items that match the prefix, excluding those that match + # the ignore pattern + local pattern="$prefix*" + if [[ -n $ZSH_AUTOSUGGEST_HISTORY_IGNORE ]]; then + pattern="($pattern)~($ZSH_AUTOSUGGEST_HISTORY_IGNORE)" + fi + + # Get all history event numbers that correspond to history + # entries that match the pattern + local history_match_keys + history_match_keys=(${(k)history[(R)$~pattern]}) + + # By default we use the first history number (most recent history entry) + local histkey="${history_match_keys[1]}" + + # Get the previously executed command + local prev_cmd="$(_zsh_autosuggest_escape_command "${history[$((HISTCMD-1))]}")" + + # Iterate up to the first 200 history event numbers that match $prefix + for key in "${(@)history_match_keys[1,200]}"; do + # Stop if we ran out of history + [[ $key -gt 1 ]] || break + + # See if the history entry preceding the suggestion matches the + # previous command, and use it if it does + if [[ "${history[$((key - 1))]}" == "$prev_cmd" ]]; then + histkey="$key" + break + fi + done + + # Give back the matched history entry + typeset -g suggestion="$history[$histkey]" +} + +#--------------------------------------------------------------------# +# Fetch Suggestion # +#--------------------------------------------------------------------# +# Loops through all specified strategies and returns a suggestion +# from the first strategy to provide one. +# + +_zsh_autosuggest_fetch_suggestion() { + typeset -g suggestion + local -a strategies + local strategy + + # Ensure we are working with an array + strategies=(${=ZSH_AUTOSUGGEST_STRATEGY}) + + for strategy in $strategies; do + # Try to get a suggestion from this strategy + _zsh_autosuggest_strategy_$strategy "$1" + + # Ensure the suggestion matches the prefix + [[ "$suggestion" != "$1"* ]] && unset suggestion + + # Break once we've found a valid suggestion + [[ -n "$suggestion" ]] && break + done +} + +#--------------------------------------------------------------------# +# Async # +#--------------------------------------------------------------------# + +_zsh_autosuggest_async_request() { + zmodload zsh/system 2>/dev/null # For `$sysparams` + + typeset -g _ZSH_AUTOSUGGEST_ASYNC_FD _ZSH_AUTOSUGGEST_CHILD_PID + + # If we've got a pending request, cancel it + if [[ -n "$_ZSH_AUTOSUGGEST_ASYNC_FD" ]] && { true <&$_ZSH_AUTOSUGGEST_ASYNC_FD } 2>/dev/null; then + # Close the file descriptor and remove the handler + exec {_ZSH_AUTOSUGGEST_ASYNC_FD}<&- + zle -F $_ZSH_AUTOSUGGEST_ASYNC_FD + + # We won't know the pid unless the user has zsh/system module installed + if [[ -n "$_ZSH_AUTOSUGGEST_CHILD_PID" ]]; then + # Zsh will make a new process group for the child process only if job + # control is enabled (MONITOR option) + if [[ -o MONITOR ]]; then + # Send the signal to the process group to kill any processes that may + # have been forked by the suggestion strategy + kill -TERM -$_ZSH_AUTOSUGGEST_CHILD_PID 2>/dev/null + else + # Kill just the child process since it wasn't placed in a new process + # group. If the suggestion strategy forked any child processes they may + # be orphaned and left behind. + kill -TERM $_ZSH_AUTOSUGGEST_CHILD_PID 2>/dev/null + fi + fi + fi + + # Fork a process to fetch a suggestion and open a pipe to read from it + exec {_ZSH_AUTOSUGGEST_ASYNC_FD}< <( + # Tell parent process our pid + echo $sysparams[pid] + + # Fetch and print the suggestion + local suggestion + _zsh_autosuggest_fetch_suggestion "$1" + echo -nE "$suggestion" + ) + + # There's a weird bug here where ^C stops working unless we force a fork + # See https://github.com/zsh-users/zsh-autosuggestions/issues/364 + autoload -Uz is-at-least + is-at-least 5.8 || command true + + # Read the pid from the child process + read _ZSH_AUTOSUGGEST_CHILD_PID <&$_ZSH_AUTOSUGGEST_ASYNC_FD + + # When the fd is readable, call the response handler + zle -F "$_ZSH_AUTOSUGGEST_ASYNC_FD" _zsh_autosuggest_async_response +} + +# Called when new data is ready to be read from the pipe +# First arg will be fd ready for reading +# Second arg will be passed in case of error +_zsh_autosuggest_async_response() { + emulate -L zsh + + local suggestion + + if [[ -z "$2" || "$2" == "hup" ]]; then + # Read everything from the fd and give it as a suggestion + IFS='' read -rd '' -u $1 suggestion + zle autosuggest-suggest -- "$suggestion" + + # Close the fd + exec {1}<&- + fi + + # Always remove the handler + zle -F "$1" +} + +#--------------------------------------------------------------------# +# Start # +#--------------------------------------------------------------------# + +# Start the autosuggestion widgets +_zsh_autosuggest_start() { + # By default we re-bind widgets on every precmd to ensure we wrap other + # wrappers. Specifically, highlighting breaks if our widgets are wrapped by + # zsh-syntax-highlighting widgets. This also allows modifications to the + # widget list variables to take effect on the next precmd. However this has + # a decent performance hit, so users can set ZSH_AUTOSUGGEST_MANUAL_REBIND + # to disable the automatic re-binding. + if (( ${+ZSH_AUTOSUGGEST_MANUAL_REBIND} )); then + add-zsh-hook -d precmd _zsh_autosuggest_start + fi + + _zsh_autosuggest_bind_widgets +} + +# Mark for auto-loading the functions that we use +autoload -Uz add-zsh-hook is-at-least + +# Automatically enable asynchronous mode in newer versions of zsh. Disable for +# older versions because there is a bug when using async mode where ^C does not +# work immediately after fetching a suggestion. +# See https://github.com/zsh-users/zsh-autosuggestions/issues/364 +if is-at-least 5.0.8; then + typeset -g ZSH_AUTOSUGGEST_USE_ASYNC= +fi + +# Start the autosuggestion widgets on the next precmd +add-zsh-hook precmd _zsh_autosuggest_start diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/.editorconfig b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/.editorconfig new file mode 100644 index 00000000..3c6877cc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/.editorconfig @@ -0,0 +1,10 @@ +; This file is for unifying the coding style for different editors and IDEs. +; More information at https://editorconfig.org/ + +root = true + +[_*] +indent_style = space +indent_size = 2 +tab_width = 2 +end_of_line = LF diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/.github/ISSUE_TEMPLATE.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/.github/ISSUE_TEMPLATE.md new file mode 100644 index 00000000..8b137891 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/.github/ISSUE_TEMPLATE.md @@ -0,0 +1 @@ + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/.github/PULL_REQUEST_TEMPLATE.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/.github/PULL_REQUEST_TEMPLATE.md new file mode 100644 index 00000000..085d8ea9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/.github/PULL_REQUEST_TEMPLATE.md @@ -0,0 +1,10 @@ + + + + +- [ ] This compdef is not already available in zsh. +- [ ] This compdef is not already available in their original project. +- [ ] I am the original author, or I have authorization to submit this work. +- [ ] This is a finished work. +- [ ] It has a header containing authors, status and origin of the script. +- [ ] It has a license header or I accept that it will be licensed under the terms of the Zsh license. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/.gitignore b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/.gitignore new file mode 100644 index 00000000..c29589fc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/.gitignore @@ -0,0 +1,6 @@ +# zsh word code files +*.zwc + +# IDE files +.vscode/ +.idea/ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/CONTRIBUTING.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/CONTRIBUTING.md new file mode 100644 index 00000000..3d588e60 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/CONTRIBUTING.md @@ -0,0 +1,39 @@ +# Contributing + +## How to Contribute to zsh-completions + +Contributions are welcome, just make sure you follow the guidelines: + + * Completions are not accepted when already available in zsh. + * Completions are not accepted when already available in their original project. + * Please do not just copy/paste someone else's completion, ask before. + * Partially implemented completions are not accepted. + * Please add a header containing authors, status and origin of the script and license header if you do not wish to use the Zsh license (example [here](src/_tox)). + * Any reasonable open source license is acceptable but note that we recommend the use of the Zsh license and that you should use it if you hope for the function to migrate to zsh itself. + * Please try to follow the [Zsh completion style guide](https://github.com/zsh-users/zsh/blob/master/Etc/completion-style-guide). + * Please send one separate pull request per file. + * Send a pull request or ask for committer access. + +## Contributing Completion Functions to Zsh + +The zsh project itself welcomes completion function contributions via +[github pull requests](https://github.com/zsh-users/zsh/), +[gitlab merge requests](https://gitlab.com/zsh-org/zsh/) or via patch +files sent to its mailing list, `zsh-workers@zsh.org`. + +Contributing to zsh has the advantage of reaching the most users. + +## Including Completion Functions in Upstream Projects + +Many upstream projects include zsh completions. + +If well maintained, this has the advantage that users get a completion +function that matches the installed version of their software. + +If you are the upstream maintainer this is a good choice. If the project +already includes completions for bash, fish, tcsh, etc then they are +likely open to including zsh's too. It can also be a good option for +completions handling commands that are system or distribution specific. + +Ideally, arrange for the project's build system to install the +completion function in `$prefix/share/zsh/site-functions`. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/LICENSE b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/LICENSE new file mode 100644 index 00000000..d275ca9d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/LICENSE @@ -0,0 +1,25 @@ +The Z Shell is copyright (c) 1992-2017 Paul Falstad, Richard Coleman, +Zoltán Hidvégi, Andrew Main, Peter Stephenson, Sven Wischnowsky, and +others. All rights reserved. Individual authors, whether or not +specifically named, retain copyright in all changes; in what follows, they +are referred to as `the Zsh Development Group'. This is for convenience +only and this body has no legal status. The Z shell is distributed under +the following licence; any provisions made in individual files take +precedence. + +Permission is hereby granted, without written agreement and without +licence or royalty fees, to use, copy, modify, and distribute this +software and to distribute modified versions of this software for any +purpose, provided that the above copyright notice and the following +two paragraphs appear in all copies of this software. + +In no event shall the Zsh Development Group be liable to any party for +direct, indirect, special, incidental, or consequential damages arising out +of the use of this software and its documentation, even if the Zsh +Development Group have been advised of the possibility of such damage. + +The Zsh Development Group specifically disclaim any warranties, including, +but not limited to, the implied warranties of merchantability and fitness +for a particular purpose. The software provided hereunder is on an "as is" +basis, and the Zsh Development Group have no obligation to provide +maintenance, support, updates, enhancements, or modifications. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/README.md new file mode 100644 index 00000000..e1a7e562 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/README.md @@ -0,0 +1,71 @@ +zsh-completions ![GitHub release](https://img.shields.io/github/release/zsh-users/zsh-completions.svg) ![GitHub contributors](https://img.shields.io/github/contributors/zsh-users/zsh-completions.svg) [![IRC](https://img.shields.io/badge/IRC-%23zsh--completions-yellow.svg)](irc://irc.freenode.net/#zsh-completions) [![Gitter](https://badges.gitter.im/zsh-users/zsh-completions.svg)](https://gitter.im/zsh-users/zsh-completions?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) +============= + +**Additional completion definitions for [Zsh](https://www.zsh.org/).** + +*This projects aims at gathering/developing new completion scripts that are not available in Zsh yet. The scripts may be contributed to the Zsh project when stable enough.* + + +## Usage + +### Using packages + +| System | Package | +| ------------- | ------------- | +| Debian / Ubuntu | [zsh-completions OBS repository](https://software.opensuse.org/download.html?project=shells%3Azsh-users%3Azsh-completions&package=zsh-completions) | +| Fedora / CentOS / RHEL / Scientific Linux | [zsh-completions OBS repository](https://software.opensuse.org/download.html?project=shells%3Azsh-users%3Azsh-completions&package=zsh-completions) | +| OpenSUSE / SLE | [zsh-completions OBS repository](https://software.opensuse.org/download.html?project=shells%3Azsh-users%3Azsh-completions&package=zsh-completions) | +| Arch Linux / Manjaro / Antergos / Hyperbola | [zsh-completions](https://www.archlinux.org/packages/zsh-completions), [zsh-completions-git](https://aur.archlinux.org/packages/zsh-completions-git) | +| Gentoo / Funtoo | [app-shells/zsh-completions](https://packages.gentoo.org/packages/app-shells/zsh-completions) | +| NixOS | [zsh-completions](https://github.com/NixOS/nixpkgs/blob/master/pkgs/shells/zsh/zsh-completions/default.nix) | +| Void Linux | [zsh-completions](https://github.com/void-linux/void-packages/blob/master/srcpkgs/zsh-completions/template) | +| Slackware | [Slackbuilds](https://slackbuilds.org/repository/14.2/system/zsh-completions/) | +| macOS | [homebrew](https://github.com/Homebrew/homebrew-core/blob/master/Formula/zsh-completions.rb), [MacPorts](https://github.com/macports/macports-ports/blob/master/sysutils/zsh-completions/Portfile) | +| NetBSD | [pkgsrc](https://ftp.netbsd.org/pub/pkgsrc/current/pkgsrc/shells/zsh-completions/README.html) | +| FreeBSD | [shells/zsh-completions](https://www.freshports.org/shells/zsh-completions) | + + +### Using zsh frameworks + +#### [antigen](https://github.com/zsh-users/antigen) + +Add `antigen bundle zsh-users/zsh-completions` to your `~/.zshrc`. + +#### [oh-my-zsh](https://github.com/ohmyzsh/ohmyzsh) + +* Clone the repository inside your oh-my-zsh repo: + + git clone https://github.com/zsh-users/zsh-completions ${ZSH_CUSTOM:-${ZSH:-~/.oh-my-zsh}/custom}/plugins/zsh-completions + +* Add it to `FPATH` in your `.zshrc` by adding the following line before `source "$ZSH/oh-my-zsh.sh"`: + + fpath+=${ZSH_CUSTOM:-${ZSH:-~/.oh-my-zsh}/custom}/plugins/zsh-completions/src + +Note: adding it as a regular Oh My ZSH! plugin will not work properly (see [#603](https://github.com/zsh-users/zsh-completions/issues/603)). + +#### [zinit](https://github.com/zdharma-continuum/zinit) + +Add `zinit light zsh-users/zsh-completions` to your `~/.zshrc`. + +### Manual installation + +* Clone the repository: + + git clone https://github.com/zsh-users/zsh-completions.git + +* Include the directory in your `$fpath`, for example by adding in `~/.zshrc`: + + fpath=(path/to/zsh-completions/src $fpath) + +* You may have to force rebuild `zcompdump`: + + rm -f ~/.zcompdump; compinit + +### Contributing + +Contributions are welcome, see [CONTRIBUTING](https://github.com/zsh-users/zsh-completions/blob/master/CONTRIBUTING.md). + + +## License +Completions use the Zsh license, unless explicitly mentioned in the file header. +See [LICENSE](https://github.com/zsh-users/zsh-completions/blob/master/LICENSE) for more information. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_afew b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_afew new file mode 100644 index 00000000..140ca5ba --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_afew @@ -0,0 +1,65 @@ +#compdef afew +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for afew(version 3.0.1) an initial tagging script for notmuch mail. +# (https://github.com/teythoon/afew) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Jindřich Pilař (https://github.com/JindrichPilar) +# +# ------------------------------------------------------------------------------ + +_arguments \ + '(- 1 *)'{-h,--help}'[display usage information]' \ + '(- 1 *)'{-V,--version}"[show program's version number and exit]" \ + "(-t --tag -m --move-mails)"{-w,--watch}"[continuously monitor the mailbox for new messages matching the given query]" \ + "(-m --move-mails -w --watch)"{-t,--tag}"[run the tag filters]" \ + "(-w --watch -m --move-mails)"{-m,--move-mails}"[move mail files between maildir folders]" \ + "(-n --all)"{-a,--all}"[operate on all email]" \ + "(-a --new)"{-n,--new}"[operate on all new email]" \ + {-C,--notmuch-config=}"[specify path to notmuch configuration file]:files:_files" \ + {-e,--enable-filters=}"[specify filter classes to use]:filter" \ + {-d,--dry-run}"[don't change the DB]" \ + {-R,--reference-set-size=}"[specify size of the reference set]:size [1000]" \ + {-T,--reference-set-timeframe-days=}"[don't use emails older than specified age]:age (days) [30]" \ + {-N,--notmuch-args=}"[arguments for nutmuch new(in move mode)]:notmuch arg" \ + {-v,--verbose}"[be more verbose]" \ + '*: :_guard "^-*" query' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_android b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_android new file mode 100644 index 00000000..c26e2f8a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_android @@ -0,0 +1,308 @@ +#compdef android +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for the android command (Revision 12) +# (http://developer.android.com/guide/developing/tools/android.html). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# +# ------------------------------------------------------------------------------ + + +_android() { + typeset -A opt_args + local context state line curcontext="$curcontext" + + local ret=1 + + _arguments -C -A "-*" \ + '(- : *)'{-h,--help}'[get help on a specific command]:command:_android_cmds' \ + '(-s --silent -v --verbose)'{-v,--verbose}'[verbose mode: errors, warnings and informational messages are printed]' \ + '(-v --verbose -s --silent)'{-s,--silent}'[silent mode: only errors are printed out]' \ + '1: :_android_cmds' \ + '*::arg:->args' \ + && ret=0 + + case "$state" in + (args) + curcontext="${curcontext%:*:*}:android-cmd-$words[1]:" + case $words[1] in + (list) + _arguments -C \ + '1: :_android_list_entities' \ + '*::list-arg:->list-args' \ + && ret=0 + case "$state" in + (list-args) + case $words[1] in + (avd|target) + _arguments \ + '(-0 --null)'{-0,--null}'[terminate lines with \0 instead of \n (e.g. for xargs -0)]' \ + '(-c --compact)'{-c,--compact}'[compact output (suitable for scripts)]' \ + && ret=0 + ;; + (sdk) + _arguments \ + '(-o --obsolete)'{-o,--obsolete}'[install obsolete packages]' \ + '--proxy-host[HTTP/HTTPS proxy host (overrides settings if defined)]:proxy host:_hosts' \ + '--proxy-port[HTTP/HTTPS proxy port (overrides settings if defined)]:proxy port number' \ + '(-s --no-https)'{-s,--no-https}'[use HTTP instead of HTTPS (the default) for downloads]' \ + '(-u --no-ui)'{-u,--no-ui}'[display list result on console (no GUI)]' \ + && ret=0 + ;; + esac + ;; + esac + ;; + (create) + _arguments -C \ + '1: :_android_create_entities' \ + '*::create-arg:->create-args' \ + && ret=0 + case "$state" in + (create-args) + case $words[1] in + (avd) + _arguments \ + '(-c --sdcard)'{-c,--sdcard}'[path to a shared SD card image, or size of a new sdcard for the new AVD]:SD card image or size:_files -g "*.img"' \ + '(-n --name)'{-n,--name}'[name of the new AVD]:name' \ + '(-a --snapshot)'{-a,--snapshot}'[place a snapshots file in the AVD, to enable persistence]' \ + '(-p --path)'{-p,--path}'[directory where the new AVD will be created]: :_files -/' \ + '(-f --force)'{-f,--force}'[forces creation (overwrites an existing AVD)]' \ + '(-s --skin)'{-s,--skin}'[skin for the new AVD]:skin' \ + '(-t --target)'{-t,--target}'[target ID of the new AVD]: :_android_targets' \ + && ret=0 + ;; + (project) + _arguments \ + '(-n --name)'{-n,--name}'[project name]:project name' \ + '(-p --path)'{-p,--path}'[the new project'\''s directory]: :_files -/' \ + '(-k --package)'{-k,--package}'[Android package name for the application]:package name' \ + '(-a --activity)'{-a,--activity}'[name of the default Activity that is created]:activity name' \ + '(-t --target)'{-t,--target}'[target ID of the new project]: :_android_targets' \ + && ret=0 + ;; + (test-project) + _arguments \ + '(-n --name)'{-n,--name}'[project name]:project name' \ + '(-p --path)'{-p,--path}'[the new project'\''s directory]: :_files -/' \ + '(-m --main)'{-m,--main}'[path to directory of the app under test, relative to the test project directory]:path' \ + && ret=0 + ;; + (lib-project) + _arguments \ + '(-n --name)'{-n,--name}'[project name]:project name' \ + '(-p --path)'{-p,--path}'[the new project'\''s directory]: :_files -/' \ + '(-k --package)'{-k,--package}'[Android package name for the application]:package name' \ + '(-t --target)'{-t,--target}'[target ID of the new project]: :_android_targets' \ + && ret=0 + ;; + esac + ;; + esac + ;; + (update) + _arguments -C \ + '1: :_android_update_entities' \ + '*::update-arg:->update-args' \ + && ret=0 + case "$state" in + (update-args) + case $words[1] in + (avd) + _arguments \ + '(-n --name)'{-n,--name}'[name of the AVD to update]: :_android_avd_names' \ + && ret=0 + ;; + (project) + _arguments \ + '(-l --library)'{-l,--library}'[directory of an Android library to add, relative to this project'\''s directory]: :_files -/' \ + '(-p --path)'{-p,--path}'[the project'\''s directory]: :_files -/' \ + '(-n --name)'{-n,--name}'[project name]:name' \ + '(-t --target)'{-t,--target}'[target ID to set for the project]: :_android_targets' \ + '(-s --subprojects)'{-s,--subprojects}'[also updates any projects in sub-folders, such as test projects]' \ + && ret=0 + ;; + (test-project) + _arguments \ + '(-p --path)'{-p,--path}'[the project'\''s directory]: :_files -/' \ + '(-m --main)'{-m,--main}'[directory of the app under test, relative to the test project directory]:path' \ + && ret=0 + ;; + (lib-project) + _arguments \ + '(-p --path)'{-p,--path}'[the project'\''s directory]: :_files -/' \ + '(-t --target)'{-t,--target}'[target ID to set for the project]: :_android_targets' \ + && ret=0 + ;; + (sdk) + _arguments \ + '(-o --obsolete)'{-o,--obsolete}'[install obsolete packages]' \ + '--proxy-host[HTTP/HTTPS proxy host (overrides settings if defined)]:proxy host:_hosts' \ + '--proxy-port[HTTP/HTTPS proxy port (overrides settings if defined)]:proxy port number' \ + '(-s --no-https)'{-s,--no-https}'[use HTTP instead of HTTPS (the default) for downloads]' \ + '(-u --no-ui)'{-u,--no-ui}'[update from command-line (no GUI)]' \ + '(-f --force)'{-f,--force}'[force replacement of a package or its parts, even if something has been modified]' \ + '(-t --filter)'{-t,--filter}'[a filter that limits the update to the specified types of packages]: :_android_sdk_update_filters -s ,' \ + '(-n --dry-mode)'{-n,--dry-mode}'[simulate the update but does not download or install anything]' \ + && ret=0 + ;; + esac + ;; + esac + ;; + (move) + _arguments -C \ + '1: :_android_move_entities' \ + '*::move-arg:->move-args' \ + && ret=0 + case "$state" in + (move-args) + case $words[1] in + (avd) + _arguments \ + '(-n --name)'{-n,--name}'[name of the AVD to move or rename]: :_android_avd_names' \ + '(-p --path)'{-p,--path}'[path to the AVD'\''s new directory]: :_files -/' \ + '(-r --rename)'{-r,--rename}'[new name of the AVD]:name' \ + && ret=0 + ;; + esac + ;; + esac + ;; + (delete) + _arguments -C \ + '1: :_android_delete_entities' \ + '*::delete-arg:->delete-args' \ + && ret=0 + case "$state" in + (delete-args) + case $words[1] in + (avd) + _arguments \ + '(-n --name)'{-n,--name}'[name of the AVD to delete]: :_android_avd_names' \ + && ret=0 + ;; + esac + ;; + esac + ;; + (display) + _arguments \ + '1: :_android_display_entities' \ + && ret=0 + ;; + esac + ;; + esac + + return ret +} + +(( $+functions[_android_cmds] )) || +_android_cmds() { + local commands; commands=( + 'list:list existing targets or virtual devices' + 'create:create new virtual devices or projects' + 'update:update a virtual device, project, SDK or adb' + 'move:move a virtual device' + 'delete:delete a virtual device' + 'avd:displays the AVD Manager window' + 'sdk:displays the SDK Manager window' + 'display:display manager windows' + ) + _describe -t commands 'command' commands "$@" +} + +(( $+functions[_android_list_entities] )) || +_android_list_entities() { + local entities; entities=( + 'avd:list existing Android Virtual Devices' + 'target:list existing targets' + 'sdk:list remote SDK repository' + ) + _describe -t entities 'entity' entities "$@" +} + +(( $+functions[_android_create_entities] )) || +_android_create_entities() { + local entities; entities=( + 'avd:create a new Android Virtual Device' + 'project:create a new Android project' + 'test-project:create a new Android project for a test package' + 'lib-project:create a new Android library project' + ) + _describe -t entities 'entity' entities "$@" +} + +(( $+functions[_android_update_entities] )) || +_android_update_entities() { + local entities; entities=( + 'avd:update an Android Virtual Device to match the folders of a new SDK' + 'project:update an Android project' + 'test-project:update the Android project for a test package' + 'lib-project:update an Android library project' + 'adb:update adb to support the USB devices declared in the SDK add-ons' + 'sdk:update the SDK by suggesting new platforms to install if available' + ) + _describe -t entities 'entity' entities "$@" +} + +(( $+functions[_android_move_entities] )) || +_android_move_entities() { + local entities; entities=( + 'avd:move or rename an Android Virtual Device' + ) + _describe -t entities 'entity' commands "$@" +} + +(( $+functions[_android_delete_entities] )) || +_android_delete_entities() { + local entities; entities=( + 'avd:delete an Android Virtual Device' + ) + _describe -t entities 'entity' entities "$@" +} + +(( $+functions[_android_display_entities] )) || +_android_display_entities() { + local entities; entities=( + 'sdk:display the SDK Manager window' + 'avd:display the AVD Manager window' + ) + _describe -t entities 'entity' entities "$@" +} + +(( $+functions[_android_targets] )) || +_android_targets() { + local targets; targets=(${(f)"$(_call_program targets $service list target --compact)"//:/\\:}) + _describe -t targets 'target' targets "$@" +} + +(( $+functions[_android_avd_names] )) || +_android_avd_names() { + local avd_names; avd_names=(${(f)"$(_call_program targets $service list avd --compact)"//:/\\:}) + _describe -t avd-names 'AVD name' avd_names "$@" +} + +(( $+functions[_android_sdk_update_filters] )) || +_android_sdk_update_filters() { + local filters; filters=(platform tool platform-tool doc sample extra) + _values $@ 'filter' "${filters[@]}" +} + +_android "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_archlinux-java b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_archlinux-java new file mode 100644 index 00000000..49fe9037 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_archlinux-java @@ -0,0 +1,85 @@ +#compdef archlinux-java +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for archlinux-java a tool for selecting default Java runtime (https://wiki.archlinux.org/index.php/java). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Jindřich Pilař (https://github.com/JindrichPilar) +# +# ------------------------------------------------------------------------------ + + +_archlinux-java_command_arguments() { + case $words[1] in + (set) + local java_versions=("${(@f)$(archlinux-java status | tail -n +2 | tr -s ' ' | cut -d ' ' -f2)}") + _describe -t output 'Downloads to delete' java_versions + ;; + esac +} + +_archlinux-java() { + local -a commands + + commands=( + "status:List installed Java environments and enabled one" + "get:Return the short name of the Java environment set as default" + "set:Force as default" + "unset:Unset current default Java environment" + "fix:Fix an invalid/broken default Java environment configuration" + "help:Show help" + ) + + _arguments -C \ + '1:cmd:->cmds' \ + '*:: :->args' \ + + case "$state" in + (cmds) + _describe -t commands 'commands' commands + ;; + (*) + _archlinux-java_command_arguments + ;; + esac +} + +_archlinux-java + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_artisan b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_artisan new file mode 100644 index 00000000..8f9f0690 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_artisan @@ -0,0 +1,63 @@ +#compdef artisan +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for artisan (http://laravel.com/docs/artisan). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * loranger (https://github.com/loranger) +# * Yohan Tambè (https://github.com/Cronos87) +# +# ------------------------------------------------------------------------------ + + +_artisan_get_command_list () { + IFS=" " + php artisan --no-ansi | \ + sed "1,/Available commands/d" | \ + awk '/ [a-z]+/ { print $1 }' | \ + sed -E 's/^[ ]+//g' | \ + sed -E 's/[:]+/\\:/g' | \ + sed -E 's/[ ]{2,}/\:/g' +} + +_artisan () { + if [ -f artisan ]; then + local -a commands + IFS=$'\n' + commands=(`_artisan_get_command_list`) + _describe 'commands' commands + fi +} + +compdef _artisan php artisan +compdef _artisan artisan diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_atach b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_atach new file mode 100644 index 00000000..5e88dab1 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_atach @@ -0,0 +1,71 @@ +#compdef atach +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for atach (https://github.com/sorin-ionescu/atach). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Sorin Ionescu +# +# ------------------------------------------------------------------------------ + +local state mode_values existing_sessions ret=1 + +mode_values=( + "none:disable redrawing" + "ctrl_l:use ctrl + l to redraw" + "winch:use sigwinch to redraw" +) + +existing_sessions=($(_call_program session atach)) + +_arguments -C -s -S \ + '(--list -l)'{--list,-l}'[list sessions]' \ + '(--sockets -L)'{--sockets,-L}'[list sockets]' \ + '(--session -s)'{--session=,-s+}'[set the session name]:session' \ + '(--char -c)'{--char=,-c+}'[set the detach character (default: ^\\)]:char' \ + '(--redraw -r)'{--redraw=,-r+}'[set the redraw method (none, ctrl_l, or winch)]:mode:->mode' \ + '(--detached -d)'{--detached,-d}'[start the session detached]' \ + '(--no-detach -D)'{--no-detach,-D}'[disable detaching]' \ + '(--no-suspend -Z)'{--no-suspend,-Z}'[disable suspending]' \ + '(--version -v)'{--version,-v}'[display version and copyright]' \ + '(--help -h)'{--help,-h}'[display help]' \ + '(-)::args:->session-or-command' && ret=0 + +case "$state" in + (mode) + _describe -t mode 'redraw mode' mode_values && ret=0 + ;; + (session-or-command) + _describe -t 'session' 'sessions' existing_sessions && ret=0 + _path_commands && ret=0 + ;; +esac + +return $ret + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_avdmanager b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_avdmanager new file mode 100644 index 00000000..9b181d8d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_avdmanager @@ -0,0 +1,197 @@ +#compdef avdmanager +# ------------------------------------------------------------------------------ +# Copyright (c) 2023 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for avdmanager(https://developer.android.com/studio/command-line/avdmanager) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_avdmanager() { + typeset -A opt_args + local context state line + local curcontext="$curcontext" + local ret=1 + + _arguments -C -A "-*" \ + '(- *)'{-h,--help}'[Print help message]' \ + '(-s --silent)'{-s,--silent}'[Silent mode, shows error only]' \ + '(-v --verbose)'{-v,--verbose}'[Verbose mode, shows errors, warnings and all messages]' \ + '--clear-cache[Clear the SDK Manager repository manifest cache]' \ + '1: :_avdmanager_subcommands' \ + '*::arg:->args' \ + && ret=0 + + case "$state" in + (args) + if (( $+functions[_avdmanager_${words[1]}] )); then + _avdmanager_${words[1]} && ret=0 + else + ret=0 + fi + ;; + esac + + return ret +} + +(( $+functions[_avdmanager_list] )) || +_avdmanager_list() { + local ret=1 + + _arguments -C \ + '1: :(avd target device)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (avd|target|device) + _arguments \ + '(-0 --null)'{-0,--null}'[Terminate lines with \0 instead of \n]' \ + '(-c --compact)'{-c,--compact}'[Compact output]' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_avdmanager_create] )) || +_avdmanager_create() { + local ret=1 + + _arguments -C \ + '1: :(avd)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (avd) + _arguments \ + '(-c --sdcard)'{-c,--sdcard}'[Path to a shared SD card image]: :_files' \ + '(-g --tag)'{-g,--tag}'[The sys-img tag to use for the AVD]:tag' \ + '(-p --path)'{-p,--path}'[Directory where the new AVD will be created]' \ + '(-k --package)'{-k,--package}'[Package path of the system image for this AVD]:package' \ + '(-n --name)'{-n,--name}'[Name of the new AVD]:name' \ + '--skin[The optional name of a skin to use with this device]' \ + '(-f --force)'{-f,--force}'[Forces creation]' \ + '(-b --abi)'{-b,--abi}'[The ABI to use for the AVD]:abi' \ + '(-d --device)'{-d,--device}'[The optional device definition to use]' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_avdmanager_move] )) || +_avdmanager_move() { + local ret=1 + + _arguments -C \ + '1: :(avd)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (avd) + _arguments \ + '(-p --path)'{-p,--path}"[Path to the AVD's new directory]: :_files -/" \ + '(-n --name)'{-n,--name}'[Name of the AVD to delete]: :_avdmanager_avds' \ + '(-r --rename)'{-r,--rename}'[New name of the AVD]' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_avdmanager_delete] )) || +_avdmanager_delete() { + local ret=1 + + _arguments -C \ + '1: :(avd)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (avd) + _arguments \ + '(-n --name)'{-n,--name}'[Name of the AVD to delete]: :_avdmanager_avds' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_avdmanager_subcommands] )) || +_avdmanager_subcommands() { + local -a commands=( + "list:Lists existing targets or virtual devices" + "create:Creates a new Android Virtual Device" + "move:Moves or renames an Android Virtual Device" + "delete:Deletes an Android Virtual Device" + ) + _describe -t commands 'subcommand' commands +} + +(( $+functions[_avdmanager_avds] )) || +_avdmanager_avds() { + local -a avds=(${(@f)"$(avdmanager list avd -c)"}) + _values 'android virtual devices' $avds +} + +_avdmanager "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_bitcoin-cli b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_bitcoin-cli new file mode 100644 index 00000000..5178a8da --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_bitcoin-cli @@ -0,0 +1,230 @@ +#compdef bitcoin-cli +# ------------------------------------------------------------------------------ +# Copyright (c) 2017 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for bitcoin-cli (https://bitcoin.org). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Ian Ker-Seymer (https://github.com/ianks) +# * notmike +# ------------------------------------------------------------------------------ + +_bitcoin-cli() { + local context state line curcontext="$curcontext" + + _arguments -C \ + -?'[This help message]' \ + -addrinfo'[Get the number of addresses known to the node, per network and total, after filtering for quality and recency. Total number of addresses known to the node may be higher.]' \ + -chain='[Use the chain (default: main). Allowed values: main, test, signet, regtest]:chain:(main test signet regtest)' \ + -color='[Color setting for CLI output (default: auto). Valid values: always, auto, never]:when:(always auto never)' \ + -conf='[Specify configuration file. Relative paths will be prefixed by datadir location. (default: bitcoin.conf)]:PATH:_files' \ + -datadir='[Specify data directory]:PATH:_directories' \ + -getinfo='[Get general information from the remote server.]' \ + -testnet'[Use the test chain]' \ + -regtest'[Enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.]' \ + -named'[Pass named instead of positional arguments (default: false)]' \ + -netinfo=-'[Get network peer connection information from the remote server.]::level_or_help:(0 1 2 3 4 help)' \ + -stdin'[Read extra arguments from standard input, one per line until EOF/Ctrl-D (recommended for sensitive information such as passphrases)]' \ + -rpcport='[Connect to JSON-RPC on (default: 8332, testnet: 18332, regtest: 18443)]: :_guard "[[\:digit\:]]#" "PORT"' \ + -rpcwait'[Wait for RPC server to start]' \ + -rpcuser='[Username for JSON-RPC connections]:RPCUSER:()' \ + -rpcpassword='[Password for JSON-RPC connections]:RPCPASSWORD:()' \ + -rpcconnect='[Send commands to node running on (default: 127.0.0.1)]:RPCCONNECT:_hosts' \ + -rpcclienttimeout='[Timeout during HTTP requests, or 0 for no timeout. (default: 900)]: :_guard "[[\:digit\:]]#" "RPCCLIENTTIMEOUT"' \ + -version'[Print version and exit]' \ + ':subcommand:->subcommand' && ret=0 + + case $state in + subcommand) + subcommands=( + 'getbestblockhash' + 'getblock' + 'getblockchaininfo' + 'getblockcount' + 'getblockfilter' + 'getblockfrompeer' + 'getblockhash' + 'getblockheader' + 'getblockstats' + 'getchaintips' + 'getchaintxstats' + 'getdeploymentinfo' + 'getdifficulty' + 'getmempoolancestors' + 'getmempooldescendants' + 'getmempoolentry' + 'getmempoolinfo' + 'getrawmempool' + 'gettxout' + 'gettxoutproof' + 'gettxoutsetinfo' + 'gettxspendingprevout' + 'preciousblock' + 'pruneblockchain' + 'savemempool' + 'scantxoutset' + 'verifychain' + 'verifytxoutproof' + 'getmemoryinfo' + 'getrpcinfo' + 'help' + 'logging' + 'stop' + 'uptime' + 'getblocktemplate' + 'getmininginfo' + 'getnetworkhashps' + 'prioritisetransaction' + 'submitblock' + 'submitheader' + 'addnode' + 'clearbanned' + 'disconnectnode' + 'getaddednodeinfo' + 'getconnectioncount' + 'getnettotals' + 'getnetworkinfo' + 'getnodeaddresses' + 'getpeerinfo' + 'listbanned' + 'ping' + 'setban' + 'setnetworkactive' + 'analyzepsbt' + 'combinepsbt' + 'combinerawtransaction' + 'converttopsbt' + 'createpsbt' + 'createrawtransaction' + 'decodepsbt' + 'decoderawtransaction' + 'decodescript' + 'finalizepsbt' + 'fundrawtransaction' + 'getrawtransaction' + 'joinpsbts' + 'sendrawtransaction' + 'signrawtransactionwithkey' + 'testmempoolaccept' + 'utxoupdatepsbt' + 'enumeratesigners' + 'createmultisig' + 'deriveaddresses' + 'estimatesmartfee' + 'getdescriptorinfo' + 'signmessagewithprivkey' + 'validateaddress' + 'verifymessage' + 'abandontransaction' + 'abortrescan' + 'addmultisigaddress' + 'backupwallet' + 'bumpfee' + 'createwallet' + 'dumpprivkey' + 'dumpwallet' + 'encryptwallet' + 'getaddressesbylabel' + 'getaddressinfo' + 'getbalance' + 'getbalances' + 'getnewaddress' + 'getrawchangeaddress' + 'getreceivedbyaddress' + 'getreceivedbylabel' + 'gettransaction' + 'getunconfirmedbalance' + 'getwalletinfo' + 'importaddress' + 'importdescriptors' + 'importmulti' + 'importprivkey' + 'importprunedfunds' + 'importpubkey' + 'importwallet' + 'keypoolrefill' + 'listaddressgroupings' + 'listdescriptors' + 'listlabels' + 'listlockunspent' + 'listreceivedbyaddress' + 'listreceivedbylabel' + 'listsinceblock' + 'listtransactions' + 'listunspent' + 'listwalletdir' + 'listwallets' + 'loadwallet' + 'lockunspent' + 'migratewallet' + 'newkeypool' + 'psbtbumpfee' + 'removeprunedfunds' + 'rescanblockchain' + 'restorewallet' + 'send' + 'sendall' + 'sendmany' + 'sendtoaddress' + 'sethdseed' + 'setlabel' + 'settxfee' + 'setwalletflag' + 'signmessage' + 'signrawtransactionwithwallet' + 'simulaterawtransaction' + 'unloadwallet' + 'upgradewallet' + 'walletcreatefundedpsbt' + 'walletdisplayaddress' + 'walletlock' + 'walletpassphrase' + 'walletpassphrasechange' + 'walletprocesspsbt' + 'getzmqnotifications' + ) + + _describe -t subcommands 'bitcoin-cli subcommands' subcommands && ret=0 + esac + + return ret +} + +_bitcoin-cli "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_bower b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_bower new file mode 100644 index 00000000..75e43422 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_bower @@ -0,0 +1,163 @@ +#compdef bower +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Bower (https://bower.io). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Joe Lencioni (https://github.com/lencioni) +# +# ------------------------------------------------------------------------------ + + +local curcontext="$curcontext" state line _opts ret=1 + +_arguments -C \ + '(- 1 *)'{-v,--version}'[display version information]' \ + '1: :->cmds' \ + '*:: :->args' && ret=0 + +case $state in + cmds) + _values "bower command" \ + "cache[manage bower cache]" \ + "help[display help information about Bower]" \ + "home[opens a package homepage into your favorite browser]" \ + "info[info of a particular package]" \ + "init[interactively create a bower.json file]" \ + "install[install a package locally]" \ + "link[symlink a package folder]" \ + "list[list local packages - and possible updates]" \ + "login[authenticate with GitHub and store credentials]" \ + "lookup[look up a package URL by name]" \ + "prune[removes local extraneous packages]" \ + "register[register a package]" \ + "search[search for a package by name]" \ + "update[update a local package]" \ + "uninstall[remove a local package]" \ + "unregister[remove a package from the registry]" \ + "version[bump a package version]" && ret=0 + _arguments \ + '(--force)--force[make various commands more forceful]' \ + '(--json)--json[output consumable JSON]' \ + '(--log-level)--log-level[what level of logs to report]' \ + "(--offline)--offline[don't hit the network]" \ + '(--quiet)--quiet[only output important information]' \ + "(--silent)--silent[don't output anything, besides errors]" \ + '(--verbose)--verbose[make output more verbose]' \ + '(--allow-root)--allow-root[allow running commands as root]' \ + '(--version)--version[output Bower version]' \ + '(--no-color)--no-color[disable colors]' && ret=0 + ;; + args) + case $line[1] in + help) + _values 'commands' \ + 'cache' \ + 'home' \ + 'info' \ + 'init' \ + 'install' \ + 'link' \ + 'list' \ + 'login' \ + 'lookup' \ + 'prune' \ + 'register' \ + 'search' \ + 'update' \ + 'uninstall' \ + 'unregister' \ + 'version' && ret=0 + ;; + (home|info|init|link|lookup|prune|register|search|unregister) + _arguments \ + '(--help)--help[show help message]' && ret=0 + ;; + install) + _arguments \ + '(--force-latest)--force-latest[force latest version on conflict]' \ + '(--help)--help[show help message]' \ + "(--production)--production[don't install project devDependencies]" \ + "(--save)--save[save installed packages into the project's bower.json dependencies]" \ + "(--save-dev)--save-dev[save installed packages into the project's bower.json devDependencies]" && ret=0 + ;; + list) + _arguments \ + '(--help)--help[show help message]' \ + '(--paths)--paths[generate a simple JSON source mapping]' \ + '(--relative)--relative[make paths relative to the directory config property, which defaults to bower_components]' && ret=0 + ;; + login) + _arguments \ + '(--help)--help[show help message]' \ + '(-t --token)'{-t,--token}'[Pass GitHub auth token (will not prompt for username/password)]' && ret=0 + ;; + uninstall) + _arguments \ + '(--help)--help[show help message]' \ + "(--save)--save[save installed packages into the project's bower.json dependencies]" \ + "(--save-dev)--save-dev[save installed packages into the project's bower.json devDependencies]" && ret=0 + ;; + update) + _arguments \ + '(--force-latest)--force-latest[force latest version on conflict]' \ + '(--help)--help[show help message]' \ + "(--production)--production[don't install project devDependencies]" && ret=0 + ;; + version) + _arguments \ + '(--message)--message[custom git commit and tag message]' && ret=0 + ;; + exec) + _normal && ret=0 + ;; + *) + _opts=( $(bower help $line[1] | sed -e '/^ \[-/!d; s/^ \[\(-[^=]*\)=.*/\1/') ) + _opts+=( $(bower help $line[1] | sed -e '/^ -/!d; s/^ \(-.\), \[\(-[^=]*\)=.*/\1 \2/') ) + if [[ $_opts != "" ]]; then + _values 'option' $_opts && ret=0 + fi + ;; + esac + ;; +esac + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_bundle b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_bundle new file mode 100644 index 00000000..f6dbb64e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_bundle @@ -0,0 +1,353 @@ +#compdef bundle +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Bundler 2.4.1 (https://bundler.io/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Bruno Michel (https://github.com/nono) +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +local curcontext="$curcontext" state line ret=1 + +_bundle_commands() { + local -a commands=( + "install:Install the gems specified by the Gemfile or Gemfile.lock" + "update:Update dependencies to their latest versions" + "cache:Package the .gem files required by your application" + "exec:Execute a script in the context of the current bundle" + "config:Specify and read configuration options for bundler" + "help:Describe available tasks or one specific task" + "add:Add the named gem to the Gemfile and run bundle install" + "binstubs:Generate binstubs for executables in a gem" + "check:Determine whether the requirements for your application are installed" + "show:Show the source location of a particular gem in the bundle" + "outdated:Show all of the outdated gems in the current bundle" + "console:Start an IRB session in the context of the current bundle" + "open:Open an installed gem in the editor" + "list:Show all of the gems in the current bundle" + "lock:Generate a lockfile for your dependencies" + "viz:Generate a visual representation of your dependencies" + "init:Generate a simple Gemfile, placed in the current directory" + "gem:Create a simple gem, suitable for development with bundler" + "platform:Displays platform compatibility information" + "clean:Clean up unused gems in your Bundler directory" + "doctor:Display warnings about common problems" + "remove:Removes gems from the Gemfile" + ) + + _describe -t commands 'command' commands "$@" +} + +_bundle_gems() { + local -a gems=($(bundle show | awk '/^ / { print $2 }')) + if [[ $? == 0 ]]; then + _values 'gems' $gems + fi +} + +_bundle_groups() { + if [[ -e Gemfile ]]; then + local -a groups=(${(@f)"$(awk '/^ *group *:/{sub(/^ *group *:/, ""); print $1}' Gemfile)"}) + _values 'groups' $groups + fi +} + +_bundle_config_subcommands() { + local subcommands; + subcommands=( + "list:print a list of all bundler configuration" + "get:print the value of that configuration setting" + "set:set defaults to setting configuration" + "unset:delete the configuration" + ) + _describe -t subcommands 'subcommand' subcommands "$@" +} + +_arguments -C -A "-v" -A "--version" \ + '(- 1 *)'{-v,--version}'[display version information]' \ + '(-r --retry)'{-r,--retry}'[specify the number of times you with to attempt network commands]:number:' \ + '(-v --verbose)'{-V,--verbose}'[print out additional logging information]' \ + '--no-color[print all output without color]' \ + '1: :_bundle_commands' \ + '*:: :->args' && ret=0 + +case $state in + args) + case $words[1] in + help) + local -a commands=('install' 'update' 'cache' 'exec' 'config' 'help' 'add' 'binstubs' + 'check' 'show' 'outdated' 'console' 'open' 'list' 'lock' 'lock' 'viz' 'init' + 'gem' 'platform' 'clean' 'doctor' 'remove') + _arguments -C \ + '1: :($commands)' \ + && ret=0 + ;; + install) + local -a policies=('HighSecurity' 'MediumSecurity' 'LowSecurity' 'AlmostNoSecurity' 'NoSecurity') + _arguments \ + '--binstubs=-[generate bin stubs for bundled gems to ./bin]:directory:_files -/' \ + '--clean[remove any gems not present in the current Gemfile]' \ + '--deployment[install using defaults tuned for deployment environments]' \ + '--redownload[force download every gem, even if the required versions are already available locally]' \ + '--frozen[do not allow the Gemfile.lock to be updated after this install]' \ + '--full-index[download and cache the index file of all gems]' \ + '--gemfile=-[use the specified gemfile instead of Gemfile]:gemfile:_files' \ + '(-j --jobs)'{-j,--jobs}'[the maximum number of parallel download and install jobs]:number' \ + '--local[do not attempt to connect to rubygems.org]' \ + '--no-cache[do not update the cache in vendor/cache with newly installed gems]' \ + '--no-prune[do not remove stale gem from cache after installation]' \ + '--path=-[specify a different path than the system default]:path:_files' \ + '--quiet[only output warnings and errors]' \ + '--shebang=-[specify ruby executable to execute scripts]:ruby:_files' \ + '--standalone=-[create standalone bundles]:groups:_bundle_groups' \ + '--system[install to the system location]' \ + "--trust-policy=-[apply the Rubygems security policy]:arg:($policies)" \ + '--with=-[include gems that are part of the specified named group]:groups:_bundle_groups' \ + '--without=-[exclude gems that are part of the specified named group]:groups:_bundle_groups' \ + && ret=0 + ;; + update) + _arguments \ + '--all[update all gems specified in Gemfile]' \ + \*{--group,-g}=-'[only update the gems in the specified group]' \ + '--source=-[the name of a source used in the Gemfile]:url' \ + '--local[do not attempt to fetch gems remotely and use the gem cached instead]' \ + '--ruby[update the locked version of Ruby to the current version of Ruby]' \ + '--bundler[update the locked version of bundler to invoked bundler version]' \ + '--full-index[fall back to using the single-file index of all gems]' \ + '(-j --jobs)'{-j,--jobs}'[specify the number of jobs to run in parallel]:number' \ + '--retry=-[retry failed network or git requests for number times]:number' \ + '--quiet[only output warnings and errors]' \ + '--redownload[force download every gem, even if the required versions are already available locally]' \ + '--patch[prefer updating only to next patch version]' \ + '--minor[prefer updating only to next minor version]' \ + '--major[prefer updating only to next major version (default)]' \ + '--strict[do not allow any gem to be updated past latest --patch | --minor | --major]' \ + '--conservative[use bundle install conservative update behavior]' \ + '*:: :_bundle_gems' \ + && ret=0 + ;; + cache) + _arguments \ + '--all[include all sources]' \ + '--all-platforms[include gems for all platforms present in the lockfile, not only the current one]' \ + '--cache-path=-[specify a different cache path than the default(vendor/cache)]: :_files -/' \ + '--gemfile=-[use the specified gemfile instead of Gemfile]:gemfile:_files' \ + "--no-install[don't install the gems, only update the cache]" \ + "--no-prune[don't remove stale gems from the cache]" \ + '--path=-[specify a different path than the system default($BUNDLE_PATH or $GAM_HOME)]: :_files' \ + '--quite[only output warnings and errors]' \ + '--frozen[do not allow the Gemfile.lock to be updated after this bundle cache operation]' \ + '--no-color[disable colorization in output]' \ + '(-r --retry)'{-r,--retry}=-'[specify the number of times you with to attempt network commands]:nums' \ + '(-V --verbose)'{-v,--verbose}'[enable verbose output mode]' \ + && ret=0 + ;; + exec) + _arguments \ + '--keep-file-descriptors[exec will revert to the 1.9 behavior of passing all file descriptors to the new process]' \ + '*:: :_normal' \ + && ret=0 + ;; + config) + _arguments -C \ + '1: :_bundle_config_subcommands' \ + '--local[use local configuration]' \ + '--global[use global configuration]' \ + && ret=0 + ;; + add) + _arguments \ + '(-v --version)'{-v,--version}=-'[specify version requirements for the added gem]:version' \ + '(-g --group)'{-g,--group}=-'[specify the group for the added gem]:group:_bundle_groups' \ + '(-s --source)'{-s,--source}=-'[specify the source for the added gem]: :_files' \ + '(-r --require)'{-r,--require}=-'[adds require path to gem]: :_files' \ + '--path=-[specify the file path for the added gem]: :_files -/' \ + '--git=-[specify the git source for the added gem]:git' \ + '--github=-[specify the github source for the added gem]:github' \ + '--branch=-[specify the git branch for the added gem]:branch' \ + '--ref=-[specify the git ref for the added gem]' \ + '--skip-install[adds the gem to the Gemfile but does not install it]' \ + '--optimistic[adds optimistic declaration of version]' \ + '--strict[adds strict declaration of version]' \ + '1::gem:' \ + && ret=0 + ;; + binstubs) + _arguments \ + '--force[overwrite existing binstubs if they exist]' \ + '--path=-[the location to install the specified binstubs to]: :_files -/' \ + '--standalone[makes binstubs that can work without depending on Rubygems or Bundler at runtime]' \ + '--shebang=-[specify a different shebang executable name than the default(default: ruby)]: :_files' \ + '--all[create binstubs for all gems in the bundle]' \ + '1::gem:' \ + && ret=0 + ;; + check) + _arguments \ + '--dry-run[locks the Gemfile before running the command]' \ + '--gemfile=-[use the specified gemfile instead of the Gemfile]: :_files' \ + '--path=-[specify a different path than the system default($BUNDLE_PATH or $GEM_HOME)]: :_files -/' \ + && ret=0 + ;; + show) + _arguments \ + '--paths[list the paths of all gems that are required by your Gemfile]' \ + '1:: :_bundle_gems' \ + && ret=0 + ;; + outdated) + _arguments \ + '--local[do not attempt to fetch gems remotely and use the gem cache instead]' \ + '--pre[check for newer pre-release gems]' \ + '--source[check against a specific source]' \ + '--strict[only list newer versions allowed by your Gemfile requirements]' \ + {--parseable,--porcelain}'[use minimal formatting for more parsable output]' \ + '--group=-[list gems from a specific group]:group:_bundle_groups' \ + '--groups[list gems organized by groups]' \ + '--major[prefer updating to next major version(default)]' \ + '--minor[prefer updating only to next minor version]' \ + '--patch[prefer updating only to next patch version]' \ + '--filter-major[only list major new versions]' \ + '--filter-minor[only list minor new versions]' \ + '--filter-patch[only list patch new versions]' \ + '--only-explicit[only list gems specified in your Gemfile, not their dependencies]' \ + '*:: :_bundle_gems' \ + && ret=0 + ;; + console) + _arguments \ + '--no-color[disable colorization in output]' \ + '(-r --retry)'{-r,--retry}=-'[specify the number of times you with to attempt network commands]:num' \ + '(-v --verbose)'{-v,--verbose}=-'[enable verbose output mode]' \ + '1:: :_bundle_groups' \ + && ret=0 + ;; + open) + _arguments \ + '1:: :_bundle_gems' \ + && ret=0 + ;; + list) + _arguments \ + '--name-only[print only the name of each gem]' \ + '--paths[print the path to each gem in the bundle]' \ + '--without-group=-[a space-separated list of groups of gems to skip during printing]: :_bundle_groups' \ + '--only-group=-[a space-separated list of groups of gems to print]: :_bundle_groups' \ + && ret=0 + ;; + lock) + _arguments \ + '--update=-[ignores the existing lockfile]' \ + '--local[do not attempt to connect to rubygems.org]' \ + '--print[prints the lockfile to STDOUT instead of writing to the file system]' \ + '--lockfile=-[the path where the lick file should be written to]: :_files' \ + '--full-index[fall back to using the single file index of all gems]' \ + '--add-platform=-[add a new platform to the lockfile, re-resolving for the addition of that platform]' \ + '--remove-platform=-[remove a platform from the lockfile]' \ + '--patch[if updating, prefer updating only to next patch version]' \ + '--minor[if updating, prefer updating only to next minor version]' \ + '--major[if updating, prefer updating to next major version(default)]' \ + '--strict[if updating, do not allow any gem to be updated past latest --patch | --minor | --major]' \ + '--conservative[if updating, use bundle install conservative update behavior]' \ + && ret=0 + ;; + viz) + _arguments \ + '(-f --file)'{-f,--file}=-'[the name to use for the generated file]: :_files' \ + '(-F --format)'{-F,--format}=-'[output format option]: :(png jpg svg dot)' \ + '(-R --requirements)'{-r,--requirements}'[set to show the version of each required dependency]' \ + '(-v --version)'{-v,--version}'[set to show each version]' \ + '(-W --without)'{-W,--without}'[exclude gems that are part of the specified named group]' \ + && ret=0 + ;; + init) + _arguments \ + '--gemspec=-[use the specified .gemspec to create the Gemfile]: :_files' \ + && ret=0 + ;; + gem) + _arguments \ + '(--exe -b --bin --no-exe)'{--exe,-b,--bin}'[specify that bundler should create a binary executable in the generated rubygem project]' \ + '(--exe -b --bin --no-exe)--no-exe[do not create a binary]' \ + '(--no-coc)--coc[add a CODE_OF_CONDUCT.md to the root of the generated project]' \ + '(--coc)--no-coc[do not create a CODE_OF_CONDUCT.md]' \ + '(--no-ext --ext)--ext=[add boilerplate for C or Rust extension code to the generated project]: :(c rust)' \ + '(--ext --no-ext)--no-ext[do not add extension code]' \ + '(--no-mit --mit)--mit[add an MIT license to a LICENSE.txt file in the root of the generated project]' \ + '(--mit --no-mit)--no-mit[do not create a LICENSE.txt]' \ + '(-t --test)'{-t,--test}=-'[specify the test framework]: :(minitest rspec test-unit)' \ + '--ci=-[specify the continuous integration service]: :(github travis gitlab circle)' \ + '--linter=-[specify the linter and code formatter]: :(rubocop standard)' \ + '(-e --edit)'{-e,--edit}=-'[open the resulting GEM_NAME.gemspec in EDITOR]' \ + '1::gem_name:' \ + && ret=0 + ;; + platform) + _arguments \ + '--ruby[it will display the ruby directive information]' \ + && ret=0 + ;; + clean) + _arguments \ + '--dry-run[print the changes, but do not clean the unused gems]' \ + '--force[forces cleaning up unused gems even if Bundler is configured to use globally installed gems]' \ + && ret=0 + ;; + doctor) + _arguments \ + '--quiet[only output warnings and errors]' \ + '--gemfile=-[the location of the Gemfile which Bundler should use]: :_files' \ + && ret=0 + ;; + remove) + _arguments \ + '--install[runs bundle install after the given gem have been removed from the Gemfile]' \ + '*:: :_bundle_gems' \ + && ret=0 + ;; + esac + ;; +esac + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cap b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cap new file mode 100644 index 00000000..6f6fb67e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cap @@ -0,0 +1,93 @@ +#compdef cap +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Capistrano 3.17.1 (https://capistranorb.com/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Bruno Michel (https://github.com/nono) +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + + +local curcontext="$curcontext" state line cmds ret=1 + +_arguments -C \ + '--backtrace=[Enable full backtrace]: :(stderr stdout)' \ + '--comments[Show commented tasks only]' \ + '--job-stats[Display job statistics]:level' \ + '--suppress-backtrace[Suppress backtrace lines matching regexp PATTERN]:pattern' \ + '(-A --all)'{-A,--all}'[Show all tasks, even uncommented ones]' \ + '(-B --build-all)'{-B,--build-all}'[Build all prerequisites, including those which are up-to-date]' \ + '(-C --directory)'{-C,--directory}'[Change to DIRECTORY before doing anything]: :_files -/' \ + '(-D --describe)'{-D,--describe}'[Describe the tasks, then exit]:pattern' \ + '(-E --execute-continue)'{-E,--execute-continue}'[Execute Ruby code and exit]:code' \ + '(-f --rakefile)'{-f,--rakefile}'[Use FILENAME as the rakefile to search for]: :_files' \ + '(-G --no-system --nosystem)'{-G,--no-system,--nosystem}'[Use standard project Rakefile search paths, ignore system wide rakefiles]' \ + '(-g --system)'{-g,--system}'[Using system wide rakefiles]' \ + '(-I --libdir)'\*{-I,--libdir}'[Include LIBDIR in the search path for required modules]: :_files -/' \ + '(-j --jobs)'{-j,--jobs}'[Specifies the maximum number of tasks to execute in parallel]:num' \ + '(-m --multitask)'{-m,--multitask}'[Treat all tasks as multitasks]' \ + '(-N --no-search --nosearch)'{-N,--no-search,--nosearch}'[Do not search parent directories for the Rakefile]' \ + '(-P --prereqs)'{-P,--prereqs}'[Display the tasks and dependencies, then exit]' \ + '--execute-print[Execute some Ruby code, print the result, then exit]:code' \ + '--require[Require MODULE before executing rakefile]:module' \ + '(-R --rakelibdir --rakelib)'{-R,--rakelibdir,--rakelib}'[Auto-import any .rake files in RAKELIBDIR]: :_files -/' \ + '(-t --trace)'{-t,--trace}'[Turn on invoke/execute tracing, enable full backtrace]: :(stderr stdout)' \ + '(-T --tasks)'{-T,--tasks}'[Display the tasks with descriptions]::pattern' \ + '(-W --where)'{-W,--where}'[Describe the tasks then exit]::pattern' \ + '(-X --no-deprecation-warnings)'{-X,--no-deprecation-warnings}'[Disable the deprecation warnings]' \ + '(- *)'{-V,--version}'[Display the program version]' \ + '(-n --dry-run)'{-n,--dry-run}'[Do a dry run without executing actions]' \ + '(-r --roles)'{-r,--roles}'[Run SSH commands only on hosts matching these roles]:roles' \ + '(-z --hosts)'{-z,--hosts}'[Run SSH commands only on matching hosts]:hosts' \ + '(-p --print-config-variables)'{-p,--print-config-variables}'[Display the defined config variables before starting the deployment tasks]' \ + '(- *)'{-h,-H,--help}'[Display help message]' \ + '*: :->cmds' && ret=0 + +case $state in + cmds) + cmds=( ${(f)"$(_call_program commands cap -T 2>/dev/null | sed -e '/ # /!d; s/:/\\:/g; s/cap \([A-Za-z0-9\\:_-]*\) .*# /\1:/')"} ) + _describe -t commands 'cap command' cmds && ret=0 + ;; +esac + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cask b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cask new file mode 100644 index 00000000..5fd1e1c6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cask @@ -0,0 +1,89 @@ +#compdef cask +# ------------------------------------------------------------------------------ +# Copyright (c) 2014 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY DIRECT, INDIRECT, +# INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR +# PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF +# LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING +# NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, +# EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for cask (https://cask.readthedocs.io) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * ptrv +# * Johan Andersson +# * Sebastien Duthil +# +# ------------------------------------------------------------------------------ + +function _cask() { + local ret=1 state + _arguments \ + ':subcommand:->subcommand' \ + '*:: :->subcmds' && ret=0 + + case $state in + subcommand) + subcommands=( + "build:build all Elisp files in the files directive" + "clean-elc:remove all byte compiled Elisp files in the files directive" + "exec:execute command with correct 'exec-path' and 'load-path'" + "exec-path:print 'exec-path' for all packages and dependencies" + "files:print list of files specified in the files directive" + "help:display usage information or documentation for specified command" + "info:show info about the current package" + "init:initialize the current directory with a Cask-file" + "install:install all packages specified in the Cask-file" + "link:manage links" + "list:list dependencies" + "load-path:print 'load-path' for all packages and dependencies" + "outdated:print list of outdated packages" + "package:build package and put in specified directory (default: dist)" + "package-directory:print current package installation directory" + "path:print 'exec-path' for all packages and dependencies" + "pkg-file:write a 'define-package' file" + "update:update package version" + "upgrade-cask:upgrade Cask itself and its dependencies" + "upgrade:upgrade Cask itself and its dependencies" + "version:print program version" + ) + _describe -t subcommands 'cask subcommands' subcommands && ret=0 + esac + + case "$words[1]" in + init) + _arguments \ + '(--dev)--dev[Run in dev mode]' && ret=0 ;; + exec) + _generic + ;; + esac + + return ret +} + +_cask "$@" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ccache b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ccache new file mode 100644 index 00000000..72d619dd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ccache @@ -0,0 +1,350 @@ +#compdef ccache -P -value-,CCACHE_*,-default- + +# zsh completion script for ccache 4.6.1 + +# Copyright 2018 CERN for the benefit of the LHCb Collaboration. + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this +# list of conditions and the following disclaimer. +# +# * Redistributions in binary form must reproduce the above copyright notice, +# this list of conditions and the following disclaimer in the documentation +# and/or other materials provided with the distribution. +# +# * Neither the name of the copyright holder nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +# FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +# CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +# OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# In applying this licence, CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization +# or submit itself to any jurisdiction. + +# allow users to define their better compilers +# inspired by _cmake_compilers +# users could override with +# +# _ccache_compilers() { +# local -a _ccache_compilers +# _ccache_compilers=(gcc g++ clang clang++) +# _wanted compilers expl "compiler" compadd -- $_ccache_compilers +# } +(( $+functions[_ccache_compilers] )) || +_ccache_compilers() { + _command_names -e +} + +_ccache_booleans() { + _message 'There are no "false" values, unset variable to disable' + local description; description=${1:-boolean} + local booleans; booleans=( + 'true' + 'yes' + ) + _describe -t booeans "$description" booleans +} + +(( $+functions[_ccache_compressionlevels] )) || +_ccache_compressionlevels() { + local -a one_nine + one_nine=(1 2 3 4 5 6 7 8 9) + _describe -t onetonine "compression level (if using compression)" one_nine +} + +(( $+functions[_ccache_sloppiness] )) || +_ccache_sloppiness() { + _values -s ',' \ + "file_macro[ignore __FILE__]" \ + "file_stat_matches[rely on mtimes and ctimes]" \ + "include_file_ctime[ignore headers' ctime too new]" \ + "include_file_mtime[ignore headers' mtime too new]" \ + "no_system_headers[exclude system headers from cache]" \ + "pch_defines[be sloppy about #defines in pch]" \ + "time_macros[ignore __date__ and __time__]" +} + +(( $+functions[_ccache_compilerchecks] )) || +_ccache_compilerchecks() { + local -a compiler_check_values + compiler_check_values=( + 'content: the actual compiler binary' + 'mtime: mtime and size of the compiler' + 'none: ignore compiler for hashing' + 'string\:: any hard coded string (pre-computed version)' + '%compiler%\ -v:any compiler invocation output' + ) + _describe -t compilerchecks "compiler information included in the hash" compiler_check_values +} + +(( $+functions[_ccache_dirlevels] )) || +_ccache_dirlevels() { + local -a one_eight + one_eight=(1 2 3 4 5 6 7 8) + _describe -t onetoeight "directory levels in the cache directory" one_eight +} + +if [[ "$service" = -value-* ]]; then + case $service in + *CCACHE_*DIR*) + # CCACHE_BASEDIR: relative to which top level paths are hashed + # CCACHE_DIR: where the cache and config are kept + # CCACHE_TEMPDIR: where temporary files are kept + # all: a single path + _path_files -/ + ;; + *CCACHE_NLEVELS*) + _ccache_dirlevels + ;; + *CCACHE_CC*) + _ccache_compilers + ;; + *CCACHE_COMPILERCHECK*) + _ccache_compilerchecks + ;; + *CCACHE_*COMPRESS*) + _ccache_booleans "write compressed cache" + ;; + *CCACHE_COMPRESSLEVEL*) + _ccache_compressionlevels + ;; + *CCACHE_EXTENSION*) + _alternative ':set extension for intermediate files: ' + ;; + *CCACHE_*DIRECT*) + _ccache_booleans "use direct mode" + ;; + *CCACHE_*DISABLE*) + _ccache_booleans "disable cache usage" + ;; + *CCACHE_EXTRAFILES*) + local sep=: + compset -P "*${sep}" + compset -S "${sep}*" || suf="$sep" + + _files "" -r "${sep}"' /\t\t\-' "$@" + ;; + *CCACHE_*HARDLINK*) + _ccache_booleans "create hard links rather than copies" + ;; + *CCACHE_*HASHDIR*) + _ccache_booleans "include the cwd in the hash" + ;; + *CCACHE_IGNOREHEADERS*) + _dir_list + ;; + *CCACHE_*COMMENTS*) + _ccache_booleans "consider comments in hashing" + ;; + *CCACHE_LIMIT_MULTIPLE*) + _alternative ":clean up down to level (e.g. 0.8): " + ;; + *CCACHE_LOGFILE*) + _path_files -g "*(/) *.log" + ;; + *CCACHE_MAXFILES*) + _alternative ":maximum number of files in the cache (0= no limit): " + ;; + *CCACHE_MAXSIZE*) + _alternative ':maximum cache size (0= no limit) with suffix k,M,G,T or Ki,Mi,Gi,Ti: ' + ;; + *CCACHE_PATH*) + _alternative ':PATH for compiler lookup (instead of $PATH):_dir_list' + ;; + *CCACHE_PREFIX*) + _alternative ':prefixes for compiler invocation: ' + ;; + *CCACHE_PREFIX_CPP*) + _alternative ':prefixes for preprocessor invocation: ' + ;; + *CCACHE_*READONLY*) + _ccache_booleans "treat cache as read-only" + ;; + *CCACHE_*READONLY_DIRECT*) + _ccache_booleans "retrieve from read-only cache in direct mode" + ;; + *CCACHE_*RECACHE*) + _ccache_booleans "use cache in write-only mode" + ;; + *CCACHE_*CPP2*) + _ccache_booleans "pass original rather than preprocessed source code to compiler" + ;; + *CCACHE_SLOPPINESS*) + _ccache_sloppiness + ;; + *CCACHE_*STATS*) + _ccache_booleans "update statistics counters" + ;; + *CCACHE_UMASK*) + _alternative ":umask value (octal): " + ;; + *CCACHE_*UNIFY*) + _ccache_booleans "normalise sources prior to processing" + ;; + esac + + return +fi + +__ccache_config_keys() { + local -a keys + keys=( + 'compression:write compressed cache' + 'direct_mode:use direct mode' + 'disable:disable cache usage' + 'hard_link:create hard links rather than copies' + 'hash_dir:include the cwd in the hash' + 'keep_comments_cpp:consider comments in hashing' + 'read_only:treat cache as read-only' + 'read_only_direct:retrieve from read-only cache in direct mode' + 'recache:use cache in write-only mode' + 'run_second_cpp:pass original rather than preprocessed source code to compiler' + 'stats:update statistics counters' + 'unify:normalise sources prior to processing' + 'base_dir:specify relative to which top level paths are hashed' + 'temporary_dir:specify where temporary files are kept' + 'cache_dir:specify where the cache is kept' + 'compiler:specify compiler' + 'cache_dir_levels:directory levels in the cache directory' + 'compiler_check:compiler information included in the hash' + 'compression_level:cache compression level' + 'cpp_extension:set extensions for intermediate files' + 'extra_files_to_hash:additional files to consider in hashing' + 'ignore_headers_in_manifest:set paths to headers to ignore in hashing' + 'limit_multiple:cleanup level' + 'log_file:specify a log file' + 'max_files:maximum number of files in the cache' + 'max_size:maximum size of the cache' + 'path:PATH for compiler lookup (instead of $PATH)' + 'prefix_command:prefixes for compiler invocation' + 'prefix_command_cpp:prefixes for preprocessor invocation' + 'sloppiness:hash files sloppy' + 'umask:set umask for ccache and child processes (e.g. for sharing cache)' + ) + _describe -t configkeys "configuration keys" keys -S '=' +} + +if compset -P '--set-config=*='; then + case $IPREFIX in + *=compression= | *=direct_mode= | *=disable= | *=hard_link= | *=hash_dir= | *=keep_comments_cpp= | *=read_only= | *=read_only_direct= | *=recache= | *=run_second_cpp= | *=stats= | *=unify= ) + local booleans; booleans=( + 'true' + 'false' + ) + _describe -t booleans 'boolean' booleans + ;; + *=base_dir= | *=temporary_dir= | *=cache_dir=) + _path_files -/ + ;; + *=compiler=) + _ccache_compilers + ;; + *=cache_dir_levels=) + _ccache_dirlevels + ;; + *=compiler_check=) + _ccache_compilerchecks + ;; + *=compression_level=) + _ccache_compressionlevels + ;; + *=cpp_extension=) + _alternative ':set extension for intermediate files: ' + ;; + *=extra_files_to_hash=) + local sep=: + compset -P "*${sep}" + compset -S "${sep}*" || suf="$sep" + + _files "" -r "${sep}"' /\t\t\-' "$@" + ;; + *=ignore_headers_in_manifest=) + _dir_list + ;; + *=limit_multiple=) + _alternative ":clean up down to level (e.g. 0.8): " + ;; + *=log_file=) + _path_files -g "*(/) *.log" + ;; + *=max_files=) + _alternative ":maximum number of files in the cache (0= no limit): " + ;; + *=max_size=) + _alternative ':maximum cache size (0= no limit) with suffix k,M,G,T or Ki,Mi,Gi,Ti: ' + ;; + *=path=) + _alternative ':PATH for compiler lookup (instead of $PATH):_dir_list' + ;; + *=prefix_command=) + _alternative ':prefixes for compiler invocation: ' + ;; + *=prefix_command_cpp=) + _alternative ':prefixes for preprocessor invocation: ' + ;; + *=sloppiness=) + _ccache_sloppiness + ;; + *=umask=) + _alternative ":umask value (octal): " + ;; + esac +elif [[ $words[2] == -* ]]; then + # if the first argument starts with -, we are in configure-ccache mode + _arguments \ + '*'{-o,--set-config=}"[set configuration key]:keys:__ccache_config_keys" \ + '(: -)'{-h,--help}'[show help message]' \ + '(: -)'{-V,--version}'[print version and copyright information]' \ + '(-c --cleanup)'{-c,--cleanup}'[delete old files and recalculate size counters]' \ + '(-C --clear)'{-C,--clear}'[clear the cache completely (except configuration)]' \ + '--config-path[operate on configuration file PATH instead of the default]: :_files' \ + '(-d --dir)'{-d,--dir}'[operate on cache directory PATH instead of the default]: :_files -/' \ + '--evict-namespace[remove file created in namespace NAMESPACE]:namespace' \ + '--evict-older-than[remove files older than AGE]:age' \ + '(-F --max-files=)'{-F,--max-files=}'[set maximum number of files in cache]:number of files in cache: ' \ + '(-M --max-size=)'{-M,--max-size=}'[set maximum size of cache]:cache size: ' \ + '(-X --recompress)'{-X,--recompress}'[recompress the cache to level LEVEL]:level' \ + \*{-o,--set-config}'[set configuration item KEY to value VAL]:key_val' \ + '(-p --show-config)'{-p,--show-config}'[show current configuration options]' \ + '--show-log-stats[print statistics counters from the stas log in human-readable format]' \ + '(-s --show-stats)'{-s,--show-stats}'[show statistics summary]' \ + '(-v --verbose)'{-v,--verbose}'[increase verbosity]' \ + '(-z --zero-stats)'{-z,--zero-stats}'[zero statistics counters]' \ + '--trim-dir[remove old files from directory _PATH_]: :_files -/' \ + '--trim-max-size[specify the maximum size for --trim-dir]:size' \ + '--trim-method[specify the method for --trim-dir]: :(atime mtime)' \ + '--checksum-file[print the checksum of the file at PATH]: :_files' \ + '--extract-result[extract file data stored in result file at PATH to the current working directory]' \ + '(-k --get-config)'{-k,--get-config}'[print the value of configuration key]:key' \ + '--hash-file[print the hash of the file at PATH]: :_files' \ + '--inspect[print result/manifest file at PATH in human-readable format]' \ + '--print-stats[print statistics counter IDs and corresponding values in machine-parsable format]' +elif [[ $CURRENT -eq 2 ]]; then + _ccache_compilers +else + # the command line already looks like 'ccache ...' + # forward to the completion function of the compiler + (( CURRENT-- )) + shift words + _normal +fi + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cf b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cf new file mode 100644 index 00000000..3f0ae192 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cf @@ -0,0 +1,994 @@ +#compdef cf +# ------------------------------------------------------------------------------ +# +# Copyright 2015 Ferran Rodenas & Danny Rosen +# +# 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 +# +# https://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. +# +# ------------------------------------------------------------------------------ +# +# Description +# ----------- +# +# Completion script for Cloud Foundry CLI (https://github.com/cloudfoundry/cli#downloads) +# +# ------------------------------------------------------------------------------ +# +# Authors +# ------- +# +# * Ferran Rodenas (https://github.com/frodenas) +# * Danny Rosen (https://github.com/dannyzen) +# +# ------------------------------------------------------------------------------ + +# ---------------------- +# ----- Helper functions +# ---------------------- + +# Output a selectable list of organizations +__cf_orgs() { + declare -a cont_cmd + cont_cmd=($(CF_COLOR=false CF_TRACE=false cf orgs | awk 'NR>3{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'ORG' cont_cmd +} + +# Output a selectable list of spaces +__cf_spaces() { + declare -a cont_cmd + cont_cmd=($(CF_COLOR=false CF_TRACE=false cf spaces | awk 'NR>3{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'SPACE' cont_cmd +} + +# Output a selectable list of applications +__cf_apps() { + declare -a cont_cmd + cont_cmd=($(CF_COLOR=false CF_TRACE=false cf apps | awk 'NR>4{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'APP' cont_cmd +} + +# Output a selectable list of stacks +__cf_stacks() { + declare -a cont_cmd + cont_cmd=($(CF_COLOR=false CF_TRACE=false cf stacks | awk 'NR>4{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'STACK' cont_cmd +} + +# Output a selectable list of services +__cf_marketplace_services() { + declare -a cont_cmd + cont_cmd=($(CF_COLOR=false CF_TRACE=false cf marketplace | awk 'NR>4{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'SERVICE' cont_cmd +} + +# Output a selectable list of services +__cf_services() { + declare -a cont_cmd + cont_cmd=($(CF_COLOR=false CF_TRACE=false cf services | awk 'NR>4{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'SERVICE' cont_cmd +} + +# Output a selectable list of domains +__cf_domains() { + declare -a cont_cmd + cont_cmd=($(CF_COLOR=false CF_TRACE=false cf domains | grep -v shared | awk 'NR>2{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'DOMAIN' cont_cmd +} + +# Output a selectable list of shared domains +__cf_shared_domains() { + declare -a cont_cmd + cont_cmd=($(CF_COLOR=false CF_TRACE=false cf domains | grep -v owned | awk 'NR>2{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'SHARED-DOMAIN' cont_cmd +} + +# Output a selectable list of hostnames +__cf_hostnames() { + declare -a cont_cmd + cont_cmd=($(CF_COLOR=false CF_TRACE=false cf routes | awk 'NR>3{print $2}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'ROUTE' cont_cmd +} + +# Output a selectable list of buildpacks +__cf_buildpacks() { + declare -a cont_cmd + cont_cmd=($(CF_COLOR=false CF_TRACE=false cf buildpacks | awk 'NR>3{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'BUILDPACK' cont_cmd +} + +# Output a selectable list of feature flags +__cf_feature_flags() { + declare -a cont_cmd + cont_cmd=($(CF_COLOR=false CF_TRACE=false cf feature-flags | awk 'NR>4{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'FEATURE-FLAG' cont_cmd +} + +# Output a selectable list of plugin repos +__cf_repo_plugins() { + declare -a cont_cmd + cont_cmd=($(CF_COLOR=false CF_TRACE=false cf list-plugin-repos | awk 'NR>3{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'REPO-PLUGIN' cont_cmd +} + +# Output a selectable list of plugins +__cf_plugins() { + declare -a cont_cmd + cont_cmd=($(cf plugins | awk 'NR>4{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'PLUGIN' cont_cmd +} + +# Output a selectable list of targets (requires cf-targets plugin) +__cf_targets() { + declare -a cont_cmd + cont_cmd=($(cf targets | awk '{print $1}')) + if [[ 'X$cont_cmd' != 'X' ]] + _describe 'TARGET' cont_cmd +} + + +# -------------------------- +# ----- end Helper functions +# -------------------------- + +# -------------- +# ----- Commands +# -------------- + +__login() { + _arguments \ + '-a=[API endpoint (e.g. https://api.example.com)]:api endpoint:' \ + '-u=[Username]:username:' \ + '-p=[Password]:password:' \ + '-o=[Organization]:organization name:__cf_orgs' \ + '-s=[Space]:space name:__cf_spaces' \ + '--sso[Use a one-time password to login]' \ + '--skip-ssl-validation[Skip SSL validation]' +} + +__logout() { + # no arguments +} + +__passwd() { + _arguments \ + '1:password:' +} + +__target() { + _arguments \ + '-o=[Organization]:organization name:__cf_orgs' \ + '-s=[Space]:space name:__cf_spaces' +} + +__api() { + _arguments \ + '1:API url:' \ + '--unset[Remove all api endpoint targeting]' \ + '--skip-ssl-validation[Skip SSL validation]' +} + +__auth() { + # no arguments +} + +__apps() { + # no arguments +} + +__app() { + _arguments \ + '1:application name:__cf_apps' \ + '--guid[Retrieve and display the given app guid. All other health and status output for the app is suppressed]' +} + +__push() { + _arguments \ + '1:application name:__cf_apps' \ + '-b=[Custom buildpack by name (e.g. my-buildpack) or GIT URL or GIT BRANCH URL]:buildpack name:__cf_buildpacks' \ + '-c=[Startup command, set to null to reset to default start command]:startup command:' \ + '-d=[Domain (e.g. example.com)]:domain (e.g. example.com):__cf_domains' \ + '-f=[Path to manifest]:file:_files:' \ + '-i=[Number of instances]:number of instances:' \ + '-k=[Disk limit (e.g. 256M, 1024M, 1G)]:disk limit (e.g. 256M, 1024M, 1G):' \ + '-m=[Memory limit (e.g. 256M, 1024M, 1G)]:memory limit (e.g. 256M, 1024M, 1G):' \ + '-n=[Hostname (e.g. my-subdomain)]:hostname (e.g. my-subdomain):' \ + '-p=[Path to app directory or to a zip file of the contents of the app directory]:file:_files' \ + '-s=[Stack to use (a stack is a pre-built file system, including an operating system, that can run apps)]:stack name:__cf_stacks:' \ + '-t=[Maximum time (in seconds) for CLI to wait for application start, other server side timeouts may apply]:maximum time (in seconds):' \ + '--no-hostname[Map the root domain to this app]' \ + '--no-manifest[Ignore manifest file]' \ + '--no-route[Do not map a route to this app and remove routes from previous pushes of this app]' \ + '--no-start[Do not start an app after pushing]' \ + '--random-route[Create a random route for this app]' +} + +__scale() { + _arguments \ + '1:application name:__cf_apps' \ + '-i=[Number of instances]:number of instances:' \ + '-k=[Disk limit (e.g. 256M, 1024M, 1G)]:disk limit (e.g. 256M, 1024M, 1G):' \ + '-m=[Memory limit (e.g. 256M, 1024M, 1G)]:memory limit (e.g. 256M, 1024M, 1G):' \ + '-f[Force restart of app without prompt]' +} + +__delete() { + _arguments \ + '1:application name:__cf_apps' \ + '--f[Force deletion without confirmation]' \ + '--r[Also delete any mapped routes]' +} + +__rename() { + _arguments \ + '1:application name:__cf_apps' \ + '2:application name:' +} + +__start() { + _arguments \ + '1:application name:__cf_apps' +} + +__stop() { + _arguments \ + '1:application name:__cf_apps' +} + +__restart() { + _arguments \ + '1:application name:__cf_apps' +} + +__restage() { + _arguments \ + '1:application name:__cf_apps' +} + +__restart-app-instance() { + _arguments \ + '1:application name:__cf_apps' \ + '2:application index:' +} + +__events() { + _arguments \ + '1:application name:__cf_apps' +} + +__files() { + _arguments \ + '1:application name:__cf_apps' \ + '2::path:' \ + '-i=[instance]' +} + +__logs() { + _arguments \ + '1:application name:__cf_apps' \ + '--recent[Dump recent logs instead of tailing]' +} + +__env() { + _arguments \ + '1:application name:__cf_apps' +} + +__set-env() { + _arguments \ + '1:application name:__cf_apps' \ + '2:env var name:' \ + '3:env var value:' +} + +__unset-env() { + _arguments \ + '1:application name:__cf_apps' \ + '2:env var name:' +} + +__stacks() { + # no arguments +} + +__stack() { + _arguments \ + '1:stack name:__cf_stacks' \ + '--guid[Retrieve and display the given stack guid. All other output for the stack is suppressed]' +} + +__copy-source() { + _arguments \ + '1:source application name:__cf_apps' \ + '2:target application name:' \ + '-o=[Org that contains the target application]:organization name:__cf_orgs' \ + '-s=[Space that contains the target application]:space name:__cf_spaces' \ + '--no-restart[Override restart of the application in target environment after copy-source completes]' +} + +__create-app-manifest() { + _arguments \ + '1:application name:__cf_apps' \ + '-p=[Specify a path for file creation. If path not specified, manifest file is created in current working directory]:path:_files' +} + +__marketplace() { + _arguments \ + '-s=[Show plan details for a particular service offering]' +} + +__services() { + # no arguments +} + +__service() { + _arguments \ + '1:service name:__cf_services' \ + '--guid[Retrieve and display the given service guid. All other output for the service is suppressed]' +} + +__create-service() { + _arguments \ + '1:service:__cf_marketplace_services' \ + '2:plan:' \ + '3:service name:' \ + '-c=[Valid JSON object containing service-specific configuration parameters, provided either in-line or in a file]' \ + '-t=[User provided tags]' +} + +__update-service() { + _arguments \ + '1:service name:__cf_services' \ + '-p=[Change service plan for a service instance]' \ + '-c=[Valid JSON object containing service-specific configuration parameters, provided either in-line or in a file]' \ + '-t=[User provided tags]' +} + +__rename-service() { + _arguments \ + '1:service name:__cf_services' \ + '2:service name:' +} + +__delete-service() { + _arguments \ + '1:service name:__cf_services' \ + '-f[Force deletion without confirmation]' +} + +__create-service-key() { + _arguments \ + '1:service name:__cf_services' \ + '2:service key:' \ + '-c=[Valid JSON object containing service-specific configuration parameters, provided either in-line or in a file]' +} + +__service-keys() { + _arguments \ + '1:service name:__cf_services' +} + +__service-key() { + _arguments \ + '1:service name:__cf_services' \ + '2:service key:' +} + +__delete-service-key() { + _arguments \ + '1:service name:__cf_services' \ + '2:service key:' \ + '-f[Force deletion without confirmation]' +} + +__bind-service() { + _arguments \ + '1:application name:__cf_apps' \ + '2:service name:__cf_services' \ + '-c=[Valid JSON object containing service-specific configuration parameters, provided either in-line or in a file]' +} + +__unbind-service() { + _arguments \ + '1:application name:__cf_apps' \ + '2:service name:__cf_services' +} + +__create-user-provided-service() { + _arguments \ + '1:service name:' \ + '-p=[Credentials]' \ + '-l=[Syslog Drain Url]' +} + +__update-user-provided-service() { + _arguments \ + '1:service name:__cf_services' \ + '-p=[Credentials]' \ + '-l=[Syslog Drain Url]' +} + +__orgs() { + # no arguments +} + +__org() { + _arguments \ + '1:organization name:__cf_orgs' \ + '--guid[Retrieve and display the given org guid. All other output for the org is suppressed]' +} + +__create-org() { + _arguments \ + '1:organization name:' \ + '-q=[Quota to assign to the newly created org (excluding this option results in assignment of default quota)]' +} + +__delete-org() { + _arguments \ + '1:organization name:__cf_orgs' \ + '-f[Force deletion without confirmation]' +} + +__spaces() { + # no arguments +} + +__space() { + _arguments \ + '1:space name:__cf_spaces' \ + '--guid[Retrieve and display the given space guid. All other output for the space is suppressed]' \ + '--security-group-rules[Retrieve the rules for all the security groups associated with the space]' +} + +__create-space() { + _arguments \ + '1:space name:' \ + '-o=[Org that contains the target application]:organization name:__cf_orgs' \ + '-q=[Quota to assign to the newly created space (excluding this option results in assignment of default quota)]' +} + +__delete-space() { + _arguments \ + '1:space name:__cf_spaces' \ + '-f[Force deletion without confirmation]' +} + +__domains() { + # no arguments +} + +__create-domain() { + _arguments \ + '1:organization name:__cf_orgs' \ + '2:domain:' +} + +__delete-domain() { + _arguments \ + '1:domain:__cf_domains' \ + '-f[Force deletion without confirmation]' +} + +__create-shared-domain() { + _arguments \ + '1:domain:' +} + +__delete-shared-domain() { + _arguments \ + '1:domain:__cf_shared_domains' \ + '-f[Force deletion without confirmation]' +} + +__routes() { + _arguments \ + '--orglevel[List all the routes for all spaces of current organization]' +} + +__create-route() { + _arguments \ + '1:space name:__cf_spaces' \ + '2:domain:__cf_domains' \ + '-n=[Hostname]' +} + +__check-route() { + _arguments \ + '1:hostname:__cf_hostnames' \ + '2:domain:__cf_domains' +} + +__map-route() { + _arguments \ + '1:application name:__cf_apps' \ + '2:domain:__cf_domains' \ + '-n=[Hostname]:hostname:__cf_hostnames:' +} + +__unmap-route() { + _arguments \ + '1:application name:__cf_apps' \ + '2:domain:__cf_domains' \ + '-n=[Hostname]:hostname:__cf_hostnames:' +} + +__delete-route() { + _arguments \ + '1:domain:__cf_domains' \ + '-n=[Hostname]:hostname:__cf_hostnames:' \ + '-f[Force deletion without confirmation]' +} + +__delete-orphaned-routes() { + _arguments \ + '-f[Force deletion without confirmation]' +} + +__buildpacks() { + # no arguments +} + +__create-buildpack() { + _arguments \ + '1:buildpack name:' \ + '2:path:_files' \ + '3:position:' \ + '--enable[Enable the buildpack to be used for staging]' \ + '--disable[Disable the buildpack from being used for staging]' +} + +__update-buildpack() { + _arguments \ + '1:buildpack name:__cf_buildpacks' \ + '-p=[Path to directory or zip file]:file:_files' \ + '-i=[The order in which the buildpacks are checked during buildpack auto-detection]' \ + '--enable[Enable the buildpack to be used for staging]' \ + '--disable[Disable the buildpack from being used for staging]' \ + '--lock[Lock the buildpack to prevent updates]' \ + '--unlock[Unlock the buildpack to enable updates]' +} + +__rename-buildpack() { + _arguments \ + '1:buildpack name:__cf_buildpacks' \ + '2:new buildpack name:' +} + +__delete-buildpack() { + _arguments \ + '1:buildpack name:__cf_buildpacks' \ + '-f[Force deletion without confirmation]' +} + +__running-environment-variable-group() { + # no arguments +} + +__staging-environment-variable-group() { + # no arguments +} + +__set-staging-environment-variable-group() { + # no arguments +} + +__set-running-environment-variable-group() { + # no arguments +} + +__feature-flags() { + # no arguments +} + +__feature-flag() { + _arguments \ + '1:feature name:__cf_feature_flags' +} + +__enable-feature-flag() { + _arguments \ + '1:feature name:__cf_feature_flags' +} + +__disable-feature-flag() { + _arguments \ + '1:feature name:__cf_feature_flags' +} + +__curl() { + _arguments \ + '1:path:' \ + '-i[Include response headers in the output]' \ + '-v[Enable CF_TRACE output for all requests and responses]' \ + '-X=[HTTP method]:http method:(GET POST PUT DELETE)' \ + '-h=[Custom headers to include in the request, flag can be specified multiple times]' \ + '-d=[HTTP data to include in the request body]' \ + '--output[Write curl body to FILE instead of stdout]' +} + +__config() { + _arguments \ + '--async-timeout=[Timeout for async HTTP requests]' \ + '--trace=[Trace HTTP requests]:trace:(true false)' \ + '--color=[Enable or disable color]:color:(true false)' \ + '--locale=[Set default locale. If LOCALE is CLEAR, previous locale is deleted]' +} + +__oauth-token() { + # no arguments +} + +__add-plugin-repo() { + _arguments \ + '1:repo name:' \ + '2:url:' +} + +__remove-plugin-repo() { + _arguments \ + '1:repo name:__cf_repo_plugins' \ + '2:url:' +} + +__list-plugin-repos() { + # no arguments +} + +__repo-plugins() { + _arguments \ + '-r=[Repo Name]:repo name:__cf_repo_plugins' +} + +__plugins() { + _arguments \ + '-checksum[Compute and show the sha1 value of the plugin binary file]' +} + +__install-plugin() { + _arguments \ + '1:plugin URL or path:_files' \ + '-r=[repo name where the plugin binary is located]:repo name:__cf_repo_plugins' +} + +__uninstall-plugin() { + _arguments \ + '1:plugin name:__cf_plugins' +} + +__save-target() { + _arguments \ + '1:target-name:' \ + '-f[Force save even if current target is already saved under another name]' +} + +__set-target() { + _arguments \ + '1:target-name:__cf_targets' \ + '-f[Force target change even if current target is unsaved]' +} + +__delete-target() { + _arguments \ + '1:target-name:__cf_targets' +} + +# ------------------ +# ----- end Commands +# ------------------ + +# ------------------- +# ----- 1st Arguments +# ------------------- + +local -a _1st_arguments +_1st_arguments=( + "login":"Log user in" + "logout":"Log user out" + "passwd":"Change user password" + "target":"Set or view the targeted org or space" + "api":"Set or view target api url" + "auth":"Authenticate user non-interactively" + "apps":"List all apps in the target space" + "app":"Display health and status for app" + "push":"Push a new app or sync changes to an existing app" + "scale":"Change or view the instance count, disk space limit, and memory limit for an app" + "delete":"Delete an app" + "rename":"Rename an app" + "start":"Start an app" + "stop":"Stop an app" + "restart":"Restart an app" + "restage":"Restage an app" + "restart-app-instance":"Terminate the running application Instance at the given index and instantiate a new instance of the application with the same index" + "events":"Show recent app events" + "files":"Print out a list of files in a directory or the contents of a specific file" + "logs":"Tail or show recent logs for an app" + "env":"Show all env variables for an app" + "set-env":"Set an env variable for an app" + "unset-env":"Remove an env variable" + "stacks":"List all stacks" + "stack":"Show information for a stack" + "copy-source":"Make a copy of app source code from one application to another. Unless overridden, the copy-source command will restart the application" + "create-app-manifest":"Create an app manifest for an app that has been pushed successfully" + "marketplace":"List available offerings in the marketplace" + "services":"List all service instances in the target space" + "service":"Show service instance info" + "create-service":"Create a service instance" + "update-service":"Update a service instance" + "delete-service":"Delete a service instance" + "rename-service":"Rename a service instance" + "create-service-key":"Create key for a service instance" + "service-keys":"List keys for a service instance" + "service-key":"Show service key info" + "delete-service-key":"Delete a service key" + "bind-service":"Bind a service instance to an app" + "unbind-service":"Unbind a service instance from an app" + "create-user-provided-service":"Make a user-provided service instance available to cf apps" + "update-user-provided-service":"Update user-provided service instance name value pairs" + "orgs":"List all orgs" + "org":"Show org info" + "create-org":"Create an org" + "delete-org":"Delete an org" + "rename-org":"Rename an org" + "spaces":"List all spaces in an org" + "space":"Show space info" + "create-space":"Create a space" + "delete-space":"Delete a space" + "rename-space":"Rename a space" + "domains":"List domains in the target org" + "create-domain":"Create a domain in an org for later use" + "delete-domain":"Delete a domain" + "create-shared-domain":"Create a domain that can be used by all orgs (admin-only)" + "delete-shared-domain":"Delete a shared domain" + "routes":"List all routes in the current space or the current organization" + "create-route":"Create a url route in a space for later use" + "check-route":"Perform a simple check to determine whether a route currently exists or not" + "map-route":"Add a url route to an app" + "unmap-route":"Remove a url route from an app" + "delete-route":"Delete a route" + "delete-orphaned-routes":"Delete all orphaned routes (e.g.: those that are not mapped to an app)" + "buildpacks":"List all buildpacks" + "create-buildpack":"Create a buildpack" + "update-buildpack":"Update a buildpack" + "rename-buildpack":"Rename a buildpack" + "delete-buildpack":"Delete a buildpack" + "running-environment-variable-group":"Retrieve the contents of the running environment variable group" + "staging-environment-variable-group":"Retrieve the contents of the staging environment variable group" + "set-staging-environment-variable-group":"Pass parameters as JSON to create a staging environment variable group" + "set-running-environment-variable-group":"Pass parameters as JSON to create a running environment variable group" + "feature-flags":"Retrieve list of feature flags with status of each flag-able feature" + "feature-flag":"Retrieve an individual feature flag with status" + "enable-feature-flag":"Enable the use of a feature so that users have access to and can use the feature" + "disable-feature-flag":"Disable the use of a feature so that users have access to and can use the feature" + "curl":"Executes a raw request, content-type set to application/json by default" + "config":"write default values to the config" + "oauth-token":"Retrieve and display the OAuth token for the current session" + "add-plugin-repo":"Add a new plugin repository" + "remove-plugin-repo":"Remove a plugin repository" + "list-plugin-repos":"list all the added plugin repository" + "repo-plugins":"List all available plugins in all added repositories" + "plugins":"list all available plugin commands" + "install-plugin":"Install the plugin defined in command argument" + "uninstall-plugin":"Uninstall the plugin defined in command argument" + "targets":"List all saved targets (requires cf-targets plugin)" + "save-target":"Save the current target under a given name (requires cf-targets plugin)" + "set-target":"Restore a previously saved target (requires cf-targets plugin)" + "delete-target":"Delete a saved target (requires cf-targets plugin)" +) + +# ----------------------- +# ----- end 1st Arguments +# ----------------------- + +# ---------- +# ----- Main +# ---------- + +_arguments '*:: :->command' + +if (( CURRENT == 1 )); then + _describe -t commands "cf command" _1st_arguments + return +fi + +local -a _command_args +case "$words[1]" in + login) + __login ;; + logout) + __logout ;; + passwd) + __passwd ;; + target) + __target ;; + api) + __api ;; + auth) + __auth ;; + apps) + __apps ;; + app) + __app ;; + push) + __push ;; + scale) + __scale ;; + delete) + __delete ;; + rename) + __rename ;; + start) + __start ;; + stop) + __stop ;; + restart) + __restart ;; + restage) + __restage ;; + restart-app-instance) + __restart-app-instance ;; + events) + __events ;; + files) + __files ;; + logs) + __logs ;; + env) + __env ;; + set-env) + __set-env ;; + unset-env) + __unset-env ;; + stacks) + __stacks ;; + stack) + __stack ;; + copy-source) + __copy-source ;; + create-app-manifest) + __create-app-manifest ;; + marketplace) + __marketplace ;; + services) + __services ;; + service) + __service ;; + create-service) + __create-service ;; + update-service) + __update-service ;; + rename-service) + __rename-service ;; + delete-service) + __delete-service ;; + create-service-key) + __create-service-key ;; + service-keys) + __service-keys ;; + service-key) + __service-key ;; + delete-service-key) + __delete-service-key ;; + bind-service) + __bind-service ;; + unbind-service) + __unbind-service ;; + create-user-provided-service) + __create-user-provided-service ;; + update-user-provided-service) + __update-user-provided-service ;; + orgs) + __orgs ;; + org) + __org ;; + create-org) + __create-org ;; + delete-org) + __delete-org ;; + spaces) + __spaces ;; + space) + __space ;; + create-space) + __create-space ;; + delete-space) + __delete-space ;; + domains) + __domains ;; + create-domain) + __create-domain ;; + delete-domain) + __delete-domain ;; + create-shared-domain) + __create-shared-domain ;; + delete-shared-domain) + __delete-shared-domain ;; + routes) + __routes ;; + create-route) + __create-route ;; + check-route) + __check-route ;; + map-route) + __map-route ;; + unmap-route) + __unmap-route ;; + delete-route) + __delete-route ;; + delete-orphaned-routes) + __delete-orphaned-routes ;; + buildpacks) + __buildpacks ;; + create-buildpack) + __create-buildpack ;; + update-buildpack) + __update-buildpack ;; + rename-buildpack) + __rename-buildpack ;; + delete-buildpack) + __delete-buildpack ;; + running-environment-variable-group) + __running-environment-variable-group ;; + staging-environment-variable-group) + __staging-environment-variable-group ;; + set-staging-environment-variable-group) + __set-staging-environment-variable-group ;; + set-running-environment-variable-group) + __set-running-environment-variable-group ;; + feature-flags) + __feature-flags ;; + feature-flag) + __feature-flag ;; + enable-feature-flag) + __enable-feature-flag ;; + disable-feature-flag) + __disable-feature-flag ;; + curl) + __curl ;; + config) + __config ;; + oauth-token) + __oauth-token ;; + add-plugin-repo) + __add-plugin-repo ;; + remove-plugin-repo) + __remove-plugin-repo ;; + list-plugin-repos) + __list-plugin-repos ;; + repo-plugins) + __repo-plugins ;; + plugins) + __plugins ;; + install-plugin) + __install-plugin ;; + uninstall-plugin) + __uninstall-plugin ;; + save-target) + __save-target ;; + set-target) + __set-target ;; + delete-target) + __delete-target ;; +esac diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_chatblade b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_chatblade new file mode 100644 index 00000000..62d12e6c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_chatblade @@ -0,0 +1,63 @@ +#compdef chatblade +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for chatblade (https://github.com/npiv/chatblade) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Johannes Bittner (https://github.com/johannes87) +# +# ------------------------------------------------------------------------------ + +_chatblade() { + local -a args + local context state state_descr line + typeset -A opt_args + + args+=( + '(- *)'{-h,--help}'[show this help message and exit]' + '--openai-api-key[the OpenAI API key can also be set as env variable OPENAI_API_KEY]:key' + '--temperature[temperature (openai setting)]:temperature' + '(-c --chat-gpt)'{-c,--chat-gpt}'[chat GPT model 3.5/4 shorthand or full qualified model name, can also be set via env variable OPENAI_API_MODEL]:chat GPT model:(3.5 4)' + '(-i --interactive)'{-i,--interactive}'[start an interactive chat session. This will implicitly continue the conversation]' + '(-s --stream)'{-s,--stream}'[Stream the incoming text to the terminal]' + '(-t --tokens)'{-t,--tokens}'[display what *would* be sent, how many tokens, and estimated costs]' + '(-p --prompt-file)'{-p,--prompt-file}'[prompt name - will load the prompt with that name at ~/.config/chatblade/name or a path to a file]:prompt file:_files' + '(-e --extract)'{-e,--extract}'[extract content from response if possible (either json or code block)]' + '(-r --raw)'{-r,--raw}'[print session as pure text, dont pretty print or format]' + '(-n --no-format)'{-n,--no-format}'[do not add pretty print formatting to output]' + '(-o --only)'{-o,--only}'[Only display the response, omit query]' + '--theme[Set the theme for syntax highlighting see https://pygments.org/styles/, can also be set with CHATBLADE_THEME]:theme:_values "theme" default emacs friendly manni monokai' + '(-l --last)'{-l,--last}'[alias for -S last, the default session if none is specified]' + '(-S --session)'{-S,--session}'[initiate or continue named session]:session:->sessions' + '--session-list[list sessions]' + '--session-path[show path to session file]' + '--session-dump[dump session to stdout]' + '--session-delete[delete session]' + '--session-rename[rename session]:new session:->sessions' + ) + + _arguments -s $args + + case $state in + (sessions) + local -a sessions + sessions=("${(@f)$(chatblade --session-list)}") + _describe 'session' sessions + ;; + esac +} + +_chatblade + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_choc b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_choc new file mode 100644 index 00000000..8d79af32 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_choc @@ -0,0 +1,60 @@ +#compdef choc +# ------------------------------------------------------------------------------ +# Copyright (c) 2012 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for choc (https://chocolatapp.com/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Nicholas Penree (https://github.com/drudge) +# +# ------------------------------------------------------------------------------ + +local curcontext="$curcontext" state line ret=1 +typeset -A opt_args + +_arguments -C \ + '(-a --async)'{-a,--async}'[do not wait for the user to close the file in Chocolat]' \ + '(-w --wait)'{-w,--wait}'[wait for file to be closed by Chocolat]' \ + '(-n --no-reactivation)'{-n,--no-reactivation}'[after editing with -w, do not reactivate the calling app]' \ + '(-h --help)'{-h,--help}'[show help information]' \ + '(-v --version)'{-v,--version}'[print version information]' \ + '*:script or directory:_files' && ret=0 + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_chromium b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_chromium new file mode 100644 index 00000000..917739b5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_chromium @@ -0,0 +1,211 @@ +#compdef chromium + +# Copyright 2018 CERN for the benefit of the LHCb Collaboration + +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are +# met: +# +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above +# copyright notice, this list of conditions and the following disclaimer +# in the documentation and/or other materials provided with the +# distribution. +# * Neither the name of CERN nor the names of its +# contributors may be used to endorse or promote products derived from +# this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS +# "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT +# LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR +# A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT +# OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, +# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT +# LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY +# THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# In applying this licence, CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization +# or submit itself to any jurisdiction. + +_arguments \ + "--user-data-dir=[Specify the directory that user data is kept in]:directory:_path_files -/" \ + "--app=[Runs URL in app mode]:url:_urls" \ + "--incognito[Open in incognito mode]" \ + "--new-window[open in new window]" \ + "(--no-proxy-server --proxy-auto-detect --proxy-pac-url --password-store)--proxy-server=[specify proxy server]:[\://][\:]:_chromium_proxyurls" \ + "--no-proxy-server[Disables the proxy server]" \ + "--proxy-auto-detect[Autodetect proxy configuration]" \ + "--proxy-pac-url=[Specify proxy autoconfiguration URL]:proxy autoconfiguration url:_urls" \ + "--password-store=[Set the password store to use]:password store: _wanted arguments expl 'wallet store' compadd -- basic gnome kwallet" \ + "--version[print version]" \ + "*:: :{ _alternative _urls _files }" + +# excerpt from the chromium help message: +# +# Specify the HTTP/SOCKS4/SOCKS5 proxy server to use for requests. This overrides any environment variables or settings picked via the options dialog. An individual proxy server is specified +# using the format: +# +# +# +# Where is the protocol of the proxy server, and is one of: +# +# "http", "socks", "socks4", "socks5". +# +# If the is omitted, it defaults to "http". Also note that "socks" is equivalent to "socks5". +# +# Examples: +# +# --proxy-server="foopy:99" +# Use the HTTP proxy "foopy:99" to load all URLs. +# +# --proxy-server="socks://foobar:1080" +# Use the SOCKS v5 proxy "foobar:1080" to load all URLs. +# +# --proxy-server="socks4://foobar:1080" +# Use the SOCKS v4 proxy "foobar:1080" to load all URLs. +# +# --proxy-server="socks5://foobar:66" +# Use the SOCKS v5 proxy "foobar:66" to load all URLs. +# +# It is also possible to specify a separate proxy server for different URL types, by prefixing the proxy server specifier with a URL specifier: +# +# Example: +# +# --proxy-server="https=proxy1:80;http=socks4://baz:1080" +# Load https://* URLs using the HTTP proxy "proxy1:80". And load http://* +# URLs using the SOCKS v4 proxy "baz:1080". +# + +_chromium_proxyurls () { + #TODO: semicolon separated urls not yet implemented + # mostly copied from _urls + local ipre scheme host user uhosts ret=1 expl match glob suf + local localhttp + zstyle -a ":completion:${curcontext}:urls" local localhttp + local localhttp_servername="$localhttp[1]" + local localhttp_documentroot="$localhttp[2]" + local localhttp_userdir="$localhttp[3]" + zstyle -a ":completion:${curcontext}:urls" urls urls + if [[ $#urls -gt 1 || ( $#urls -eq 1 && ! -d $urls[1] ) ]] + then + [[ $#urls -eq 1 && -f $urls[1] ]] && urls=($(< $urls[1])) + _wanted urls expl 'URL' compadd "$@" -a urls && return 0 + urls=() + fi + urls="$urls[1]" + glob=(-g '*(^/)') + zparseopts -D -K -E 'g:=glob' + ipre="$IPREFIX" + if ! compset -P '(#b)([-+.a-z0-9]#):' + then + _tags -C argument prefixes + while _tags + do + while _next_label prefixes expl 'URL prefix' -S '' "$@" + do + compset -S '[^:/]*' && compstate[to_end]='' + compadd "$expl[@]" http:// socks:// socks4:// socks5:// && ret=0 + done + (( ret )) || return 0 + done + return 1 + fi + scheme="$match[1]" + case "$scheme" in + (http(|s)|socks(|4|5)) if ! compset -P // + then + _wanted -C "$scheme" prefixes expl 'end of prefix' compadd -S '' "$@" // + return + fi ;; + (file) [[ -prefix //(127.0.0.1|localhost)/ ]] && compset -P '//(127.0.0.1|localhost)' + [[ -prefix /// ]] && compset -P // + if ! compset -P // + then + _tags -C file files + while _tags + do + while _next_label files expl 'local file' + do + if [[ -prefix / ]] + then + _path_files "$expl[@]" -S '' "${glob[@]}" && ret=0 + _path_files "$expl[@]" -S/ -r '/' -/ && ret=0 + elif [[ -z "$PREFIX" ]] + then + compadd -S '/' -r '/' "$expl[@]" "$@" - "${PWD%/}" && ret=0 + fi + done + (( ret )) || return 0 + done + return 1 + fi ;; + esac + if ! compset -P '(#b)([^:/]#)([:/])' + then + uhosts=($urls/$scheme/$PREFIX*$SUFFIX(/:t)) + _tags hosts + while _tags + do + while _next_label hosts expl host + do + compset -S '[:/]*' || suf="/" + (( $#uhosts )) || _hosts -S "$suf" -r '/:' "$expl[@]" && ret=0 + [[ "$scheme" = http ]] && uhosts=($uhosts $localhttp_servername) + compadd -S "$suf" -r '/:' "$expl[@]" -a uhosts && ret=0 + done + (( ret )) || return 0 + done + return 1 + fi + host="$match[1]" + [[ $match[2] = ':' ]] && ! compset -P '<->/' && _message -e ports 'port number' && return 0 + _tags remote-files files || return 1 + if [[ "$localhttp_servername" = "$host" ]] + then + if compset -P \~ + then + if ! compset -P '(#b)([^/]#)/' + then + _users -S/ "$@" + return + fi + user="$match[1]" + while _tags + do + while _next_label files expl 'local file' + do + _path_files "$expl[@]" "$@" -W ~$user/$localhttp_userdir "${glob[@]}" && ret=0 + _path_files -S/ -r '/' "$expl[@]" -W ~$user/$localhttp_userdir-/ && ret=0 + done + (( ret )) || return 0 + done + else + while _tags + do + while _next_label files expl 'local file' + do + _path_files "$expl[@]" "$@" -W $localhttp_documentroot "${glob[@]}" && ret=0 + _path_files -S/ -r '/' "$expl[@]" -W $localhttp_documentroot -/ && ret=0 + done + (( ret )) || return 0 + done + fi + else + while _tags + do + (( $#urls )) && while _next_label files expl 'local file' + do + _path_files "$expl[@]" "$@" -W $urls/$scheme/$host "${glob[@]}" && ret=0 + _path_files -S/ -r '/' "$expl[@]" -W $urls/$scheme/$host -/ && ret=0 + done + [[ $scheme = (scp|sftp) ]] && _requested remote-files && _remote_files -h $host -- ssh && ret=0 + (( ret )) || return 0 + done + fi + return $ret +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_clang-check b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_clang-check new file mode 100644 index 00000000..f2f96179 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_clang-check @@ -0,0 +1,62 @@ +#compdef clang-check +# ------------------------------------------------------------------------------ +# Copyright (c) 2022 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for clang-check v15.0.2 (https://clang.llvm.org/docs/ClangCheck.html) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_arguments \ + '(- *)--help[Display available options]' \ + '(- *)--help-hidden[Display available more options]' \ + '(- *)--version[Display the version of this program]' \ + '--analyze[Run static analysis engine]' \ + '--analyzer-output-path=[Write output to file]: :_files' \ + '--ast-dump[Build ASTs and then debug dump them]' \ + '--ast-dump-filter=[Use with -ast-dump or -ast-print to dump/print only AST declaration nodes having a certain substring]:string' \ + '--ast-list[Build ASTs and print the list of declaration node qualified names]' \ + '--ast-print[Build ASTs and then pretty-print them]' \ + '*--extra-arg=[Additional argument to append to the compiler command line]:arg' \ + '*--extra-arg-before=[Additional argument to prepend to the compiler command line]:arg' \ + '--fix-what-you-can[Apply fix-it advice even in the presence of unfixable errors]' \ + '--fixit[Apply fix-it advice to the input source]' \ + '-p[Build directory where compile_commands.json is]: :_files -/' \ + '--syntax-tree-dump[dump the syntax tree]' \ + '--tokens-dump[dump the preprocessed tokens]' \ + '*: :_files' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_clang-format b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_clang-format new file mode 100644 index 00000000..18b613f1 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_clang-format @@ -0,0 +1,70 @@ +#compdef clang-format +# ------------------------------------------------------------------------------ +# Copyright (c) 2022 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for clang-format v15.0.2 (https://clang.llvm.org/docs/ClangFormat.html) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +local -a styles=(LLVM GNU Google Chromium Microsoft) + +_arguments \ + '(- *)--help[Display available options]' \ + '(- *)--help-hidden[Display available more options]' \ + '(- *)--help-list[Display list of available options]' \ + '(- *)--help-list-hidden[Display list of more available options]' \ + '--Werror=[If set, changes formatting warnings to errors]' \ + '*--Wno-error=[If set, do not error out on the specified warning type]:warn' \ + '--assume-filename=[Set filename used to determine the language and to find .clang-format file]: :_files' \ + '--cursor=[The position of the cursor when invoking clang-format from an editor integration]:pos' \ + '(-n --dry-run)'{-n,--dry-run}'[If set, do not actually make the formatting changes]' \ + '--dump-config[Dump configuration options to stdout and exit]' \ + '--fallback-style=[The name of the predefined style used as a fallback]: :'"($styles)" \ + '--ferror-limit=[Set the maximum number of clang-format errors to emit before stopping]:limit' \ + '*--files=[Provide a list of files to run clang-format]: :_files' \ + '-i[Inplace edit files, if specified]' \ + '--length=[Format a range of this length(in bytes)]:bytes' \ + '--lines=[format a range of lines]:format' \ + '--offset=[Format a range starting at this byte offset]' \ + '--output-replacements-xml[Output replacements as XML]' \ + '--qualifier-alignment=[If set, overrides the qualifier alignment style determined by the QualifierAlignment style flag]' \ + '--sort-includes[If set, overrides the include sorting behavior determined by the SortIncludes style flag]' \ + '--style=[Set coding style]: :'"($styles)" \ + '--verbose[If set, show the list of processed files]' \ + '*: :_files' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_clang-tidy b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_clang-tidy new file mode 100644 index 00000000..eead4be7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_clang-tidy @@ -0,0 +1,76 @@ +#compdef clang-tidy +# ------------------------------------------------------------------------------ +# Copyright (c) 2022 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for clang-tidy v15.0.2 (https://clang.llvm.org/extra/clang-tidy/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +local -a styles=(LLVM GNU Google Chromium Microsoft) + +_arguments \ + '(- *)--help[Display available options]' \ + '(- *)--help-hidden[Display available more options]' \ + '(- *)--help-list[Display list of available options]' \ + '(- *)--help-list-hidden[Display list of more available options]' \ + '--checks=[Comma-separated list of globs with optional "-" prefix]:checks' \ + '--config=[Specifies a configuration in YAML/JSON format]:conf' \ + '--config-file=[Specify the path of .clang-tidy or custom config-file]: :_files' \ + '--dump-config[Dumps configuration in the YAML format to stdout]' \ + '--enable-check-profile[Enable per-check timing profiles, and print a report to stderr]' \ + '--explain-config[For each enabled check explains, where it is enabled]' \ + '--export-fixes=[YAML file to store suggested fixes in]: :_files' \ + '*--extra-arg[Additional argument to append to the compiler command line]:arg' \ + '*--extra-arg-before[Additional argument to prepend to the compiler command line]:arg' \ + '--fix[Apply suggested fixes]' \ + '--fix-errors[Apply suggested fixes even if compilation errors were found]' \ + '--fix-notes[If a warning has no fix, but a single fix can be found through an associated diagnostic node, apply the fix]' \ + '--format-style=[Style for formatting code around applied fixes]: :(llvm google webkit mozilla)' \ + '--header-filter=[Regular expression matching the names of the headers to output diagnostics from]:regexp' \ + '(- *)--list-checks[List all enabled checks and exit]' \ + '--load=[Load the specified plugin]: :_files' \ + '-p[Build directory where compile_commands.json is]: :_files -/' \ + '--quiet[Run clang-tidy in quiet mode]' \ + '--store-check-profile=[These per-TU profiles are instead stored as JSON]:prefix' \ + '--system-headers[Display the errors from system headers]' \ + '--use-color[Use colors in diagnostics]' \ + '--verify-config[Check the config files to ensure each check and option is recognized]' \ + '--vfsoverlay=[Overlay the virtual filesystem described by file over the real file system]: :_files' \ + '--warnings-as-errors=[Upgrades warning to errors]:check' \ + '*: :_files' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cmake b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cmake new file mode 100644 index 00000000..afb17395 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cmake @@ -0,0 +1,595 @@ +#compdef cmake -value-,CMAKE_GENERATOR,-default- +# ------------------------------------------------------------------------------ +# Copyright (c) 2017 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------- +# Description +# ----------- +# +# Completion script for CMake 3.25.0 (https://cmake.org). +# +# ------------------------------------------------------------------------- +# Authors +# ------- +# +# * Scott M. Kroll (initial version) +# * Paul Seyfert (handling of --build and updates) +# * Norbert Lange (presets, command mode, updates) +# +# ------------------------------------------------------------------------- +# Notes +# ----- +# +# * By default only C and C++ languages are supported for compiler flag +# variables. To define your own list of languages: +# +# cmake_langs=('C' 'C' +# 'CXX' 'C++') +# zstyle ':completion:*:cmake:*' languages $cmake_langs +# +# ------------------------------------------------------------------------- + +local context state line curcontext="$curcontext" cmake_args + +local -a cmake_build_options=( + '-S[Explicitly specify a source directory]:source directory:_path_files -/' + '-B[Explicitly specify a build directory]:build directory:_path_files -/' + '-C[Pre-load a script to populate the cache]:initial cache:_files' + '*-D-[Create a cmake cache entry]:property:_cmake_define_property' + '*-U[Remove matching entries from CMake cache]:globbing expression' + '-G[Specify a makefile generator]:generator:_cmake_generators' + '-T[Specify toolset name if supported by generator]:toolset name' + '-A[Specify platform name if supported by generator]:platform name' + '--toolchain[Specify toolchain file]: :_files' + '--install-prefix[Specify install directory]: :_path_files -/' + + # Warnings + '(-Wdev)-Wno-dev[Suppress/Enable developer warnings]' + '(-Wno-dev)-Wdev[Suppress/Enable developer warnings]' + '(-Wdeprecated)-Wno-deprecated[Suppress/Enable deprecation warnings]' + '(-Wno-deprecated)-Wdeprecated[Suppress/Enable deprecation warnings]' + '(-Werror=dev)-Wno-error=dev[Make developer warnings (not) errors]' + '(-Wno-error=dev)-Werror=dev[Make developer warnings (not) errors]' + '(-Wno-error=deprecated)-Werror=deprecated[Make deprecated macro and function warnings (not) errors]' + '(-Werror=deprecated)-Wno-error=deprecated[Make deprecated macro and function warnings (not) errors]' + + '--preset=[Specify a configure preset]:preset:_cmake_presets' + '--list-presets[List available presets]' + + '-E[CMake command mode]:command:_cmake_command_help' + + '-L-[List cache variables]::_values "options" "[non-advanced cache variables]" "A[advanced cache variables]" "H[non-advanced cached variables with help]" "AH[advanced cache variables with help]"' + '--fresh[Configure a fresh build tree, removing any existing cache file]' + + '--build[Build a CMake-generated project binary tree]:project directory:_path_files -/' + '--install[Install a CMake-generated project binary tree]:project directory:_path_files -/' + '--open[Open generated project in the associated application]:project directory:_path_files -/' + + '-N[View mode only]' + '-P[Process script mode]:script:_files' + + '--find-package[Legacy pkg-config like mode. Do not use]' + + '--graphviz=[Generate graphviz of dependencies, see CMakeGraphVizOptions.cmake for more]:graphviz output:_files' + '--system-information[Dump information about this system]::system information output:_files' + + '--log-level=[Set the verbosity of messages from CMake files]:log level:(ERROR WARNING NOTICE STATUS VERBOSE DEBUG TRACE)' + '--log-context[Prepend log messages with context, if given]' + + '--debug-trycompile[Do not delete the try_compile build tree. Only useful on one try_compile at a time]' + '--debug-output[Put cmake in a debug mode]' + '--debug-find[Put cmake find in a debug mode]' + + '(--trace-expand)--trace[Put cmake in trace mode]' + '(--trace)--trace-expand[Put cmake in trace mode with variable expansion]' + '--trace-format=[Set the output format of the trace]:trace format:(human json-v1)' + '*--trace-source[Trace only this CMake file/module. Multiple options allowed]:filename:_files' + '--trace-redirect[Redirect trace output to a file instead of stderr]:trace output:_files' + + '--warn-uninitialized[Warn about uninitialized values]' + '--no-warn-unused-cli[Do not warn about command line options]' + '--warn-unused-vars[Warn about unused variables]' + '--check-system-vars[Find problems with variable usage in system files]' + '--compile-no-warning-as-error[Ignore COMPILE_WARNING_AS_ERROR property and CMAKE_COMPILE_WARNING_AS_ERROR variable]' + + '--profiling-format[Output data for profiling CMake scripts]:profiling format:(google-trace)' + '--profiling-output[Select an output path for the profiling data]:filename:_files' + + ':cmake project:_path_files -/' +) + +# ------------------------ +# _cmake_generator_options +# +# arguments are $1: build working directory (top level Makefile or build.ninja file) +# $2: position of "--" in the command line +# ------------------------ +(( $+functions[_cmake_generator_options] )) || +_cmake_generator_options() { + # pass only the part of the command line starting at "--" to the completion + shift (( $2 - 1 )) words + (( CURRENT = $CURRENT + 1 - $2 )) + if [ -f $1/Makefile ] + then + $_comps[make] + elif [ -f $1/build.ninja ] + then + $_comps[ninja] + fi +} + +# -------------- +# _cmake_presets +# -------------- +(( $+functions[_cmake_presets] )) || +_cmake_presets() { + local invoke; invoke=(${(Q)words}) + invoke[$CURRENT]=() + # TODO: remove all arguments -* except -S + + local list_presets; list_presets=(${(f)"$(${invoke} --list-presets 2>/dev/null | + sed -n -e 's,^[[:space:]]*"\([^"]*\)"[[:space:]]*-[[:space:]]*\(.*\),\1:\2,p' \ + -e 's,^[[:space:]]*"\([^"]*\)"[[:space:]]*$,\1,p')"}) + + _describe 'presets' list_presets +} + +# -------------- +# _cmake_targets +# -------------- +(( $+functions[_cmake_targets] )) || +_cmake_targets() { + local -a targets + if [ -f $1/Makefile ] + then + # `make help` doesn't work for Makefiles in general, but for CMake generated Makefiles it does. + i=1 + for target in $(make -f $1/Makefile help | \grep -e "\.\.\." | sed "s/\.\.\. //" | sed "s/ (the default.*//") ; do + targets[$i]=$target + (( i = $i + 1 )) + done + elif [ -f $1/build.ninja ] + then + # `ninja help` doesn't seem to be the list of targets we're interested in + i=1 + for target in $(ninja -C $1 -t targets all 2&>/dev/null | awk -F: '{print $1}') ; do + targets[$i]="$target" + (( i++ )) + done + fi + _describe 'build targets' targets +} + +_cmake_suggest_builddirs() { + _alternative ':current directory:(.)' 'directory::_directories' && return 0 +} + +_cmake_suggest_installdirs() { + _alternative ':current directory:(.)' 'directory::_directories' && return 0 +} + +_cmake_on_build() { + local build_extras;build_extras=( + '--[Native build tool options]' + '--target[specify build target]' + '--clean-first[build target clean first]' + '--config[For multi-configuration tools]' + '--parallel[maximum number of build processes]' + '--use-stderr') + local -a undescribed_build_extras + i=1 + for be in $build_extras ; do + undescribed_build_extras[$i]=$(echo $be | sed "s/\[.*//") + (( i++ )) + done + inbuild=false + dashdashposition=-1 + for ((i = (($CURRENT - 1)); i > 1 ; i--)); do + if [[ $words[$i] == --build ]] ; then + inbuild=true + buildat=$i + (( difference = $CURRENT - $i )) + elif [[ $words[$i] == -- ]] ; then + dashdashposition=$i + fi + done + # check if build mode has been left + outofbuild=false + for ((i = (($CURRENT - 1)); i > (($buildat + 1)); i--)); do + # don't check the word after --build (should be a directory) + if [[ ${undescribed_build_extras[(r)$words[$i]]} == $words[$i] ]] ; then continue ; fi + if [[ $words[(($i - 1))] == --target ]] ; then continue ; fi + if [[ $words[(($i - 1))] == --config ]] ; then continue ; fi + if [[ $words[(($i - 1))] == --parallel ]] ; then continue ; fi + outofbuild=true + done + if (( $dashdashposition > 0 )) ; then + _cmake_generator_options $words[(($buildat + 1))] $dashdashposition && return 0 + fi + if [[ "$inbuild" == false || "$difference" -eq 1 ]] ; then + # either there is no --build or completing the directory after --build + _arguments -C -s \ + - build_opts \ + "$cmake_build_options[@]" \ + - build_cmds \ + "$cmake_suggest_build[@]" && return 0 + elif [[ $words[(($CURRENT - 1))] == --target ]] ; then + # after --build --target, suggest targets + _cmake_targets $words[(($buildat + 1))] && return 0 + elif [[ $words[(($CURRENT - 1))] == --config ]] ; then + # after --build --config, no idea + return 0 + elif [[ $words[(($CURRENT - 1))] == --parallel ]] ; then + # after --build --parallel + return 0 + elif [ "$outofbuild" = true ] ; then + # after --build --, suggest other cmake_build_options (like -Wno-dev) + _arguments "$cmake_build_options[@]" && return 0 + else + # after --build , suggest other cmake_build_options (like -Wno-dev) or --build options (like --clean-first) + _arguments "$build_extras[@]" "$cmake_build_options[@]" && return 0 + fi +} + +_cmake_on_install() { + local build_extras;build_extras=( + '--[Native build tool options]' + '--prefix[Override the installation prefix, CMAKE_INSTALL_PREFIX]' + '--config[For multi-configuration generators(e.g. Visual Studio)]' + '--component[Component-based install]' + '--strip[Strip before installing.]' + ) + local -a undescribed_build_extras + i=1 + for be in $build_extras ; do + undescribed_build_extras[$i]=$(echo $be | sed "s/\[.*//") + (( i++ )) + done + inbuild=false + dashdashposition=-1 + for ((i = (($CURRENT - 1)); i > 1 ; i--)); do + if [[ $words[$i] == --install ]] ; then + inbuild=true + buildat=$i + (( difference = $CURRENT - $i )) + elif [[ $words[$i] == -- ]] ; then + dashdashposition=$i + fi + done + outofbuild=false + for ((i = (($CURRENT - 1)); i > (($buildat + 1)); i--)); do + # don't check the word after --install (should be a directory) + if [[ ${undescribed_build_extras[(r)$words[$i]]} == $words[$i] ]] ; then continue ; fi + if [[ $words[(($i - 1))] == --prefix ]] ; then continue ; fi + if [[ $words[(($i - 1))] == --config ]] ; then continue ; fi + if [[ $words[(($i - 1))] == --component ]] ; then continue ; fi + outofbuild=true + done + if (( $dashdashposition > 0 )) ; then + _cmake_generator_options $words[(($buildat + 1))] $dashdashposition && return 0 + fi + if [[ "$inbuild" == false || "$difference" -eq 1 ]] ; then + # either there is no --install or completing the directory after --install + _arguments -C -s \ + - build_opts \ + "$cmake_build_options[@]" \ + - build_cmds \ + "$cmake_suggest_install[@]" && return 0 + elif [[ $words[(($CURRENT - 1))] == --prefix ]] ; then + # after --install --prefix, no idea + return 0 + elif [[ $words[(($CURRENT - 1))] == --config ]] ; then + # after --install --config, no idea + return 0 + elif [[ $words[(($CURRENT - 1))] == --component ]] ; then + # after --build --component, no idea + return 0 + elif [ "$outofbuild" = true ] ; then + # after --build --, suggest other cmake_build_options (like -Wno-dev) + _arguments "$cmake_build_options[@]" && return 0 + else + # after --build , suggest other cmake_build_options (like -Wno-dev) or --build options (like --clean-first) + _arguments "$build_extras[@]" "$cmake_build_options[@]" && return 0 + fi +} + +local -a cmake_help_actions=( + '(- 1)'{--help,-help,-usage,-h,-H}'[Print usage information and exit]' + '(- 1)'{--version,-version}'[Print version number and exit]' + '(- 1)--help-full[Print all help manuals and exit]' + '(- 1)--help-manual[Print one help manual and exit]:module-name: _cmake_list_names --help-manual-list "manual name"' + '(- 1)--help-manual-list[List help manuals available and exit]' + '(- 1)--help-command[Print help for one command and exit]:command-name: _cmake_list_names --help-command-list "command name"' + '(- 1)--help-command-list[List commands with help available and exit]' + '(- 1)--help-commands[Print cmake-commands manual and exit]' + '(- 1)--help-module[Print help for one module and exit]:module-name: _cmake_list_names --help-module-list "module name"' + '(- 1)--help-module-list[List modules with help available and exit]' + '(- 1)--help-modules[Print cmake-modules manual and exit]' + '(- 1)--help-policy[Print help for one policy and exit]:policy-name: _cmake_list_names --help-policy-list "policy name"' + '(- 1)--help-policy-list[List policies with help available and exit]' + '(- 1)--help-policies[Print cmake-policies manual and exit]' + '(- 1)--help-property[Print help for one property and exit]:property-name: _cmake_list_names --help-property-list "property name" brakremove' + '(- 1)--help-property-list[List properties with help available and exit]' + '(- 1)--help-properties[Print cmake-properties manual and exit]' + '(- 1)--help-variable[Print help for one variable and exit]:variable-name: _cmake_list_names --help-variable-list "variable name" brakremove' + '(- 1)--help-variable-list[List variables with help available and exit]' + '(- 1)--help-variables[Print cmake-variables manual and exit]' +) +_cmake_help() { + _arguments -C -s - help "$cmake_help_actions[@]" +} + +# ----------------- +# _cmake_list_names +# ----------------- +(( $+functions[_cmake_list_names] )) || +_cmake_list_names() { + local command; command="$@[1]" + local desc; desc="$@[2]" + local opts; opts=($@[3]) + local list_names; list_names=(${(f)"$($service $command 2> /dev/null)"}) + # Older CMake (< 3.0) writes out the version + list_names=(${^list_names##cmake version*}) + + if [[ ${opts[(i)brakremove]} -le ${#opts} ]]; then + list_names=(${^list_names//\[/\\\[}) + list_names=(${^list_names//\]/\\\]}) + fi + + _values ${desc} ${list_names[@]:-1} && return 0 +} + +# ---------------------- +# _cmake_define_property +# ---------------------- +(( $+functions[_cmake_define_property] )) || +_cmake_define_property() { + if compset -P '*='; then + _wanted property-values expl 'property value' _cmake_define_property_values ${${IPREFIX%=}#-D} && return 0 + else + _wanted property-names expl 'property name' _cmake_define_property_names -qS= && return 0 + fi +} + +# ---------------------------- +# _cmake_define_property_names +# ---------------------------- +(( $+functions[_cmake_define_property_names] )) || +_cmake_define_property_names() { + local alternatives; alternatives=( + 'common-property-names:common property name:_cmake_define_common_property_names -qS=' + ) + local -A cmake_langs + zstyle -a ":completion:${curcontext}:" languages cmake_langs + [[ $#cmake_langs -eq 0 ]] && cmake_langs=('C' 'C' 'CXX' 'C++') + + for cmake_lang in ${(k)cmake_langs}; do + cmake_lang_desc="${cmake_langs[$cmake_lang]}" + alternatives+=("${cmake_lang//:/-}-property-names:${cmake_lang_desc} language property name:_cmake_define_lang_property_names -qS= ${cmake_lang} ${cmake_lang_desc}") + done + + _alternative "${alternatives[@]}" +} + +# --------------------------------- +# _cmake_define_lang_property_names +# --------------------------------- +(( $+functions[_cmake_define_lang_property_names] )) || +_cmake_define_lang_property_names() { + local cmake_lang="$@[-2]" cmake_lang_desc="$@[-1]" + local properties; properties=( + "CMAKE_${cmake_lang}_COMPILER:${cmake_lang_desc} compiler" + "CMAKE_${cmake_lang}_COMPILER_LAUNCHER:${cmake_lang_desc} compiler launcher (e.g. ccache)" + "CMAKE_${cmake_lang}_FLAGS:${cmake_lang_desc} compiler flags for all builds" + "CMAKE_${cmake_lang}_FLAGS_DEBUG:${cmake_lang_desc} compiler flags for all Debug build" + "CMAKE_${cmake_lang}_FLAGS_RELEASE:${cmake_lang_desc} compiler flags for all Release build" + "CMAKE_${cmake_lang}_FLAGS_MINSIZREL:${cmake_lang_desc} compiler flags for all MinSizRel build" + "CMAKE_${cmake_lang}_FLAGS_RELWITHDEBINFO:${cmake_lang_desc} compiler flags for all RelWithDebInfo build" + "CMAKE_${cmake_lang}_STANDARD:${cmake_lang_desc} language standard" + "CMAKE_${cmake_lang}_STANDARD_REQUIRED:${cmake_lang_desc} language standard is required" + "CMAKE_${cmake_lang}_EXTENSIONS:${cmake_lang_desc} enable compiler specific extensions" + ) + + _describe -t "${cmake_lang//:/-}-property-names" "${cmake_lang_desc} property name" properties $@[0,-3] && return 0 +} + +# ----------------------------------- +# _cmake_define_common_property_names +# ----------------------------------- +(( $+functions[_cmake_define_common_property_names] )) || +_cmake_define_common_property_names() { + local properties; properties=( + 'CMAKE_MODULE_PATH:Search path for CMake modules (FindPROJECT.cmake)' + 'CMAKE_PREFIX_PATH:Search path for installations (PROJECTConfig.cmake)' + 'CMAKE_BUILD_TYPE:Specifies the build type for make based generators' + 'CMAKE_TOOLCHAIN_FILE:Absolute or relative path to a CMake script which sets up toolchain related variables' + 'CMAKE_COLOR_MAKEFILE:Enables/disables color output when using the Makefile generator' + 'CMAKE_INSTALL_PREFIX:Install directory used by install' + 'CMAKE_EXPORT_COMPILE_COMMANDS:Enable/disable output of compilation database during generation' + 'CMAKE_RULE_MESSAGES:Specify whether to report a message for each make rule' + 'CMAKE_VERBOSE_MAKEFILE:Enable verbose output from Makefile builds' + 'CMAKE_UNITY_BUILD:Batch include source files' + ) + + _describe -t 'common-property-names' 'common property name' properties $@ +} + +local _cmake_build_types=('Debug' 'Release' 'RelWithDebInfo' 'MinSizeRel') +local _cmake_c_standards=(90 99 11) +local _cmake_cxx_standards=(98 11 14 17 20) + +# ---------------------------- +# _cmake_define_property_values +# ---------------------------- +(( $+functions[_cmake_define_property_values] )) || +_cmake_define_property_values() { + local ret=1 + setopt localoptions extendedglob + case $@[-1] in + (CMAKE_BUILD_TYPE) _wanted build-types expl 'build type' _values 'build type' ${_cmake_build_types[@]} && ret=0;; + (CMAKE_CXX_STANDARD) _wanted cxx-standards expl 'cxx standard' _values 'cxx standard' ${_cmake_cxx_standards[@]} && ret=0;; + (CMAKE_C_STANDARD) _wanted c-standards expl 'c standard' _values 'c standard' ${_cmake_c_standards[@]} && ret=0;; + (CMAKE_TOOLCHAIN_FILE) _wanted toolchain-files expl 'file' _cmake_toolchain_files && ret=0;; + (CMAKE_COLOR_MAKEFILE) _wanted booleans expl 'boolean' _cmake_booleans && ret=0;; + (CMAKE_RULE_MESSAGES) _wanted booleans expl 'boolean' _cmake_booleans && ret=0;; + (CMAKE_VERBOSE_MAKEFILE) _wanted booleans expl 'boolean' _cmake_booleans && ret=0;; + (CMAKE_UNITY_BUILD) _wanted booleans expl 'boolean' _cmake_booleans && ret=0;; + (CMAKE_INSTALL_PREFIX) _files -/ && ret=0;; + (CMAKE_EXPORT_COMPILE_COMMANDS) _wanted booleans expl 'boolean' _cmake_booleans && ret=0;; + (CMAKE_*_COMPILER) _wanted compilers expl 'compiler' _cmake_compilers && ret=0;; + (CMAKE_*_COMPILER_LAUNCHER) _wanted compilers expl 'compiler launcher' _cmake_launchers && ret=0;; + (CMAKE_*_FLAGS(|_?*)) _message -e compiler-flags 'compiler flags' && _dispatch $service -value-,CPPFLAGS,-default- && ret=0;; + (CMAKE_*_STANDARD_REQUIRED) _wanted booleans expl 'boolean' _cmake_booleans && ret=0;; + (CMAKE_*_EXTENSIONS) _wanted booleans expl 'boolean' _cmake_booleans && ret=0;; + (*) _files && ret=0;; + esac + + return ret +} + +local -a _cmake_generator_list=(${(f)"$(cmake --help | awk '/^Generators/{flag=1} flag && /^[* ] [^ ]/ {sub(/^[* ] /, ""); sub(/=.*$/, ""); sub(/\[arch\]/, ""); sub(/ *$/, ""); print}')"}) + +# ----------------- +# _cmake_generators +# ----------------- +(( $+functions[_cmake_generators] )) || +_cmake_generators() { + _describe -t generators 'generator' _cmake_generator_list +} + +# ---------------------- +# _cmake_toolchain_files +# ---------------------- +(( $+functions[_cmake_toolchain_files] )) || +_cmake_toolchain_files() { + _files -g '*\.cmake*' +} + +(( $+functions[_cmake_booleans] )) || +_cmake_booleans() { + _values booleans 'YES' 'NO' +} + +# --------------- +# _cmake_compilers +# +# by default just executable commands, but can be overridden by users. +# --------------- +(( $+functions[_cmake_compilers] )) || +_cmake_compilers() { + _command_names -e +} + +# --------------- +# _cmake_launchers +# +# by default just executable commands, but can be overridden by users. +# useful commands might be ccache, distcc, ... +# --------------- +(( $+functions[_cmake_launchers] )) || +_cmake_launchers() { + _command_names -e +} + +local -a _cmake_commands=( + 'capabilities:Report capabilities built into cmake in JSON format' \ + 'cat:concat the files and print them to the standard output' \ + 'chdir:run command in a given directory' \ + 'compare_files:check if file1 is same as file2' \ + 'copy:copy files to destination (either file or directory)' \ + 'copy_directory:copy content of ... directories to destination directory' \ + 'copy_if_different:copy files if it has changed' \ + 'echo:displays arguments as text' \ + 'echo_append:displays arguments as text but no new line' \ + 'env:run command in a modified environment' \ + 'environment:display the current environment' \ + 'make_directory:create parent and directories' \ + 'md5sum:create MD5 checksum of files' \ + 'sha1sum:create SHA1 checksum of files' \ + 'sha224sum:create SHA224 checksum of files' \ + 'sha256sum:create SHA256 checksum of files' \ + 'sha384sum:create SHA384 checksum of files' \ + 'sha512sum:create SHA512 checksum of files' \ + 'remove:remove the file(s), use -f to force it' \ + 'remove_directory:remove directories and their contents' \ + 'rename:rename a file or directory (on one volume)' \ + 'rm:remove files or directories' \ + 'server:start cmake in server mode' \ + 'sleep:sleep for given number of seconds' \ + 'tar:create or extract a tar or zip archive' \ + 'time:run command and display elapsed time' \ + 'touch:touch a ' \ + 'touch_nocreate:touch a but do not create it' \ + 'create_symlink:create a symbolic link new -> old' \ + 'create_hardlink:create a hard link new -> old' \ + 'true:do nothing with an exit code of 0' \ + 'false:do nothing with an exit code of 1' +) +_cmake_command() { + _arguments -C \ + '-E[CMake command mode]:command:(("${_cmake_commands[@]}"))' + +} +local cmake_suggest_build;cmake_suggest_build=( + '--build[build]:build dir:_cmake_suggest_builddirs' +) + +local cmake_suggest_install;cmake_suggest_install=( + '--install[install]:install dir:_cmake_suggest_installdirs' +) + +if [[ "$service" = -value-*CMAKE_GENERATOR* ]]; then + _cmake_generators +elif [ $CURRENT -eq 2 ] ; then + _arguments -C -s \ + - help \ + "$cmake_help_actions[@]" \ + - command \ + '-E[CMake command mode]:command:( )' \ + - build_opts \ + "$cmake_build_options[@]" \ + - build_cmds \ + "$cmake_suggest_build[@]" \ + - install_cmds \ + "$cmake_suggest_install[@]" && return 0 +elif [[ $words[2] = --help* ]] ; then + _cmake_help +elif [[ $words[2] == --build ]] ; then + _cmake_on_build +elif [[ $words[2] == --install ]] ; then + _cmake_on_install +elif [[ $words[2] == -E ]]; then + _cmake_command +else + _arguments "$cmake_build_options[@]" +fi + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_coffee b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_coffee new file mode 100644 index 00000000..ebe36e6f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_coffee @@ -0,0 +1,76 @@ +#compdef coffee +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Coffee.js v2.7.0 (https://coffeescript.org/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Mario Fernandez (https://github.com/sirech) +# * Dong Weiming (https://github.com/dongweiming) +# +# ------------------------------------------------------------------------------ + +local curcontext="$curcontext" state line ret=1 +typeset -A opt_args + +_arguments -s -S \ + '--ast[generate an abstract syntax tree of nodes]' \ + '(-b --bare)'{-b,--bare}'[compile without a top-level function wrapper]' \ + '(-c --compile)'{-c,--compile}'[compile to JavaScript and save as .js files]' \ + '(-e --eval)'{-e,--eval}'[pass a string from the command line as input]:Inline Script' \ + '(- *)'{-h,--help}'[display this help message]' \ + '(-i --interactive)'{-i,--interactive}'[run an interactive CoffeeScript REPL]' \ + '(-j --join)'{-j,--join}'[concatenate the source CoffeeScript before compiling]: :_files -g "*.coffee"' \ + '(-l --literate)'{-l,--literate}'[treat stdio as literate style coffeescript]' \ + '(-m --map)'{-m,--map}'[generate source map and save as .js.map files]' \ + '(-M --inline-map)'{-M,--inline-map}'[generate source map and include it directly in output]' \ + '(-n --nodes)'{-n,--nodes}'[print out the parse tree that the parser produces]' \ + '--nodejs[pass options directly to the "node" binary]' \ + '(-o --output)'{-o,--output}'[set the output directory for compiled JavaScript]: :_files' \ + '(-p --print --tokens)'{-p,--print}'[print out the compiled JavaScript]' \ + '(-r --require)'\*{-r,--require}'[require the given module before eval or REPL]:module' \ + '(-s --stdio)'{-s,--stdio}'[listen for and compile scripts over stdio]' \ + '(-t --transpile)'{-t,--transpile}'[pipe generated JavaScript through Babel]' \ + '(-p --print --tokens)--tokens[print out the tokens that the lexer/rewriter produce]' \ + '(- *)'{-v,--version}'[display the version number]' \ + '(-w --watch)'{-w,--watch}'[watch scripts for changes and rerun commands]' \ + '*:script or directory:_files' && ret=0 + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_conan b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_conan new file mode 100644 index 00000000..e214dff8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_conan @@ -0,0 +1,766 @@ +#compdef conan +# ------------------------------------------------------------------------------ +# Copyright (c) 2010-2017 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for conan 2.0.0 (https://conan.io). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# * Shohei Yoshida +# +# ------------------------------------------------------------------------------ + +_conan_common_options=( + '(- *)'{-h,--help}'[show help message and exit]' + '-v[verbose output]' + '-vquiet[verbose level quiet]' + '-verror[verbose level error]' + '-vwarning[verbose level warning]' + '-vnotice[verbose level notice]' + '-vstatus[verbose level status]' + '-vverbose[verbose level verbose]' + '-vv[more verbose output]' + '-vdebug[verbose level debug]' + '-vvv[more and more verbose output]' + '-vtrace[verbose level trace]' + '--logger[show the output with log format, with time, type and message]' +) + +_conan_package_options=( + '--name[Provide a package name if not specified in conanfile]:name' + '--version[Provide a package version if not specified in conanfile]:version' + '--user[Provide a user]:user' + '--channel[Provide a channel]:channel' + '--requires[directly provide requires instead of a conan file]:requires' + '--tool-requires[directly provide tool-requires instead of a conanfile]:tool_requires' +) + +_conan_define_options=( + \*{-o,--options,'-o\:h','--options\:host'}'[define options of host machine]:option' + \*{'-o\:b','--options\:build'}'[define options of build machine]:option' +) + +_conan_profile_options=( + '(-pr --profile -pr\:h --profile\:host)'{-pr,--profile,-pr:h,--profile:host}'[apply the specified profile to the host machine]: :_conan_profiles' + '(-pr\:b --profile\:build)'{-pr:b,--profile:build}'[apply the specified profile to the build machine]: :_conan_profiles' +) + +_conan_setting_options=( + \*{-s,--settings,'-s\:h','--settings\:host'}'[overwrite the defaults of host machine to build]:setting' + \*{'-s\:b','--settings\:build'}'[overwrite the defaults of build machine to build]:setting' +) + +_conan_configuration_options=( + \*{-c,--conf,'-c\:h','--conf\:host'}'[overwrite the defaults of host machine to configure]:config' + \*{'-c\:b','--conf\:build'}'[overwrite the defaults of build machine to configure]:config' +) + +_conan_lockfile_options=( + '(-l --lockfile)'{-l,--lockfile}'[path to a lockfile]: :_files' + '--lockfile-partial[do not raise an error if some dependency is not found in lockfile]' + '--lockfile-out[filename of the updated lockfile]: :_files' + '--lockfile-packages[lock package-id and package-revision information]' + '--lockfile-clean[remove unused entries from the lockfile]' +) + +_conan_remote_options=( + '(-r --remote -nr --no-remote)'{-r,--remote}'[look in the specified remote server]:remote' + '(-r --remote -nr --no-remote)'{-nr,--no-remote}'[do not use remote, resolve exclusively in the cache]' +) + +_conan() { + local context state state_descr line + typeset -A opt_args + + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(- : *)'{-v,--version}'[display version information]' \ + '(-h --help)1: :_conan_commands' \ + '(-h --help)*:: :->command_args' + + case $state in + command_args) + (( $+functions[_conan_${words[1]}] )) && _conan_${words[1]} + ;; + esac +} + +(( $+functions[_conan_commands] )) || +_conan_commands() { + local -a commands=( + # consumer commands + 'cache:perform file operations in the local cache' + 'config:manages conan configuration information' + 'graph:obtain information about the dependency graph without fetching binaries' + 'inspect:inspect a conanfile.py to return its public fields' + 'install:installs the requirements specified in a "conanfile.py" or "conanfile.txt"' + 'list:list recipes, revisions or packages in the cache or the remotes' + 'lock:create or manage lockfiles' + 'profile:manage profiles' + 'remote:manage the remote list and the users authenticated on them' + 'remove:remove recipes or packages from local cache or a remote' + 'search:search for package recipes in all the remotes or a remote' + + # create commands + 'build:install dependencies and call the build() method' + 'create:create a package' + 'download:download(without installing) a single conan package from a remote server' + 'editable:allow working with a package that resides in user folder' + 'export:export a recipe to the Conan package cache' + 'export-pkg:create a package directly from pre-compiled binaries' + 'new:create a new example recipe and source files from a template' + 'source:call the source() method' + 'test:test a package from a test_package folder' + 'upload:upload packages to a remote' + ) + + _describe -t 'subcommands' 'subcommands' commands +} + +(( $+functions[_conan_cache] )) || +_conan_cache() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '1: :(clean path)' \ + '*:: :->args' + + case $state in + (args) + local -a opts=($_conan_common_options[@]) + case $words[1] in + (clean) + opts+=( + '(-s --source)'{-s,--source}'[clean source folders]' + '(-b --build)'{-b,--build}'[clean build folders]' + '(-d --download)'{-d,--download}'[clean download folders]' + \*{-p,--package-query}'[remove only the packages matching a specific query]:query' + '1:pattern' + ) + ;; + (path) + opts+=( + '--folder[path to show]::type:(export_source source build)' \ + '1:recipe_or_package_reference:_files' + ) + ;; + esac + + _arguments "$opts[@]" + ;; + esac + + return $ret +} + +(( $+functions[_conan_config] )) || +_conan_config() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '1: :_conan_config_commands' \ + '*:: :->args' + + case $state in + (args) + local -a opts=($_conan_common_options[@]) + case $words[1] in + (install) + opts+=( + '--verify-ssl[Verify SSL connection when downloading file]: :(True False)' + '(-t --type)'{-t,--type}'[Type of remote config]: :(git dir file url)' + \*{-a,--args}'[String with extra arguments for "git clone"]:arg' + \*{-sf,--source-folder}'[Install files only from a source subfolder from specified origin]: :_files -/' + '(-tf --target-folder)'{-tf,--target-folder}'[Install to that path in the conan cache]: :_files -/' + ) + ;; + (list) + opts+=( + '(-f --format)'{-f,--format}'[select the output format]:format:(json)' + ) + ;; + esac + + _arguments "$opts[@]" + ;; + esac +} + +(( $+functions[_conan_config_commands] )) || +_conan_config_commands() { + local -a commands=( + 'home:show the Conan home folder' + 'install:install the configuration into the Conan home folder' + 'list:show all the Conan available configurations:' + ) + _describe -t 'commands' "command" commands +} + +(( $+functions[_conan_graph] )) || +_conan_graph() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '1: :_conan_graph_commands' \ + '*:: :->args' + + local -a common_opts=( + $_conan_package_options[@] + \*{-b,--build}'[optional, specify which packages to build from source]:build' + $_conan_remote_options[@] + '(-u --update)'{-u,--update}'[will check the remote and in case a newer version]' + $_conan_define_options[@] + $_conan_profile_options[@] + $_conan_setting_options[@] + $_conan_configuration_options[@] + $_conan_lockfile_options[@] + ) + + case $state in + (args) + local -a opts=($_conan_common_options[@]) + case $words[1] in + (build-order) + opts+=( + '(-f --format)'{-f,--format}'[select the output format]:format:(json)' + $common_opts[@] + ) + ;; + (build-order-merge) + opts+=( + '--file[files to be merged]:file:_files' + ) + ;; + (info) + opts+=( + $common_opts[@] + '(-f --format)'{-f,--format}'[select the output format]:format:(html json dot)' + '--check-updates[check if there are recipe updates]' + '*--filter[show only the specified fields]:filter' + '*--package-filter[print information only for packages that match the patterns]:package_filter' + '--deploy[deploy using the provided deployer to the output folder]:deployer' + ) + ;; + esac + + _arguments "$opts[@]" + ;; + esac +} + +(( $+functions[_conan_graph_commands] )) || +_conan_graph_commands() { + local -a commands=( + 'build-order:compute the build order of a dependency graph' + 'build-order-merge:merge more than 1 build-order file' + 'info:compute the dependency graph and shows information about it' + ) + _describe -t 'commands' "command" commands +} + +(( $+functions[_conan_inspect] )) || +_conan_inspect() { + _arguments \ + "$_conan_common_options[@]" \ + '(-f --format)'{-f,--format}'[select the output format]:format:(json)' \ + '*:recipe_folder:_files -/' +} + +(( $+functions[_conan_install] )) || +_conan_install() { + local -a generators=( + cmake cmake_multi cmake_paths cmake_find_package cmake_find_package_multi + msbuild visual_studio visual_studio_multi visual_studio_legacy xcode compiler_args gcc + boost-build b2 qbs qmake scons pkg_config virtualenv virtualenv_python virtualbuildenv + virtualrunenv youcompleteme txt json premake make markdown deploy + ) + local -a opts=( + $_conan_common_options[@] + '(-f --format)'{-f,--format}'[select the output format]:format:(json)' + \*{-b,--build}'[optional, specify which packages to build from source]:build' + $_conan_remote_options[@] + '(-u --update)'{-u,--update}'[will check the remote and in case a newer version]' + $_conan_define_options[@] + $_conan_profile_options[@] + $_conan_setting_options[@] + $_conan_configuration_options[@] + $_conan_lockfile_options[@] + '(-g --generator)'{-g,--generator}"[generators to use]:generator:($generators)" + '(-of --output)'{-of,--output-folder}'[the root output folder for generated and build files]:dir:_files -/' + '--deploy[deploy using the provided deployer to the output folder]:deployer' + '1:recipe_dir_or_conanfile:_files' + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_list] )) || +_conan_list() { + local -a opts=( + $_conan_common_options[@] + '(-f --format)'{-f,--format}'[select the output format]:format:(json html)' + \*{-p,--package-query}'[remove only the packages matching a specific query]:query' + '(-r --remote)'{-r,--remote}'[remote names]:remote' + '(-c --cache)'{-c,--cache}'[search in the local cache]' + '1:recipe_or_package_reference:_files' + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_lock] )) || +_conan_lock() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '1: :_conan_lock_commands' \ + '*:: :->args' + + case $state in + (args) + local -a opts=($_conan_common_options) + case $words[1] in + (add) + opts+=( + '*--requires[add references to lockfile]:requires' + '*--build-requires[add build-requires to lockfile]:build_requires' + '*--python-requires[add python-requires to lockfile]' + '--lockfile-out[file name of the created lockfile]:filename:_files' + '--lockfile[file name of the input lockfile]:filename:_files' + ) + ;; + (create) + opts+=( + \*{-b,--build}'[optional, specify which packages to build from source]:build' + $_conan_remote_options[@] + '(-u --update)'{-u,--update}'[will check the remote and in case a newer version]' + $_conan_define_options[@] + $_conan_profile_options[@] + $_conan_setting_options[@] + $_conan_configuration_options[@] + $_conan_lockfile_options[@] + '1: :_files' + ) + ;; + (merge) + opts+=( + '--lockfile-out[file name of the created lockfile]:filename:_files' + '--lockfile[file name of the input lockfile]:filename:_files' + ) + ;; + esac + + _arguments "$opts[@]" + ;; + esac +} + +(( $+functions[_conan_lock_commands] )) || +_conan_lock_commands() { + local -a commands=( + 'add:add requires, build-requires or python requires to an existing or new lockfile' + 'create:create a lockfile from a conanfile or a reference' + 'merge:merge 2 or more lockfiles' + ) + _describe -t 'commands' "command" commands +} + +(( $+functions[_conan_profile] )) || +_conan_profile() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '1: :_conan_profile_commands' \ + '*:: :->args' + + case $state in + (args) + local opts=($_conan_common_options[@]) + case $words[1] in + (detect) + opts+=( + '--name[profile name, "default" if not specified]::name' + '(-f --force)'{-f,--force}'[overwrite if exists]' + ) + ;; + (list) + opts+=( + '(-f --format)'{-f,--format}'[select the output format]:format:(json)' + ) + ;; + (path|show) + opts+=( + $_conan_define_options[@] + $_conan_profile_options[@] + $_conan_setting_options[@] + $_conan_configuration_options[@] + ) + ;; + esac + + _arguments "$opts[@]" + ;; + esac +} + +(( $+functions[_conan_profile_commands] )) || +_conan_profile_commands() { + local -a commands=( + 'detect:generate a profile using auto-detected values' + 'list:list all profiles in the cache' + 'path:show profile path location' + 'show:show aggregated profiles from the passed arguments' + ) + _describe -t 'commands' "command" commands +} + +(( $+functions[_conan_remote] )) || +_conan_remote() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '1: :_conan_remote_commands' \ + '*:: :->args' + + case $state in + (args) + local -a opts=($_conan_common_options[@]) + case $words[1] in + (add) + opts+=( + '--insecure[allow insecure server connections when using SSL]' + '--index[insert the remote at a specific position in the remote list]:index' + '(-f --force)'{-f,--force}'[force the definition of the remote even if duplicated]' + '1:name' + '2:url' + ) + ;; + (auth) + opts+=( + '--with-user[only try to auth in those remotes that already have a user name]' + '1:remote:_conan_remotes' + ) + ;; + (list|list-users) + opts+=('(-f --format)'{-f,--format}'[select the output format]:format:(json)') + ;; + (login) + opts+=( + '(-f --format)'{-f,--format}'[select the output format]:format:(json)' + '(-p --password)'{-p,--password}'[user password]:password' + '1:remote:_conan_remotes' + '2:username:' + ) + ;; + (logout) + opts+=( + '(-f --format)'{-f,--format}'[select the output format]:format:(json)' + '1:remote:_conan_remotes' + ) + ;; + (remove) + opts+=('1:remote:_conan_remotes') + ;; + (rename) + opts+=( + '1:remote:_conan_remotes' + '2:new_name' + ) + ;; + (set-user) + opts+=( + '(-f --format)'{-f,--format}'[select the output format]:format:(json)' + '1:remote:_conan_remotes' + '2:user_name' + ) + ;; + (update) + opts+=( + '--url[new url for the remote]' + '--secure[do not allow insecure server connections when using SSL]' + '--insecure[allow insecure server connections when using SSL]' + '--index[insert the remote at a specific position in the remote list]:index' + '1:remote:_conan_remotes' + ) + ;; + esac + ;; + esac +} + +(( $+functions[_conan_remote_commands] )) || +_conan_remote_commands() { + local -a commands=( + 'add:add a remote' + 'auth:authenticate in the defined remotes' + 'disable:disable all the remotes matching a pattern' + 'enable:enable all the remotes matching a pattern' + 'list:list current remotes' + 'list-users:list the users logged into all the remotes' + 'login:login into the specified remotes matching a pattern' + 'logout:clear the existing credentials for the specified remotes matching a pattern' + 'remove:remove a remote' + 'rename:rename a remote' + 'set-user:associate a username with a remote matching pattern without performing the authentication' + 'update:update a remote' + ) + _describe -t 'commands' "command" commands +} + +(( $+functions[_conan_remove] )) || +_conan_remove() { + local -a opts=( + $_conan_common_options[@] + '(-c --confirm)'{-c,--confirm}'[remove without requesting a confirmation]' + \*{-p,--package-query}'[remove only the packages matching a specific query]:query' + \*{-r,--remote}'[will remove from the specified remote]:remote' + '*:recipe_or_package_reference:_files' + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_search] )) || +_conan_search() { + local -a opts=( + $_conan_common_options[@] + \*{-r,--remote}'[will remove from the specified remote]:remote' + '*:recipe_reference:_files' + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_build] )) || +_conan_build() { + local -a opts=( + $_conan_common_options[@] + $_conan_package_options[@] + \*{-b,--build}'[optional, specify which packages to build from source]:build' + $_conan_remote_options[@] + '(-u --update)'{-u,--update}'[will check the remote and in case a newer version]' + $_conan_define_options[@] + $_conan_profile_options[@] + $_conan_setting_options[@] + $_conan_configuration_options[@] + $_conan_lockfile_options[@] + '*: :_files' + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_create] )) || +_conan_create() { + local -a opts=( + $_conan_common_options[@] + $_conan_package_options[@] + \*{-b,--build}'[optional, specify which packages to build from source]:build' + $_conan_remote_options[@] + '(-u --update)'{-u,--update}'[will check the remote and in case a newer version]' + $_conan_define_options[@] + $_conan_profile_options[@] + $_conan_setting_options[@] + $_conan_configuration_options[@] + $_conan_lockfile_options[@] + '--build-require[whether the provided reference is a build-require]' + '(-tf --test-folder)'{-tf,--test-folder}'[alternative test folder name]:folder:_files -/' + '*: :_files -/' + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_download] )) || +_conan_download() { + local -a opts=( + $_conan_common_options[@] + '--only-recipe[download only the recipe, not the binary packages]' + \*{-p,--package-query}'[only download packages matching a specific query]:query' + '(-r --remote)'{-r,--remote}'[download from the specific remote]:remote:_conan_remotes' + '*:recipe_or_package_reference:_files' + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_editable] )) || +_conan_editable() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '1: :_conan_editable_commands' \ + '*:: :->args' + + case $state in + (args) + local opts=($_conan_common_options[@]) + case $words[1] in + (add) + opts+=( + $_conan_package_options[@] + '(-of --output-folder)'{-of,--output-folder}'[the root output folder]:folder:_files -/' + ) + ;; + (list) + opts+=('(-f --format)'{-f,--format}'[select the output format]:format:(json)') + ;; + (remove) + opts+=('(-r --refs)'{-r,--refs}'[directly provide reference patterns]:refs') + ;; + esac + + _arguments "$opts[@]" + ;; + esac +} + +(( $+functions[_conan_editable_commands] )) || +_conan_editable_commands() { + local -a commands=( + 'add:define the given path location as the package reference' + 'list:list all the packages in editable mode' + 'remove:remove the editable mode for this reference' + ) + _describe -t 'commands' "command" commands +} + +(( $+functions[_conan_export] )) || +_conan_export() { + local -a opts=( + $_conan_common_options[@] + $_conan_package_options[@] + $_conan_remote_options[@] + $_conan_lockfile_options[@] + '--build-require[whether the provided reference is a build-require]' + '*: :_files -/' + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_export-pkg] )) || +_conan_export-pkg() { + local -a opts=( + $_conan_common_options[@] + $_conan_package_options[@] + $_conan_remote_options[@] + $_conan_lockfile_options[@] + $_conan_define_options[@] + $_conan_profile_options[@] + $_conan_setting_options[@] + $_conan_configuration_options[@] + '*: :_files -/' + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_new] )) || +_conan_new() { + local -a templates=( + basic cmake_lib cmake_exe meson_lib meson_exe msbuild_lib msbuild_exe + bezel_lib bezel_exe autotools_lib autotools_exe + ) + local -a opts=( + $_conan_common_options[@] + \*{-d,--define}'[define a template argument as key=value]:key_value' + '(-f --force)'{-f,--force}'[overwrite file if it already exists]' + "1:template:($templates)" + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_source] )) || +_conan_source() { + local -a opts=( + $_conan_common_options[@] + $_conan_package_options[@] + '1: :_files' + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_test] )) || +_conan_test() { + local -a opts=( + $_conan_common_options[@] + $_conan_package_options[@] + \*{-b,--build}'[optional, specify which packages to build from source]:build' + $_conan_remote_options[@] + '(-u --update)'{-u,--update}'[will check the remote and in case a newer version]' + $_conan_define_options[@] + $_conan_profile_options[@] + $_conan_setting_options[@] + $_conan_configuration_options[@] + $_conan_lockfile_options[@] + '1:path:_files -/' + '2:reference' + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_upload] )) || +_conan_upload() { + local -a opts=( + $_conan_common_options[@] + \*{-p,--package-query}'[only upload packages matching a specific query]:query' + '(-r --remote)'{-r,--remote}'[upload to this specific remote]:remote:_conan_remotes' + '--only-recipe[upload only the recipe, not the binary packages]' + '--force[force the upload of the artifacts]' + '--check[perform an integrity check before upload]' + '(-c --confirm)'{-c,--confirm}'[upload all matching recipes without confirmation]' + '1::reference' + ) + + _arguments "$opts[@]" +} + +(( $+functions[_conan_remotes] )) || +_conan_remotes() { + local -a remotes=(${(f)"$(_call_program remotes $service remote list)"}) + _describe -t remotes 'remote' remotes "$@" +} + +(( $+functions[_conan_profiles] )) || +_conan_profiles() { + local -a profiles=(${(f)"$(_call_program profiles $service profile list 2>/dev/null)"}) + _describe -t profiles 'profile' profiles "$@" +} + +_conan "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_concourse b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_concourse new file mode 100644 index 00000000..36353447 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_concourse @@ -0,0 +1,1517 @@ +#compdef concourse fly +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for concourse 5.2.0 (https://concourse-ci.org). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# +# ------------------------------------------------------------------------------ + +local _concourse_fly_target \ + _concourse_fly_pipeline \ + _concourse_fly_pipeline_config \ + _concourse_fly_job \ + _concourse_fly_resource \ + _concourse_fly_resource_type + +(( $+functions[_concourse_fly] )) || +_concourse_fly() { + + local context state state_descr line ret=1 + typeset -A opt_args + + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(- : *)'{-v,--version}'[print the version of Fly and exit]' \ + {-t,--target=}'[concourse target name]: :_concourse_fly_targets' \ + --verbose'[print API requests and responses]' \ + --print-table-headers'[print table headers even for redirected output]' \ + '(-): :->command' \ + '(-)*:: :->arguments' \ + && ret=0 + + case $state in + (command) + _concourse_fly_commands + ;; + (arguments) + curcontext=${curcontext%:*:*}:concourse-fly-$words[1]: + if (( $+functions[_concourse_fly_${words[1]}_args] )); then + _concourse_fly_target=${(v)opt_args[(i)-t|--target]} + _concourse_fly_${words[1]}_args && ret=0 + else + _message "unknown command ${words[1]}" && ret=1 + fi + ;; + esac + + return ret +} + +(( $+functions[_concourse_fly_commands] )) || +_concourse_fly_commands() { + local commands=( + {ab,abort-build}":abort a build" + {bs,builds}":list builds data" + {cr,check-resource}":check a resource" + {crt,check-resource-type}":check a resource-type" + {cl,checklist}":print a Checkfile of the given pipeline" + {ctc,clear-task-cache}":clears cache from a task container" + {cs,containers}":print the active containers" + {c,curl}":curl the api" + {dtg,delete-target}":delete target" + {dp,destroy-pipeline}":destroy a pipeline" + {dt,destroy-team}":destroy a team and delete all of its data" + {etg,edit-target}":edit a target" + {e,execute}":execute a one-off build using local bits" + {ep,expose-pipeline}":make a pipeline publicly viewable" + {fp,format-pipeline}":format a pipeline config" + {gp,get-pipeline}":get a pipeline's current configuration" + {gt,get-team}":show team configuration" + "help:print help message" + {hp,hide-pipeline}":hide a pipeline from the public" + {i,intercept,hijack}":execute a command in a container" + {js,jobs}":list the jobs in the pipelines" + {lw,land-worker}":land a worker" + {l,login}":authenticate with the target" + {o,logout}":release authentication with the target" + {op,order-pipelines}":orders pipelines" + {pj,pause-job}":pause a job" + {pp,pause-pipeline}":pause a pipeline" + {ps,pipelines}":list the configured pipelines" + {pw,prune-worker}":prune a stalled, landing, landed, or retiring worker" + {rp,rename-pipeline}":rename a pipeline" + {rt,rename-team}":rename a team" + {rvs,resource-versions}":list the versions of a resource" + {rs,resources}":list the resources in the pipeline" + {sp,set-pipeline}":create or update a pipeline's configuration" + {st,set-team}":create or modify a team to have the given credentials" + "status:login status" + {s,sync}":download and replace the current fly from the target" + {ts,targets}":list saved targets" + {t,teams}":list the configured teams" + {tj,trigger-job}":start a job in a pipeline" + {uj,unpause-job}":unpause a job" + {up,unpause-pipeline}":un-pause a pipeline" + "userinfo:user information" + {vp,validate-pipeline}":validate a pipeline config" + {vs,volumes}":list the active volumes" + {w,watch}":stream a build's output" + {ws,workers}":list the registered workers" + ) + _describe -t commands commands commands +} + +(( $+functions[_concourse_fly_ab_args] )) || +_concourse_fly_ab_args() { + _concourse_fly_abort-build_args +} + +(( $+functions[_concourse_fly_bs_args] )) || +_concourse_fly_bs_args() { + _concourse_fly_builds_args +} + +(( $+functions[_concourse_fly_cl_args] )) || +_concourse_fly_cl_args() { + _concourse_fly_checklist_args +} + +(( $+functions[_concourse_fly_cr_args] )) || +_concourse_fly_cr_args() { + _concourse_fly_check-resource_args +} + +(( $+functions[_concourse_fly_crt_args] )) || +_concourse_fly_crt_args() { + _concourse_fly_check-resource-type_args +} + +(( $+functions[_concourse_fly_ctc_args] )) || +_concourse_fly_ctc_args() { + _concourse_fly_clear-task-cache_args +} + +(( $+functions[_concourse_fly_cs_args] )) || +_concourse_fly_cs_args() { + _concourse_fly_containers_args +} + +(( $+functions[_concourse_fly_c_args] )) || +_concourse_fly_c_args() { + _concourse_fly_curl_args +} + +(( $+functions[_concourse_fly_dtg_args] )) || +_concourse_fly_dtg_args() { + _concourse_fly_delete-target_args +} + +(( $+functions[_concourse_fly_dp_args] )) || +_concourse_fly_dp_args() { + _concourse_fly_destroy-pipeline_args +} + +(( $+functions[_concourse_fly_dt_args] )) || +_concourse_fly_dt_args() { + _concourse_fly_destroy-team_args +} + +(( $+functions[_concourse_fly_etg_args] )) || +_concourse_fly_etg_args() { + _concourse_fly_edit-target_args +} + +(( $+functions[_concourse_fly_e_args] )) || +_concourse_fly_e_args() { + _concourse_fly_execute_args +} + +(( $+functions[_concourse_fly_ep_args] )) || +_concourse_fly_ep_args() { + _concourse_fly_expose-pipeline_args +} + +(( $+functions[_concourse_fly_fp_args] )) || +_concourse_fly_fp_args() { + _concourse_fly_format-pipeline_args +} + +(( $+functions[_concourse_fly_gp_args] )) || +_concourse_fly_gp_args() { + _concourse_fly_get-pipeline_args +} + +(( $+functions[_concourse_fly_gt_args] )) || +_concourse_fly_gt_args() { + _concourse_fly_get-team_args +} + +(( $+functions[_concourse_fly_hp_args] )) || +_concourse_fly_hp_args() { + _concourse_fly_hide-pipeline_args +} + +(( $+functions[_concourse_fly_hijack_args] )) || +_concourse_fly_hijack_args() { + _concourse_fly_intercept_args +} + +(( $+functions[_concourse_fly_i_args] )) || +_concourse_fly_i_args() { + _concourse_fly_intercept_args +} + +(( $+functions[_concourse_fly_js_args] )) || +_concourse_fly_js_args() { + _concourse_fly_jobs_args +} + +(( $+functions[_concourse_fly_lw_args] )) || +_concourse_fly_lw_args() { + _concourse_fly_land-worker_args +} + +(( $+functions[_concourse_fly_l_args] )) || +_concourse_fly_l_args() { + _concourse_fly_login_args +} + +(( $+functions[_concourse_fly_o_args] )) || +_concourse_fly_o_args() { + _concourse_fly_logout_args +} + +(( $+functions[_concourse_fly_op_args] )) || +_concourse_fly_op_args() { + _concourse_fly_order-pipelines_args +} + +(( $+functions[_concourse_fly_pj_args] )) || +_concourse_fly_pj_args() { + _concourse_fly_pause-job_args +} + +(( $+functions[_concourse_fly_pp_args] )) || +_concourse_fly_pp_args() { + _concourse_fly_pause-pipeline_args +} + +(( $+functions[_concourse_fly_ps_args] )) || +_concourse_fly_ps_args() { + _concourse_fly_pipelines_args +} + +(( $+functions[_concourse_fly_pw_args] )) || +_concourse_fly_pw_args() { + _concourse_fly_prune-worker_args +} + +(( $+functions[_concourse_fly_rp_args] )) || +_concourse_fly_rp_args() { + _concourse_fly_rename-pipeline_args +} + +(( $+functions[_concourse_fly_rt_args] )) || +_concourse_fly_rt_args() { + _concourse_fly_rename-team_args +} + +(( $+functions[_concourse_fly_rs_args] )) || +_concourse_fly_rs_args() { + _concourse_fly_resources_args +} + +(( $+functions[_concourse_fly_rvs_args] )) || +_concourse_fly_rvs_args() { + _concourse_fly_resource-versions_args +} + +(( $+functions[_concourse_fly_sp_args] )) || +_concourse_fly_sp_args() { + _concourse_fly_set-pipeline_args +} + +(( $+functions[_concourse_fly_st_args] )) || +_concourse_fly_st_args() { + _concourse_fly_set-team_args +} + +(( $+functions[_concourse_fly_s_args] )) || +_concourse_fly_s_args() { + _concourse_fly_sync_args +} + +(( $+functions[_concourse_fly_ts_args] )) || +_concourse_fly_ts_args() { + _concourse_fly_targets_args +} + +(( $+functions[_concourse_fly_t_args] )) || +_concourse_fly_t_args() { + _concourse_fly_teams_args +} + +(( $+functions[_concourse_fly_tj_args] )) || +_concourse_fly_tj_args() { + _concourse_fly_trigger-job_args +} + +(( $+functions[_concourse_fly_uj_args] )) || +_concourse_fly_uj_args() { + _concourse_fly_unpause-job_args +} + +(( $+functions[_concourse_fly_up_args] )) || +_concourse_fly_up_args() { + _concourse_fly_unpause-pipeline_args +} + +(( $+functions[_concourse_fly_vp_args] )) || +_concourse_fly_vp_args() { + _concourse_fly_validate-pipeline_args +} + +(( $+functions[_concourse_fly_vs_args] )) || +_concourse_fly_vs_args() { + _concourse_fly_volumes_args +} + +(( $+functions[_concourse_fly_w_args] )) || +_concourse_fly_w_args() { + _concourse_fly_watch_args +} + +(( $+functions[_concourse_fly_ws_args] )) || +_concourse_fly_ws_args() { + _concourse_fly_workers_args +} + +(( $+functions[_concourse_fly_help_args] )) || +_concourse_fly_help_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' +} + +(( $+functions[_concourse_fly_status_args] )) || +_concourse_fly_status_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' +} + +(( $+functions[_concourse_fly_userinfo_args] )) || +_concourse_fly_userinfo_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '--json[print command result as JSON]' +} + +(( $+functions[_concourse_fly_abort-build_args] )) || +_concourse_fly_abort-build_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-j --job)'{-j,--job=}'[name of a job to cancel]: :_concourse_fly_pipeline_slash_jobs' \ + '(-b --build)'{-b,--build=}'[job build number to cancel, or build id]: :_concourse_fly_builds' +} + +(( $+functions[_concourse_fly_builds_args] )) || +_concourse_fly_builds_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-a --all-teams)'{-a,--all-teams}'[show builds for the all teams that user has access to]' \ + '(-c --count)'{-c,--count=}'[number of builds you want to limit the return to]: :number' \ + '--current-team[show builds for the currently targeted team]' \ + '(-j --job -p --pipeline)'{-j,--job=}'[name of a job to get builds for]: :_concourse_fly_pipeline_slash_jobs' \ + '--json[print command result as JSON]' \ + '(-j --job -p --pipeline)'{-p,--pipeline=}'[name of a pipeline to get builds for]: :_concourse_fly_pipelines' \ + '--since=[start of the range to filter builds]: :_concourse_fly_dates' \ + '--until=[end of the range to filter builds]: :_concourse_fly_dates' +} + +(( $+functions[_concourse_fly_checklist_args] )) || +_concourse_fly_checklist_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-p --pipeline)'{-p,--pipeline=}'[the pipeline from which to generate the Checkfile]: :_concourse_fly_pipelines' +} + +(( $+functions[_concourse_fly_check-resource_args] )) || +_concourse_fly_check-resource_args() { + + local context state state_descr line ret=1 + typeset -A opt_args + + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-r --resource)'{-r,--resource=}'[name of a resource to check]: :_concourse_fly_pipeline_slash_resources' \ + '(-f --from)'{-f,--from=}'[version of the resource to check from]: :->version' \ + && ret=0 + + case $state in + (version) + _concourse_fly_resource=${(v)opt_args[(i)-r|--resource]} + _concourse_fly_pipeline_resource_versions && ret=0 + ;; + esac + + return ret +} + +(( $+functions[_concourse_fly_check-resource-type_args] )) || +_concourse_fly_check-resource-type_args() { + + local context state state_descr line ret=1 + typeset -A opt_args + + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-r --resource-type)'{-r,--resource-type=}'[name of a resource type to check]: :_concourse_fly_pipeline_slash_resource_types' \ + '(-f --from)'{-f,--from=}'[version of the resource type to check from]: :->version' \ + && ret=0 + + case $state in + (version) + _concourse_fly_resource_type=${(v)opt_args[(i)-r|--resource-type]} + _concourse_fly_pipeline_resource_type_versions && ret=0 + ;; + esac + + return ret +} + +(( $+functions[_concourse_fly_clear-task-cache_args] )) || +_concourse_fly_clear-task-cache_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-j --job)'{-j,--job=}'[name of a job to cancel]: :_concourse_fly_pipeline_slash_jobs' \ + '(-s --step)'{-s,--step=}'[step name to clear cache from]:task step' \ + '(-c --cache-path)'{-c,--cache-path=}'[cache directory to clear out]: :_files -/' \ + '(-n --non-interactive)'{-n,--non-interactive=}'[destroy the task cache(s) without confirmation]' +} + +(( $+functions[_concourse_fly_containers_args] )) || +_concourse_fly_containers_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '--json[print command result as JSON]' +} + +(( $+functions[_concourse_fly_curl_args] )) || +_concourse_fly_curl_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '--print-and-exit[print curl command and exit]' +} + +(( $+functions[_concourse_fly_delete-target_args] )) || +_concourse_fly_delete-target_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-a --all)'{-a,--all}'[delete all targets]' +} + +(( $+functions[_concourse_fly_destroy-pipeline_args] )) || +_concourse_fly_destroy-pipeline_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-p --pipeline)'{-p,--pipeline=}'[the pipeline to destroy]: :_concourse_fly_pipelines' \ + '(-n --non-interactive)'{-n,--non-interactive}'[destroy the pipeline without confirmation]' +} + +(( $+functions[_concourse_fly_destroy-team_args] )) || +_concourse_fly_destroy-team_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-n --team-name)'{-n,--team-name=}'[the team to delete]: :_concourse_fly_teams' \ + '(-n --non-interactive)'{-n,--non-interactive}'[force apply configuration]' +} + +(( $+functions[_concourse_fly_edit-target_args] )) || +_concourse_fly_edit-target_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '--target-name=[update target name]: :_concourse_fly_targets' \ + '(-u --concourse-url)'{-u,--concourse-url=}'[update concourse URL]: :_urls' \ + '(-n --team-name)'{-n,--team-name=}'[update concourse URL]: :_concourse_fly_teams' +} + +(( $+functions[_concourse_fly_execute_args] )) || +_concourse_fly_execute_args() { + + local context state state_descr line ret=1 + typeset -A opt_args + + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-c --config)'{-c,--config=}'[the task config to execute]: :_concourse_config_files' \ + '(-p --privileged)'{-p,--privileged}'[run the task with full privileges]' \ + '--include-ignored[disregard .gitignore entries and uploads everything]' \ + '*'{-i,--input=}'[an input to provide to the task]: :->input' \ + '*'{-m,--input-mapping=}'[map a resource to a different name as task input]: :->input-mapping' \ + '(-j --inputs-from)'{-j,--inputs-from=}'[a job to base the inputs on]: :_concourse_fly_pipeline_slash_jobs' \ + '*'{-o,--output=}'[an output to fetch from the task]: :->output' \ + '--image=[image resource for the one-off build]: :_concourse_fly_images' \ + '*--tag=[a tag for a specific environment]: :_concourse_fly_tags' \ + '*'{-v,--var=}'[specify a string value to set for a variable in the pipeline]: :->var' \ + '*'{-y,--yaml-var=}'[specify a YAML value to set for a variable in the pipeline]: :->var' \ + '(-l --load-vars-from)'{-l,--load-vars-from=}'[variable flag that can be used for filling in template values in configuration from a YAML file]: :_files' \ + && ret=0 + + _concourse_fly_pipeline_config=${(v)opt_args[(i)-c|--config]} + + case $state in + (input-mapping) + # TODO complete --input-mapping + _message 'input mapping' + ;; + (input) + _concourse_fly_input_equal_paths && ret=0 + ;; + (output) + _concourse_fly_output_equal_paths && ret=0 + ;; + (var) + _concourse_fly_var_equal_values && ret=0 + ;; + esac + + return ret +} + +(( $+functions[_concourse_fly_expose-pipeline_args] )) || +_concourse_fly_expose-pipeline_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-p --pipeline)'{-p,--pipeline=}'[pipeline to expose]: :_concourse_fly_pipelines' +} + +(( $+functions[_concourse_fly_format-pipeline_args] )) || +_concourse_fly_format-pipeline_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-c --config)'{-c,--config=}'[pipeline configuration file]: :_concourse_config_files' \ + '(-w --write)'{-w,--write}'[do not print to stdout, overwrite the file in place]' +} + +(( $+functions[_concourse_fly_get-pipeline_args] )) || +_concourse_fly_get-pipeline_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-p --pipeline)'{-p,--pipeline=}'[get configuration of this pipeline]: :_concourse_fly_pipelines' \ + '(-j --json)'{-j,--json}'[print config as json instead of yaml]' +} + +(( $+functions[_concourse_fly_get-team_args] )) || +_concourse_fly_get-team_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-n --team)'{-n,--team=}'[get configuration of this team]: :_concourse_fly_teams' \ + '(-j --json)'{-j,--json}'[print config as json instead of yaml]' +} + +(( $+functions[_concourse_fly_hide-pipeline_args] )) || +_concourse_fly_hide-pipeline_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-p --pipeline)'{-p,--pipeline=}'[pipeline to hide]: :_concourse_fly_pipelines' +} + +(( $+functions[_concourse_fly_intercept_args] )) || +_concourse_fly_intercept_args() { + # TODO complete --handle + # TODO complete --check + # TODO complete --step + # TODO complete --step-type + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-j --job --handle -c --check -u --url)'{-j,--job=}'[name of a job to hijack]: :_concourse_fly_pipeline_slash_jobs' \ + '(-j --job --handle -c --check -u --url)--handle=[handle id of a job to hijack]:job handle' \ + '(-j --job --handle -c --check -u --url)'{-c,--check=}'[name of a resource'\''s checking container to hijack]:name' \ + '(-j --job --handle -c --check -u --url)'{-u,--url=}'[URL for the build, job, or check container to hijack]: :_urls' \ + '(-b --build)'{-b,--build=}'[build number within the job, or global build ID]: :_concourse_fly_builds' \ + '(-s --step)'{-s,--step=}'[name of step to hijack]:step' \ + '--step-type=[type of step to hijack]:step type' \ + '(-a --attempt)'{-a,--attempt=}'[attempt number of step to hijack]: :_values -s, "number" 1 2 3 4 5 6 7 8 9' \ + '(-):command name: _command_names -e' \ + '*::arguments:_normal' +} + +(( $+functions[_concourse_fly_jobs_args] )) || +_concourse_fly_jobs_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-p --pipeline)'{-p,--pipeline=}'[get jobs in this pipeline]: :_concourse_fly_pipelines' \ + '--json[print command result as JSON]' +} + +(( $+functions[_concourse_fly_land-worker_args] )) || +_concourse_fly_land-worker_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-w --worker)'{-w,--worker=}'[worker to land]: :_concourse_fly_workers' +} + +(( $+functions[_concourse_fly_login_args] )) || +_concourse_fly_login_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-c --concourse-url)'{-c,--concourse-url=}'[concourse URL to authenticate with]: :_urls' \ + '(-k --insecure)'{-k,--insecure}'[skip verification of the endpoint'\''s SSL certificate]' \ + '(-u --username)'{-u,--username=}'[username for basic auth]: :_users' \ + '(-p --password)'{-p,--password=}'[password for basic auth]:password' \ + '(-n --team-name)'{-n,--team-name=}'[team to authenticate with]: :_concourse_fly_teams' \ + '--ca-cert=[path to Concourse PEM-encoded CA certificate file]: :_files -g "*.pem"' \ + '(-b --open-browser)'{-b,--open-browser}'[open browser to the auth endpoint]' +} + +(( $+functions[_concourse_fly_logout_args] )) || +_concourse_fly_logout_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-a --all)'{-a,--all}'[logout of all targets]' +} + +(( $+functions[_concourse_fly_order-pipelines_args] )) || +_concourse_fly_order-pipelines_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-p --pipeline)'{-p,--pipeline=}'[name of pipeline to order]: :_concourse_fly_pipelines' +} + +(( $+functions[_concourse_fly_pause-job_args] )) || +_concourse_fly_pause-job_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-j --job)'{-j,--job=}'[name of a job to pause]: :_concourse_fly_pipeline_slash_jobs' +} + +(( $+functions[_concourse_fly_pause-pipeline_args] )) || +_concourse_fly_pause-pipeline_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-p --pipeline)'{-p,--pipeline=}'[pipeline to pause]: :_concourse_fly_pipelines' +} + +(( $+functions[_concourse_fly_pipelines_args] )) || +_concourse_fly_pipelines_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-a --all)'{-a,--all}'[show all pipelines]' \ + '--json[print command result as JSON]' +} + +(( $+functions[_concourse_fly_prune-worker_args] )) || +_concourse_fly_prune-worker_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-w --worker)'{-w,--worker=}'[worker to prune]: :_concourse_fly_workers' \ + '(-a --all-stalled)'{-a,--all-stalled}'[prune all stalled workers]' +} + +(( $+functions[_concourse_fly_rename-pipeline_args] )) || +_concourse_fly_rename-pipeline_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-o --old-name)'{-o,--old-name=}'[pipeline to rename]: :_concourse_fly_pipelines' \ + '(-n --new-name)'{-n,--new-name=}'[name to set as pipeline name]: :_concourse_fly_pipelines' +} + +(( $+functions[_concourse_fly_rename-team_args] )) || +_concourse_fly_rename-team_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-o --old-name)'{-o,--old-name=}'[current team name]: :_concourse_fly_teams' \ + '(-n --new-name)'{-n,--new-name=}'[new team name]: :_concourse_fly_teams' +} + +(( $+functions[_concourse_fly_resources_args] )) || +_concourse_fly_resources_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-p --pipeline)'{-p,--pipeline=}'[get resources in this pipeline]: :_concourse_fly_pipelines' \ + '--json[print command result as JSON]' +} + +(( $+functions[_concourse_fly_resource-versions_args] )) || +_concourse_fly_resource-versions_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-c --count)'{-c,--count=}'[number of builds you want to limit the return to]:number' \ + '(-r --resource)'{-r,--resource=}'[name of a resource to get versions for]: :_concourse_fly_pipeline_slash_resources' \ + '--json[print command result as JSON]' +} + +(( $+functions[_concourse_fly_set-pipeline_args] )) || +_concourse_fly_set-pipeline_args() { + + local context state state_descr line ret=1 + typeset -A opt_args + + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-n --non-interactive)'{-n,--non-interactive}'[skips interactions, uses default values]' \ + '--no-color[disable color output]' \ + '--check-creds[validate credential variables against credential manager]' \ + '(-p --pipeline)'{-p,--pipeline=}'[pipeline to configure]: :_concourse_fly_pipelines' \ + '(-c --config)'{-c,--config=}'[pipeline configuration file]: :_concourse_config_files' \ + '*'{-v,--var=}'[specify a string value to set for a variable in the pipeline]: :->var' \ + '*'{-y,--yaml-var=}'[specify a YAML value to set for a variable in the pipeline]: :->var' \ + '(-l --load-vars-from)'{-l,--load-vars-from=}'[variable flag that can be used for filling in template values in configuration from a YAML file]: :_files' \ + && ret=0 + + _concourse_fly_pipeline_config=${(v)opt_args[(i)-c|--config]} + + case $state in + (var) + _concourse_fly_var_equal_values && ret=0 + ;; + esac + + return ret +} + +(( $+functions[_concourse_fly_set-team_args] )) || +_concourse_fly_set-team_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-n --team-name)'{-n,--team-name=}'[the team to create or modify]: :_concourse_fly_teams' \ + '--non-interactive[force apply configuration]' \ + '*--local-user=[list of whitelisted local concourse users]: :_users' \ + '(-c --config)'{-c,--config=}'[configuration file for specifying team params]: :_concourse_config_files' \ + '*--bitbucket-cloud-user=[list of whitelisted Bitbucket Cloud users]:user name' \ + '*--bitbucket-cloud-team=[list of whitelisted Bitbucket Cloud teams]:team name' \ + '*--cf-user=[list of whitelisted CloudFoundry users]:user name' \ + '*--cf-org=[list of whitelisted CloudFoundry orgs]:org name' \ + '*--cf-space=[list of whitelisted CloudFoundry spaces]:space name' \ + '*--github-user=[list of whitelisted GitHub users]:user name' \ + '*--github-org=[list of whitelisted GitHub orgs]:org name' \ + '*--github-team=[list of whitelisted GitHub teams]:team name' \ + '*--gitlab-user=[list of whitelisted GitLab users]:user name' \ + '*--gitlab-group=[list of whitelisted GitLab groups]:group name' \ + '*--ldap-user=[list of whitelisted LDAP users]:user name' \ + '*--ldap-group=[list of whitelisted LDAP groups]:group name' \ + '*--oauth-user=[list of whitelisted OAuth2 users]:user name' \ + '*--oauth-group=[list of whitelisted OAuth2 groups]:group name' \ + '*--oidc-user=[list of whitelisted OIDC users]:user name' \ + '*--oidc-group=[list of whitelisted OIDC groups]:group name' +} + +(( $+functions[_concourse_fly_sync_args] )) || +_concourse_fly_sync_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-f --force)'{-f,--force}'[sync even if versions already match]' +} + +(( $+functions[_concourse_fly_targets_args] )) || +_concourse_fly_targets_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' +} + +(( $+functions[_concourse_fly_teams_args] )) || +_concourse_fly_teams_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-d --details)'{-d,--details}'[print authentication configuration]' \ + '--json[print command result as JSON]' +} + +(( $+functions[_concourse_fly_trigger-job_args] )) || +_concourse_fly_trigger-job_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-j --job)'{-j,--job=}'[name of a job to trigger]: :_concourse_fly_pipeline_slash_jobs' \ + '(-w --watch)'{-w,--watch}'[start watching the build output]' +} + +(( $+functions[_concourse_fly_unpause-job_args] )) || +_concourse_fly_unpause-job_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-j --job)'{-j,--job=}'[name of a job to unpause]: :_concourse_fly_pipeline_slash_jobs' +} + +(( $+functions[_concourse_fly_unpause-pipeline_args] )) || +_concourse_fly_unpause-pipeline_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-p --pipeline)'{-p,--pipeline=}'[pipeline to unpause]: :_concourse_fly_pipelines' +} + +(( $+functions[_concourse_fly_validate-pipeline_args] )) || +_concourse_fly_validate-pipeline_args() { + + local context state state_descr line ret=1 + typeset -A opt_args + + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-c --config)'{-c,--config=}'[pipeline configuration file]: :_concourse_config_files' \ + '(-s --strict)'{-s,--strict}'[fail on warnings]' \ + '(-o --output)'{-o,--output}'[output templated pipeline to stdout]' \ + '*'{-v,--var=}'[specify a string value to set for a variable in the pipeline]: :->var' \ + '*'{-y,--yaml-var=}'[specify a YAML value to set for a variable in the pipeline]: :->var' \ + '(-l --load-vars-from)'{-l,--load-vars-from=}'[variable flag that can be used for filling in template values in configuration from a YAML file]: :_files' \ + && ret=0 + + _concourse_fly_pipeline_config=${(v)opt_args[(i)-c|--config]} + + case $state in + (var) + _concourse_fly_var_equal_values && ret=0 + ;; + esac + + return ret +} + +(( $+functions[_concourse_fly_volumes_args] )) || +_concourse_fly_volumes_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-d --details)'{-d,--details}'[print additional information for each volume]' \ + '--json[print command result as JSON]' +} + +(( $+functions[_concourse_fly_watch_args] )) || +_concourse_fly_watch_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-j --job)'{-j,--job=}'[watches builds of the given job]: :_concourse_fly_pipeline_slash_jobs' \ + '(-b --build)'{-b,--build=}'[watches a specific build]: :_concourse_fly_builds' \ + '(-t --timestamps)'{-t,--timestamps}'[print with local timestamp]' +} + +(( $+functions[_concourse_fly_workers_args] )) || +_concourse_fly_workers_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-d --details)'{-d,--details}'[print additional information for each worker]' \ + '--json[print command result as JSON]' +} + +(( $+functions[_concourse_fly_targets] )) || +_concourse_fly_targets() { + local targets=($(_call_program targets $service targets | awk '{print $1}')) + _describe -t targets 'target' targets $@ || _message 'no target found' +} + +(( $+functions[_concourse_fly_teams] )) || +_concourse_fly_teams() { + if [[ -n ${_concourse_fly_target} ]]; then + local teams=($(_call_program teams $service -t ${_concourse_fly_target} teams | awk '{print $1}')) + _describe -t teams 'team' teams $@ || _message 'no team found' + else + _message 'team' + fi +} + +(( $+functions[_concourse_fly_pipelines] )) || +_concourse_fly_pipelines() { + if [[ -n ${_concourse_fly_target} ]]; then + local pipelines=($(_call_program pipelines $service -t ${_concourse_fly_target} pipelines | awk '{print $1}')) + _describe -t pipelines 'pipeline' pipelines $@ || _message 'no pipeline found' + else + _message 'pipeline' + fi +} + +(( $+functions[_concourse_fly_pipeline_jobs] )) || +_concourse_fly_pipeline_jobs() { + if [[ -n ${_concourse_fly_target} ]] && [[ -n ${_concourse_fly_pipeline} ]]; then + local jobs=($(_call_program jobs $service -t ${_concourse_fly_target} jobs -p ${_concourse_fly_pipeline} 2>&1 | awk '{print $1}')) + _describe -t jobs "${_concourse_fly_pipeline} job" jobs $@ || _message 'no job found' + else + _message 'job' + fi +} + +(( $+functions[_concourse_fly_pipeline_resources] )) || +_concourse_fly_pipeline_resources() { + if [[ -n ${_concourse_fly_target} ]] && [[ -n ${_concourse_fly_pipeline} ]]; then + local resources=($(_call_program resources $service -t ${_concourse_fly_target} resources -p ${_concourse_fly_pipeline} | awk '{print $1}')) + _describe -t resources 'resource' resources $@ || _message 'no resource found' + else + _message 'resource' + fi +} + +(( $+functions[_concourse_fly_pipeline_resource_types] )) || +_concourse_fly_pipeline_resource_types() { + if [[ -n ${_concourse_fly_target} ]] && [[ -n ${_concourse_fly_pipeline} ]]; then + local resource_types=($(_call_program resource-types $service -t ${_concourse_fly_target} resources -p ${_concourse_fly_pipeline} | awk '{print $2}')) + _describe -t resource-types 'resource type' resource_types $@ || _message 'no resource type found' + else + _message 'resource type' + fi +} + +(( $+functions[_concourse_fly_workers] )) || +_concourse_fly_workers() { + if [[ -n ${_concourse_fly_target} ]]; then + local workers=($(_call_program workers $service -t ${_concourse_fly_target} workers | awk '{print $1}')) + _describe -t workers 'worker' workers $@ || _message 'no worker found' + else + _message 'worker' + fi +} + +(( $+functions[_concourse_fly_builds] )) || +_concourse_fly_builds() { + if [[ -n ${_concourse_fly_target} ]]; then + local builds=($(_call_program builds $service -t ${_concourse_fly_target} builds | awk '{print $1}')) + _describe -t builds 'build' builds $@ || _message 'no build found' + else + _message 'build' + fi +} + +(( $+functions[_concourse_fly_pipeline_resource_versions] )) || +_concourse_fly_pipeline_resource_versions() { + if [[ -n ${_concourse_fly_target} ]] && [[ -n ${_concourse_fly_resource} ]]; then + local resource_versions=($(_call_program resource-versions $service -t ${_concourse_fly_target} resource-versions -r ${_concourse_fly_resource} | awk '{print $2}')) + _describe -t resource-versions 'resource version' resource_versions $@ || _message 'no version found' + else + _message 'resource version' + fi +} + +(( $+functions[_concourse_fly_pipeline_config_vars] )) || +_concourse_fly_pipeline_config_vars() { + if [[ -n ${_concourse_fly_pipeline_config} ]]; then + local variables=($(grep -Po '(?<=\(\()[^\)]+' ${_concourse_fly_pipeline_config})) + _describe -t variables 'variables' variables $@ || _message 'no variable found' + else + _message 'variable' + fi +} + +(( $+functions[_concourse_fly_pipeline_config_inputs] )) || +_concourse_fly_pipeline_config_inputs() { + if [[ -n ${_concourse_fly_pipeline_config} ]]; then + if (( $+commands[yq] )); then + local inputs=($(yq -r '.. | .inputs? | arrays | .[].name' ${_concourse_fly_pipeline_config} 2>&1)) + _describe -t inputs 'input' inputs $@ || _message 'no input found' + else + _message 'install yq (https://github.com/kislyuk/yq) to get completion of inputs' + fi + else + _message 'input' + fi +} + +(( $+functions[_concourse_fly_pipeline_config_outputs] )) || +_concourse_fly_pipeline_config_outputs() { + if [[ -n ${_concourse_fly_pipeline_config} ]]; then + if (( $+commands[yq] )); then + local outputs=($(yq -r '.. | .outputs? | arrays | .[].name' ${_concourse_fly_pipeline_config})) + _describe -t outputs 'output' outputs $@ || _message 'no output found' + else + _message 'install yq (https://github.com/kislyuk/yq) to get completion of outputs' + fi + else + _message 'output' + fi +} + +(( $+functions[_concourse_fly_pipeline_resource_type_versions] )) || +_concourse_fly_pipeline_resource_type_versions() { + # seems like there is no command for listing resource type versions... + _message 'resource type version' +} + +(( $+functions[_concourse_fly_tags] )) || +_concourse_fly_tags() { + # seems like there is no command for listing tags... + _message 'tag' +} + +(( $+functions[_concourse_fly_dates] )) || +_concourse_fly_dates() { + # _dates completer does not seem to work on zsh 5.7.1 + _dates -f '%Y-%m-%d %H:%M:%S' +} + +(( $+functions[_concourse_fly_pipeline_slash_jobs] )) || +_concourse_fly_pipeline_slash_jobs() { + local ret=1 + if compset -P '*/'; then + _concourse_fly_pipeline="${${IPREFIX%/}##*=}" + _concourse_fly_pipeline_jobs && ret=0 + else + _concourse_fly_pipelines -qS/ && ret=0 + fi + return ret +} + +(( $+functions[_concourse_fly_pipeline_slash_resources] )) || +_concourse_fly_pipeline_slash_resources() { + local ret=1 + if compset -P '*/'; then + _concourse_fly_pipeline="${${IPREFIX%/}##*=}" + _concourse_fly_pipeline_resources && ret=0 + else + _concourse_fly_pipelines -qS/ && ret=0 + fi + return ret +} + +(( $+functions[_concourse_fly_pipeline_slash_resource_types] )) || +_concourse_fly_pipeline_slash_resource_types() { + local ret=1 + if compset -P '*/'; then + _concourse_fly_pipeline="${${IPREFIX%/}##*=}" + _concourse_fly_pipeline_resource_types && ret=0 + else + _concourse_fly_pipelines -qS/ && ret=0 + fi + return ret +} + +(( $+functions[_concourse_fly_var_equal_values] )) || +_concourse_fly_var_equal_values() { + local ret=1 + if compset -P '*='; then + _message 'value' && ret=0 + else + _concourse_fly_pipeline_config_vars -qS= && ret=0 + fi + return ret +} + +(( $+functions[_concourse_fly_input_equal_paths] )) || +_concourse_fly_input_equal_paths() { + local ret=1 + if compset -P '*='; then + _files && ret=0 + else + _concourse_fly_pipeline_config_inputs -qS= && ret=0 + fi + return ret +} + +(( $+functions[_concourse_fly_output_equal_paths] )) || +_concourse_fly_output_equal_paths() { + local ret=1 + if compset -P '*='; then + _files && ret=0 + else + _concourse_fly_pipeline_config_outputs -qS= && ret=0 + fi + return ret +} + +(( $+functions[_concourse_server] )) || +_concourse_server() { + + local context state state_descr line ret=1 + typeset -A opt_args + + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(- : *)'{-v,--version}'[print the version of Concourse and exit]' \ + '(-): :->command' \ + '(-)*:: :->arguments' \ + && ret=0 + + case $state in + (command) + _concourse_commands && ret=0 + ;; + (arguments) + curcontext=${curcontext%:*:*}:concourse-$words[1]: + if (( $+functions[_concourse_${words[1]}_args] )); then + _concourse_${words[1]}_args && ret=0 + else + _message "unknown command ${words[1]}" && ret=1 + fi + ;; + esac + + return ret +} + +(( $+functions[_concourse_commands] )) || +_concourse_commands() { + local commands=( + "generate-key:generate RSA key for use with Concourse components" + "land-worker:safely drain a worker's assignments for temporary downtime" + "migrate:run database migrations" + "quickstart:run both 'web' and 'worker' together, auto-wired" + "retire-worker:safely remove a worker from the cluster permanently" + "web:run the web UI and build scheduler" + "worker:run and register a worker" + ) + _describe -t commands commands commands +} + +(( $+functions[_concourse_generate-key_args] )) || +_concourse_generate-key_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(-t --type)'{-t,--type=}'[the type of key to generate]:key type:(rsa ssh)' \ + '(-f --filename)'{-f,--filename=}'[file path where the key shall be created. When generating ssh keys, the public key will be stored in a file with the same name but with .pub appended]: :_files' \ + '(-b --bits)'{-b,--bits=}'[the number of bits in the key to create]:integer' +} + +(( $+functions[_concourse_land-worker_args] )) || +_concourse_land-worker_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '--name=[the name of the worker you wish to land]:worker name' \ + '*--tsa-host=[TSA host to forward the worker through]: :_concourse_host_colon_ports' \ + '--tsa-public-key=[file containing a public key to expect from the TSA]: :_files' \ + '--tsa-worker-private-key=[file containing a public key to expect from the TSA]: :_files' +} + +(( $+functions[_concourse_migrate_args] )) || +_concourse_migrate_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(- : *)--current-db-version[print the current database version and exit]' \ + '(- : *)--supported-db-version[print the max supported database version and exit]' \ + '(- : *)--migrate-db-to-version=[migrate to the specified database version and exit]:database version' \ + '--encryption-key=[a 16 or 32 length key used to encrypt sensitive information before storing it in the database]:encryption key' \ + '--postgres-host=[the host to connect to]: :_hosts' \ + '--postgres-port=[the port to connect to]: :_concourse_ports' \ + '--postgres-socket=[path to a UNIX domain socket to connect to]: :_files' \ + '--postgres-user=[the user to sign in as]: :_users' \ + '--postgres-password=[the user'\''s password]:password' \ + '--postgres-sslmode=[whether or not to use SSL]:SSL mode:((disable require verify-ca verify-full))' \ + '--postgres-ca-cert=[CA cert file location, to verify when connecting with SSL]: :_files' \ + '--postgres-client-cert=[client cert file location]: :_files' \ + '--postgres-client-key=[client key file location]: :_files' \ + '--postgres-connect-timeout=[dialing timeout]:duration' \ + '--postgres-database=[the name of the database to use]:database name' +} + +(( $+functions[_concourse_retire-worker_args] )) || +_concourse_retire-worker_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '--name=[the name of the worker you wish to retire]:worker name' \ + '*--tsa-host=[TSA host to forward the worker through]: :_concourse_host_colon_ports' \ + '--tsa-public-key=[file containing a public key to expect from the TSA]: :_files' \ + '--tsa-worker-private-key=[file containing a public key to expect from the TSA]: :_files' +} + +(( $+functions[_concourse_web_args] )) || +_concourse_web_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '--peer-address=[network address of this web node, reachable by other web nodes]: :_concourse_host_colon_ports' \ + '--log-level=[minimum level of logs to see]: :_concourse_log_levels' \ + '--bind-ip=[IP address on which to listen for web traffic]: :_concourse_ip_addresses' \ + '--bind-port=[port on which to listen for HTTP traffic]: :_concourse_ports' \ + '--tls-bind-port=[port on which to listen for HTTPS traffic]: :_concourse_ports' \ + '--tls-cert=[file containing an SSL certificate]: :_files' \ + '--tls-key=[file containing an RSA private key, used to encrypt HTTPS traffic]: :_files' \ + '--external-url=[URL used to reach any ATC from the outside world]: :_urls' \ + '--encryption-key=[a 16 or 32 length key used to encrypt sensitive information before storing it in the database]:encryption key' \ + '--old-encryption-key=[encryption key previously used for encrypting sensitive information]:encryption key' \ + '--debug-bind-ip=[IP address on which to listen for the pprof debugger endpoints]: :_concourse_ip_addresses' \ + '--debug-bind-port=[port on which to listen for the pprof debugger endpoints]: :_concourse_ports' \ + '--intercept-idle-timeout=[length of time for a intercepted session to be idle before terminating]: :_concourse_durations' \ + '--enable-global-resources[enable equivalent resources across pipelines and teams to share a single version history]' \ + '--global-resource-check-timeout=[time limit on checking for new versions of resources]: :_concourse_durations' \ + '--resource-checking-interval=[interval on which to check for new versions of resources]: :_concourse_durations' \ + '--resource-type-checking-interval=[interval on which to check for new versions of resource types]: :_concourse_durations' \ + '--container-placement-strategy=[method by which a worker is selected during container placement]:strategy:((volume-locality random fewest-build-containers))' \ + '--baggageclaim-response-header-timeout=[how long to wait for Baggageclaim to send the response header]: :_concourse_durations' \ + '--cli-artifacts-dir=[directory containing downloadable CLI binaries]: :_files -/' \ + '--log-db-queries[log database queries]' \ + '--build-tracker-interval=[interval on which to run build tracking]: :_concourse_durations' \ + '--default-build-logs-to-retain=[default build logs to retain, 0 means all]:number' \ + '--max-build-logs-to-retain=[maximum build logs to retain, 0 means not specified]:number' \ + '--default-days-to-retain-build-logs=[default days to retain build logs. 0 means unlimited]:number' \ + '--max-days-to-retain-build-logs=[maximum days to retain build logs, 0 means not specified]:number' \ + '--default-task-cpu-limit=[default max number of cpu shares per task, 0 means unlimited]:number' \ + '--default-task-memory-limit=[default maximum memory per task, 0 means unlimited]:number' \ + '--enable-build-auditing[enable auditing for all api requests connected to builds]' \ + '--enable-container-auditing[enable auditing for all api requests connected to containers]' \ + '--enable-job-auditing[enable auditing for all api requests connected to jobs]' \ + '--enable-pipeline-auditing[enable auditing for all api requests connected to pipelines]' \ + '--enable-resource-auditing[enable auditing for all api requests connected to resources]' \ + '--enable-system-auditing[enable auditing for all api requests connected to system transactions]' \ + '--enable-team-auditing[enable auditing for all api requests connected to teams]' \ + '--enable-worker-auditing[enable auditing for all api requests connected to workers]' \ + '--enable-volume-auditing[enable auditing for all api requests connected to volumes]' \ + '--postgres-host=[the host to connect to]: :_hosts' \ + '--postgres-port=[the port to connect to]: :_concourse_ports' \ + '--postgres-socket=[path to a UNIX domain socket to connect to]: :_files' \ + '--postgres-user=[the user to sign in as]: :_users' \ + '--postgres-password=[the user'\''s password]:password' \ + '--postgres-sslmode=[whether or not to use SSL]:SSL mode:((disable require verify-ca verify-full))' \ + '--postgres-ca-cert=[CA cert file location, to verify when connecting with SSL]: :_files' \ + '--postgres-client-cert=[client cert file location]: :_files' \ + '--postgres-client-key=[client key file location]: :_files' \ + '--postgres-connect-timeout=[dialing timeout]: :_concourse_durations' \ + '--postgres-database=[the name of the database to use]:database name' \ + '--secret-retry-attempts=[the number of attempts secret will be retried to be fetched, in case a retriable error happens]:number' \ + '--secret-retry-interval=[the interval between secret retry retrieval attempts]: :_concourse_durations' \ + '--secret-cache-enabled[enable in-memory cache for secrets]' \ + '--secret-cache-duration=[if the cache is enabled, secret values will be cached for not longer than this duration]: :_concourse_durations' \ + '--secret-cache-purge-interval=[if the cache is enabled, expired items will be removed on this internal]: :_concourse_durations' \ + '--credhub-url=[CredHub server address used to access secrets]: :_urls' \ + '--credhub-path-prefix=[path under which to namespace credential lookup]:path' \ + '--credhub-ca-cert=[path to PEM-encoded CA cert files to use to verify the CredHub server SSL cert]: :_files' \ + '--credhub-client-cert=[path to the client certificate for mutual TLS authorization]: :_files' \ + '--credhub-client-key=[path to the client private key for mutual TLS authorization]: :_files' \ + '--credhub-insecure-skip-verify[enable insecure SSL verification]' \ + '--credhub-client-id=[client ID for CredHub authorization]:client ID' \ + '--credhub-client-secret=[client secret for CredHub authorization]:client secret' \ + '--kubernetes-in-cluster[enables the in-cluster client]' \ + '--kubernetes-config-path=[path to Kubernetes config when running ATC outside Kubernetes]: :_files' \ + '--kubernetes-namespace-prefix=[prefix to use for Kubernetes namespaces under which secrets will be looked up]:prefex' \ + '--aws-secretsmanager-access-key=[AWS Access key ID]:access key' \ + '--aws-secretsmanager-secret-key=[AWS Secret Access Key]:secret key' \ + '--aws-secretsmanager-session-token=[AWS Session Token]:session token' \ + '--aws-secretsmanager-region=[AWS region to send requests to]:region' \ + '--aws-secretsmanager-pipeline-secret-template=[AWS Secrets Manager secret identifier template used for pipeline specific parameter]:template' \ + '--aws-secretsmanager-team-secret-template=[AWS Secrets Manager secret identifier template used for team specific parameter]:template' \ + '--aws-ssm-access-key=[AWS Access key ID]:access key' \ + '--aws-ssm-secret-key=[AWS Secret Access Key]:secret key' \ + '--aws-ssm-session-token=[AWS Session Token]:session token' \ + '--aws-ssm-region=[AWS region to send requests to]:region' \ + '--aws-ssm-pipeline-secret-template=[AWS SSM parameter name template used for pipeline specific parameter]:template' \ + '--aws-ssm-team-secret-template=[AWS SSM parameter name template used for team specific parameter]:template' \ + '--vault-url=[vault server address used to access secrets]: :_urls' \ + '--vault-path-prefix=[path under which to namespace credential lookup]:prefix' \ + '--vault-shared-path=[path under which to lookup shared credentials]:path' \ + '--vault-ca-cert=[path to a PEM-encoded CA cert file to use to verify the vault server SSL cert]: :_files' \ + '--vault-ca-path=[path to a directory of PEM-encoded CA cert files to verify the vault server SSL cert]: :_files -/' \ + '--vault-client-cert=[path to the client certificate for Vault authorization]: :_files' \ + '--vault-client-key=[path to the client private key for Vault authorization]: :_files' \ + '--vault-server-name=[if set, is used to set the SNI host when connecting via TLS]:server name' \ + '--vault-insecure-skip-verify[enable insecure SSL verification]' \ + '--vault-client-token=[client token for accessing secrets within the Vault server]:client token' \ + '--vault-auth-backend=[auth backend to use for logging in to Vault]:auth backend' \ + '--vault-auth-backend-max-ttl=[time after which to force a re-login]: :_concourse_durations' \ + '--vault-retry-max=[the maximum time between retries when logging in or re-authing a secret]: :_concourse_durations' \ + '--vault-retry-initial=[the initial time between retries when logging in or re-authing a secret]: :_concourse_durations' \ + '*--vault-auth-param=[parameter to pass when logging in via the backend]: :_concourse_name_colon_values' \ + {-n,--noop}'[don'\''t actually do any automatic scheduling or checking]' \ + '--worker-garden-url=[a Garden API endpoint to register as a worker]: :_urls' \ + '--worker-baggageclaim-url=[a Baggageclaim API endpoint to register with the worker]: :_urls' \ + '*--worker-resource=[a resource type to advertise for the worker]: :_concourse_type_colon_images' \ + '--metrics-host-name=[host string to attach to emitted metrics]: :_hosts' \ + '*--metrics-attribute=[a key-value attribute to attach to emitted metrics]: :_concourse_name_colon_values' \ + '--capture-error-metrics[enable capturing of error log metrics]' \ + '--datadog-agent-host=[datadog agent host to expose dogstatsd metrics]: :_hosts' \ + '--datadog-agent-port=[datadog agent port to expose dogstatsd metrics]: :_concourse_ports' \ + '--datadog-prefix=[prefix for all metrics to easily find them in Datadog]:prefix' \ + '--influxdb-url=[influxDB server address to emit points to]: :_urls' \ + '--influxdb-database=[influxDB database to write points to]:database name' \ + '--influxdb-username=[influxDB server username]: :_users' \ + '--influxdb-password=[influxDB server password]:password' \ + '--influxdb-insecure-skip-verify[skip SSL verification when emitting to InfluxDB]' \ + '--emit-to-logs[emit metrics to logs]' \ + '--newrelic-account-id=[new Relic Account ID]:account ID' \ + '--newrelic-api-key=[new Relic Insights API Key]:API key' \ + '--newrelic-service-prefix=[an optional prefix for emitted New Relic events]:prefix' \ + '--prometheus-bind-ip=[IP to listen on to expose Prometheus metrics]: :_concourse_ip_addresses' \ + '--prometheus-bind-port=[port to listen on to expose Prometheus metrics]: :_concourse_ports' \ + '--riemann-host=[riemann server address to emit metrics to]: :_hosts' \ + '--riemann-port=[port of the Riemann server to emit metrics to]: :_concourse_ports' \ + '--riemann-service-prefix=[an optional prefix for emitted Riemann services]:prefix' \ + '*--riemann-tag=[tag to attach to emitted metrics]:tag' \ + '--x-frame-options=[the value to set for X-Frame-Options]:options' \ + '--cluster-name=[a name for this Concourse cluster, to be displayed on the dashboard page]:name' \ + '--gc-interval=[interval on which to perform garbage collection]: :_concourse_durations' \ + '--gc-one-off-grace-period=[period after which one-off build containers will be garbage-collected]: :_concourse_durations' \ + '--gc-missing-grace-period=[period after which to reap containers and volumes that were created but went missing from the worker]: :_concourse_durations' \ + '--syslog-hostname=[client hostname with which the build logs will be sent to the syslog server]: :_hosts' \ + '--syslog-address=[remote syslog server address with port]: :_concourse_host_colon_ports' \ + '--syslog-transport=[transport protocol for syslog messages]:protocol:((tcp udp tls))' \ + '--syslog-drain-interval=[interval over which checking is done for new build logs to send to syslog server]: :_concourse_durations' \ + '--syslog-ca-cert=[paths to PEM-encoded CA cert files to use to verify the Syslog server SSL cert]: :_files' \ + '--cookie-secure[force sending secure flag on http cookies]' \ + '--auth-duration=[length of time for which tokens are valid]: :_concourse_durations' \ + '--session-signing-key=[file containing an RSA private key, used to sign auth tokens]: :_files' \ + '*--add-local-user=[list of username:password combinations for all your local users]: :_concourse_username_colon_passwords' \ + '*--main-team-local-user=[list of whitelisted local concourse users]: :_users' \ + {-c,--main-team-config=}'[configuration file for specifying team params]: :_concourse_config_files' \ + '*--main-team-bitbucket-cloud-user=[list of whitelisted Bitbucket Cloud users]: :_users' \ + '*--main-team-bitbucket-cloud-team=[list of whitelisted Bitbucket Cloud teams]:team' \ + '*--main-team-cf-user=[list of whitelisted CloudFoundry users]: :_users' \ + '*--main-team-cf-org=[list of whitelisted CloudFoundry orgs]:org name' \ + '*--main-team-cf-space=[list of whitelisted CloudFoundry spaces]:space name' \ + '*--main-team-github-user=[list of whitelisted GitHub users]: :_users' \ + '*--main-team-github-org=[list of whitelisted GitHub orgs]:org name' \ + '*--main-team-github-team=[list of whitelisted GitHub teams]:team name' \ + '*--main-team-gitlab-user=[list of whitelisted GitLab users]: :_users' \ + '*--main-team-gitlab-group=[list of whitelisted GitLab groups]:group name' \ + '*--main-team-ldap-user=[list of whitelisted LDAP users]: :_users' \ + '*--main-team-ldap-group=[list of whitelisted LDAP groups]:group name' \ + '*--main-team-oauth-user=[list of whitelisted OAuth2 users]: :_users' \ + '*--main-team-oauth-group=[list of whitelisted OAuth2 groups]:group name' \ + '*--main-team-oidc-user=[list of whitelisted OIDC users]: :_users' \ + '*--main-team-oidc-group=[list of whitelisted OIDC groups]:group name' \ + '--bitbucket-cloud-client-id=[client id]:client ID' \ + '--bitbucket-cloud-client-secret=[client secret]:client secret' \ + '--cf-client-id=[client id]:client ID' \ + '--cf-client-secret=[client secret]:client secret' \ + '--cf-api-url=[the base API URL of your CF deployment]: :_urls' \ + '--cf-ca-cert=[CA Certificate]: :_files' \ + '--cf-skip-ssl-validation[skip SSL validation]' \ + '--github-client-id=[client id]:client ID' \ + '--github-client-secret=[client secret]:client secret' \ + '--github-host=[hostname of GitHub Enterprise deployment]: :_hosts' \ + '--github-ca-cert=[CA certificate of GitHub Enterprise deployment]: :_files' \ + '--gitlab-client-id=[client id]:client ID' \ + '--gitlab-client-secret=[client secret]:client secret' \ + '--gitlab-host=[hostname of Gitlab Enterprise deployment]: :_hosts' \ + '--ldap-display-name=[the auth provider name displayed to users on the login page]:display name' \ + '--ldap-host=[the host and optional port of the LDAP server]: :_hosts' \ + '--ldap-bind-dn=[bind DN for searching LDAP users and groups]:bind DN' \ + '--ldap-bind-pw=[bind Password for the user specified by bind-dn]:bind password' \ + '--ldap-insecure-no-ssl[required if LDAP host does not use TLS]' \ + '--ldap-insecure-skip-verify[skip certificate verification]' \ + '--ldap-start-tls[start on insecure port, then negotiate TLS]' \ + '--ldap-ca-cert=[CA certificate]: :_files' \ + '--ldap-user-search-base-dn= [baseDN to start the search from]:baseDN' \ + '--ldap-user-search-filter=[optional filter to apply when searching the directory]:filter' \ + '--ldap-user-search-username=[attribute to match against the inputted username]:attribute' \ + '--ldap-user-search-scope=[can either be: '\''sub'\'' - search the whole sub tree or '\''one'\'' - only search one level]:scope:((sub one))' \ + '--ldap-user-search-id-attr=[a mapping of attributes on the user entry to claims]:attribute mapping' \ + '--ldap-user-search-email-attr=[a mapping of attributes on the user entry to claims]:attribute mapping' \ + '--ldap-user-search-name-attr=[a mapping of attributes on the user entry to claims]:attribute mapping' \ + '--ldap-group-search-base-dn=[baseDN to start the search from]:baseDN' \ + '--ldap-group-search-filter=[optional filter to apply when searching the directory]:filter' \ + '--ldap-group-search-scope=[can either be: '\''sub'\'' - search the whole sub tree or '\''one'\'' - only search one level]:scope:((sub one))' \ + '--ldap-group-search-user-attr=[adds an additional requirement to the filter that an attribute in the group match the user'\''s attribute value]:attribute' \ + '--ldap-group-search-group-attr=[adds an additional requirement to the filter that an attribute in the group match the user'\''s attribute value]:attribute' \ + '--ldap-group-search-name-attr=[the attribute of the group that represents its name]:attribute' \ + '--oauth-display-name=[the auth provider name displayed to users on the login page]:display name' \ + '--oauth-client-id=[client id]:client ID' \ + '--oauth-client-secret=[client secret]:client secret' \ + '--oauth-auth-url=[Authorization URL]: :_urls' \ + '--oauth-token-url=[Token URL]: :_urls' \ + '--oauth-userinfo-url=[UserInfo URL]: :_urls' \ + '*--oauth-scope=[any additional scopes that need to be requested during authorization]:scope' \ + '--oauth-groups-key=[the groups key indicates which claim to use to map external groups to Concourse teams]:group key' \ + '--oauth-user-id-key=[the user id key indicates which claim to use to map an external user id to a Concourse user id]:id key' \ + '--oauth-user-name-key=[the user name key indicates which claim to use to map an external user name to a Concourse user name]:name key' \ + '--oauth-ca-cert=[CA Certificate]: :_files' \ + '--oauth-skip-ssl-validation[skip SSL validation]' \ + '--oidc-display-name=[the auth provider name displayed to users on the login page]:display name' \ + '--oidc-issuer=[An OIDC issuer URL that will be used to discover provider configuration]: :_urls' \ + '--oidc-client-id=[client id]:client ID' \ + '--oidc-client-secret=[client secret]:client secret' \ + '*--oidc-scope=[any additional scopes that need to be requested during authorization]:scope' \ + '--oidc-groups-key=[the groups key indicates which claim to use to map external groups to Concourse teams]:group key' \ + '--oidc-user-name-key=[the user name key indicates which claim to use to map an external user name to a Concourse user name]:user name key' \ + '*--oidc-hosted-domains=[list of whitelisted domains when using Google, only users from a listed domain will be allowed to log in]:domain' \ + '--oidc-ca-cert=[CA Certificate]: :_files' \ + '--oidc-skip-ssl-validation[skip SSL validation]' \ + '--tsa-log-level=[minimum level of logs to see]: :_concourse_log_levels' \ + '--tsa-bind-ip=[IP address on which to listen for SSH]: :_concourse_ip_addresses' \ + '--tsa-peer-address=[network address of this web node, reachable by other web nodes]: :_urls' \ + '--tsa-bind-port=[port on which to listen for SSH]: :_concourse_ports' \ + '--tsa-debug-bind-ip=[IP address on which to listen for the pprof debugger endpoints]: :_concourse_ip_addresses' \ + '--tsa-debug-bind-port=[port on which to listen for the pprof debugger endpoints]: :_concourse_ports' \ + '--tsa-host-key=[path to private key to use for the SSH server]: :_files' \ + '--tsa-authorized-keys=[path to file containing keys to authorize, in SSH authorized_keys format]: :_files' \ + '--tsa-team-authorized-keys=[path to file containing keys to authorize, in SSH authorized_keys format]: :_concourse_name_colon_paths' \ + '--tsa-atc-url=[ATC API endpoints to which workers will be registered]: :_urls' \ + '--tsa-session-signing-key=[path to private key to use when signing tokens in requests to the ATC during registration]: :_files' \ + '--tsa-heartbeat-interval=[interval on which to heartbeat workers to the ATC]: :_concourse_durations' \ +} + +(( $+functions[_concourse_worker_args] )) || +_concourse_worker_args() { + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '--name=[the name to set for the worker during registration]:name' \ + '*--tag=[a tag to set during registration]:tag' \ + '--team=[the name of the team that this worker will be assigned to]:team name' \ + '--http-proxy=[HTTP proxy endpoint to use for containers]: :_urls' \ + '--https-proxy=[HTTPS proxy endpoint to use for containers]: :_urls' \ + '*--no-proxy=[blacklist of addresses to skip the proxy when reaching]: :_urls' \ + '--ephemeral[if set, the worker will be immediately removed upon stalling]' \ + '--certs-dir=[directory to use when creating the resource certificates volume]: :_files -/' \ + '--work-dir=[directory in which to place container data]: :_files -/' \ + '--bind-ip=[IP address on which to listen for the Garden server]: :_concourse_ip_addresses' \ + '--bind-port=[port on which to listen for the Garden server]: :_concourse_ports' \ + '--debug-bind-ip=[IP address on which to listen for the pprof debugger endpoints]: :_concourse_ip_addresses' \ + '--debug-bind-port=[port on which to listen for the pprof debugger endpoints]: :_concourse_ports' \ + '--healthcheck-bind-ip=[IP address on which to listen for health checking requests]: :_concourse_ip_addresses' \ + '--healthcheck-bind-port=[port on which to listen for health checking requests]: :_concourse_ports' \ + '--healthcheck-timeout=[HTTP timeout for the full duration of health checking]: :_concourse_durations' \ + '--sweep-interval=[interval on which containers and volumes will be garbage collected from the worker]: :_concourse_durations' \ + '--volume-sweeper-max-in-flight=[maximum number of volumes which can be swept in parallel]:number' \ + '--container-sweeper-max-in-flight=[maximum number of containers which can be swept in parallel]:number' \ + '--rebalance-interval=[duration after which the registration should be swapped to another random SSH gateway]: :_concourse_durations' \ + '--connection-drain-timeout=[duration after which a worker should give up draining forwarded connections on shutdown]: :_concourse_durations' \ + '--external-garden-url=[API endpoint of an externally managed Garden server to use instead of running the embedded Garden server]: :_urls' \ + '--resource-types=[path to directory containing resource types the worker should advertise]: :_files -/' \ + '--log-level=[minimum level of logs to see]: :_concourse_log_levels' \ + '*--tsa-host=[TSA host to forward the worker through]: :_hosts' \ + '--tsa-public-key=[file containing a public key to expect from the TSA]: :_files' \ + '--tsa-worker-private-key=[file containing the private key to use when authenticating to the TSA]: :_files' \ + '--garden-use-houdini[use the insecure Houdini Garden backend]' \ + '--garden-bin=[path to gdn executable (or leave as gdn to find it in $PATH)]: :_files' \ + '--garden-config=[path to a config file to use for Garden]: :_files' \ + '--garden-dns-proxy-enable[enable proxy DNS server]' \ + '--baggageclaim-log-level=[minimum level of logs to see]: :_concourse_log_levels' \ + '--baggageclaim-bind-ip=[IP address on which to listen for API traffic]: :_concourse_ip_addresses' \ + '--baggageclaim-bind-port=[port on which to listen for API traffic]: :_concourse_ports' \ + '--baggageclaim-debug-bind-ip=[IP address on which to listen for the pprof debugger endpoints]: :_concourse_ip_addresses' \ + '--baggageclaim-debug-bind-port=[port on which to listen for the pprof debugger endpoints]: :_concourse_ports' \ + '--baggageclaim-volumes=[directory in which to place volume data]: :_files -/' \ + '--baggageclaim-driver=[driver to use for managing volumes]:driver:((detect naive btrfs overlay))' \ + '--baggageclaim-btrfs-bin=[path to btrfs binary]: :_files' \ + '--baggageclaim-mkfs-bin=[path to mkfs.btrfs binary]: :_files' \ + '--baggageclaim-overlays-dir=[path to directory in which to store overlay data]: :_files -/' \ + '--baggageclaim-disable-user-namespaces[disable remapping of user/group IDs in unprivileged volumes]' +} + +(( $+functions[_concourse_config_files] )) || +_concourse_config_files() { + _files -g "*.(yml|yaml)" +} + +(( $+functions[_concourse_ip_addresses] )) || +_concourse_ip_addresses() { + _message 'IP address' +} + +(( $+functions[_concourse_ports] )) || +_concourse_ports() { + _message 'port number' +} + +(( $+functions[_concourse_host_colon_ports] )) || +_concourse_host_colon_ports() { + local ret=1 + if compset -P '*:'; then + _concourse_ports && ret=0 + else + _alternative \ + 'hosts: :_hosts -qS:' \ + 'ip-addresses: :_guard "[[:digit:]]*" "IP address"' \ + && ret=0 + fi + return ret +} + +(( $+functions[_concourse_type_colon_images] )) || +_concourse_type_colon_images() { + local ret=1 + if compset -P '*:'; then + _message 'type' && ret=0 + else + _message 'image' && ret=0 + fi + return ret +} + +(( $+functions[_concourse_name_colon_values] )) || +_concourse_name_colon_values() { + local ret=1 + if compset -P '*:'; then + _message 'name' && ret=0 + else + _message 'value' && ret=0 + fi + return ret +} + +(( $+functions[_concourse_username_colon_passwords] )) || +_concourse_username_colon_passwords() { + local ret=1 + if compset -P '*:'; then + _message 'username' && ret=0 + else + _message 'password' && ret=0 + fi + return ret +} + +(( $+functions[_concourse_name_colon_paths] )) || +_concourse_name_colon_paths() { + local ret=1 + if compset -P '*:'; then + _message 'name' && ret=0 + else + _files && ret=0 + fi + return ret +} + +(( $+functions[_concourse_durations] )) || +_concourse_durations() { + _message 'duration, eg: "5s", "5m", "5h", "5d"' +} + +(( $+functions[_concourse_log_levels] )) || +_concourse_log_levels() { + local levels=( + 'debug:debug traces' + 'info:normal log level' + 'error:log only errors' + 'fatal:log only fatal errors' + ) + _describe -t log-levels 'log level' levels +} + +case $service in + concourse) _concourse_server "$@" ;; + fly) _concourse_fly "$@" ;; + *) _message "unknown command ${service}" && ret=1 ;; +esac + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_console b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_console new file mode 100644 index 00000000..2d11e43e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_console @@ -0,0 +1,64 @@ +#compdef console +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for symfony console (https://github.com/symfony/Console). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * loranger (https://github.com/loranger) +# * Yohan Tambè (https://github.com/Cronos87) +# +# ------------------------------------------------------------------------------ + +_find_console () { + echo "php $(find . -maxdepth 2 -mindepth 1 -name 'console' -type f | head -n 1)" +} + +_console_get_command_list () { + IFS=" " + `_find_console` --no-ansi | \ + sed "1,/Available commands/d" | \ + awk '/ [a-z]+/ { print $0 }' | \ + sed -E 's/^[ ]+//g' | \ + sed -E 's/[:]+/\\:/g' | \ + sed -E 's/[ ]{2,}/\:/g' +} + +_console () { + local -a commands + IFS=$'\n' + commands=(`_console_get_command_list`) + _describe 'commands' commands +} + +compdef _console php console +compdef _console console diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cppcheck b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cppcheck new file mode 100644 index 00000000..e8ab3fee --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_cppcheck @@ -0,0 +1,119 @@ +#compdef cppcheck +# ------------------------------------------------------------------------------ +# Copyright (c) 2019 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for cppcheck -- a tool for static C/C++ code analysis (https://cppcheck.sourceforge.io/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Georgy Komarov (https://github.com/jubnzv) +# +# ------------------------------------------------------------------------------ +# Notes +# ----- +# +# Created for Cppcheck version 2.12 (https://github.com/danmar/cppcheck) +# +# ------------------------------------------------------------------------------ + +_cppcheck_files() { + _path_files -/ -g "*.(c|cpp|cxx|h|hpp|C)" +} + +_cppcheck() { + local curcontext="$curcontext" state line + typeset -A opt_args + + local check_ids='(all warning style performance portability information unusedFunction missingInclude)' + + _arguments -C \ + "--addon=[Execute addon]" \ + "--addon-python=[Specify the python interpreter]: :_files" \ + "--cppcheck-build-dir=[Analysis output directory]:directory:_files -/" \ + "--check-config[Check cppcheck configuration]" \ + "--check-library[Show information when library files have incomplete info]" \ + "--clang=[Use clang parser instead of the builtin Cppcheck parser]: :_files" \ + "--config-exclude=[Path to be excluded from configuration checking]:directory:_files -/" \ + "--config-exclude-files=[A file that contains a list of config-excludes]:file:_files" \ + "--doc[Print a list of all available checks]" \ + "*--disable=[Disable indivisual checks]:id:$check_ids" \ + "--dump[Dump xml data for each translation unit]" \ + "-D[Define preprocessor symbol]" \ + "-U[Undefine preprocessor symbol]" \ + "-E[Print preprocessor output on stdout and don't do any further processing]" \ + "--enable=[Enable additional checks]:id:$check_ids" \ + "--error-exitcode=[Integer to return if errors are found]" \ + "--errorlist[Print a list of all the error messages in XML format]" \ + "--exitcode-suppressions=[Used when certain messages should be displayed but should not cause a non-zero exitcode]:_files" \ + "*--file-filter=[Analyze only those files matching the given filter str]:filter" \ + "--file-list=[Specify the files to check in a text file]:_files" \ + '(-f --force)'{-f,--force}"[Force checking of all configurations in files]" \ + '(- 1 *)'{-h,--help}"[Print this help]" \ + "-I[A file that contains a list of config-excludes]:directory:_files -/" \ + "--include-file=[Specify directory paths to search for included header files in a text file]:file:_files" \ + "--include=[Force inclusion of a file before the checked file]:file:_files" \ + "-i[Give a source file or source file directory to exclude from the check]:directory or file:_files" \ + "--inconclusive[Report even though the analysis is inconclusive]" \ + "--inline-suppr[Enable inline suppressions]" \ + "-j[Number of threads to do the checking simultaneously]::num" \ + "-l[No new threads should be started if the load average is exceeds this value]::load_avg" \ + {-x,--language=}"[Forces cppcheck to check all files as the given language]:language:(c c++)" \ + "--max-configs=[Maximum number of configurations to check in a file]" \ + "--max-ctu-depth=[Maximum depth in whole program analysis]:num" \ + "--output-file=[File to save results]:file:_files" \ + "--plist-output=[Generate Clang-plist output files in folder]:_files" \ + "--project=[Run Cppcheck on project]:file:_files" \ + "--project-configuration=[Limit the configuration cppcheck should check]:configuration" \ + "--platform=[Set platform specific types and sizes]:platforms:(unix32 unix64 win32A win32W win64 avr8 elbrus-e1cp pic8 pic8-enhanced pic16 mips32 native unspecified)" \ + '(-q --quiet)'{-q,--quiet}"[Do not show progress reports]" \ + {-rp,--relative-paths}"=[Use relative paths in output (separated with ;)]:_files" \ + "--report-progress[Report progress messages while checking a file]" \ + "--std=[Set standard]:std:(c89 c99 c11 c++03 c++11 c++14 c++17 c++20)" \ + "--suppress=[Suppress warnings (format: \[error id\]:\[filename\]:\[line\])]" \ + "--suppressions-list=[Suppress warnings listed in the file]:_files" \ + "--suppress-xml=[Suppress warnings listed in a xml file]:_files" \ + "--template=[Format the error messages]" \ + "--template-location=[Format the error message location]" \ + "(-v --verbose)"{-v,--verbose}"[Output more detailed error information]" \ + "--version[Print out version number]" \ + "--xml[Write results in xml format to stderr]" \ + '*: :_cppcheck_files' +} + +_cppcheck "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_dad b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_dad new file mode 100644 index 00000000..40d523cd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_dad @@ -0,0 +1,68 @@ +#compdef dad +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for dad a command line manager of aria2 daemon. (https://github.com/baskerville/diana). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Jindřich Pilař (https://github.com/JindrichPilar) +# +# ------------------------------------------------------------------------------ + +_dad() { + local -a commands + + commands=( + "start:Start aria2c daemon" + "stop:Stop aria2c daemon" + ) + + _arguments -C \ + '(- 1 *)'-h"[Show help and exit]" \ + "-d[Set download dir]:download_dir:->val" \ + "-s[Set secret token]:secret_token:->val" \ + "-u[Set aria2c username]:username:->val" \ + "-p[Set aria2c password]:password:->val" \ + '1:cmd:->cmds' \ + '*: : :->args' \ + + case "$state" in + (cmds) + _describe -t commands 'commands' commands + ;; + (*) + ;; + esac +} + +_dad + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_dart b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_dart new file mode 100644 index 00000000..fc82690e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_dart @@ -0,0 +1,584 @@ +#compdef dart +# ------------------------------------------------------------------------------ +# Copyright (c) 2023 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for dart 3.1.0 (https://dart.dev/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_dart() { + typeset -A opt_args + local context state line + local curcontext="$curcontext" + local ret=1 + + _arguments -C -A "-*" \ + '(-v --verbose)'{-v,--verbose}'[Show additional command output]' \ + '(- *)--version[Print the Dart SDK version]' \ + '(--enable-analytics --disable-analytics --suppress-analytics)--enable-analytics[Enable analytics]' \ + '(--enable-analytics --disable-analytics --suppress-analytics)--disable-analytics[Disable analytics]' \ + '(--enable-analytics --disable-analytics --suppress-analytics)--suppress-analytics[Disapply analytics for this "dart *" run without changing the analytics configuration]' \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_dart_subcommands' \ + '*::arg:->args' \ + && ret=0 + + case "$state" in + (args) + case $words[1] in + (help) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_dart_subcommands' \ + && ret=0 + ;; + (analyze) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--fatal-infos[Treat info level issues as fatal]' \ + '(--no-fatal-warnings --fatal-warnings)--fatal-warnings[Treat warnings level issue as fatal]' \ + '(--no-fatal-warnings --fatal-warnings)--no-fatal-warnings[Do not treat warnings level issue as fatal]' \ + '*: :_files -/' \ + && ret=0 + ;; + (compile) + _dart_compile && ret=0 + ;; + (create) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-t --template)'{-t,--template}'[The project template to use]:template:(console package server-shelf web)' \ + '(--no-pub --pub)--pub[Run "pub get" after the project has been created]' \ + '(--no-pub --pub)--no-pub[Do not run "pub get" after the project has been created]' \ + '--force[Force project generation even if the target directory already exists]' \ + '*: :_files -/' \ + && ret=0 + ;; + (devtools) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(- *)--version[Prints the DevTools version]' \ + '--host=[Hostname to serve DevTools on(defaults to localhost)]:host' \ + '--port=[Port to serve DevTools on, specify 0 to automatically use any available port(defaults to 9100)]:port' \ + '(--no-launch-browser --launch-browser)--launch-browser[Launches DevTools in a browser immediately at start]' \ + '(--no-launch-browser --launch-browser)--no-launch-browser[Do not launches DevTools in a browser immediately at start]' \ + '--machine[Sets output format to JSON for consumption in tools]' \ + '--record-memory-profile=[Start devtools headlessly and write memory profiling samples to the indicated file]:file:_files' \ + '--app-size-base=[Path to the base app size file used for app size]' \ + '*:server_uri :' \ + && ret=0 + ;; + (doc) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-o --output)'{-o,--output=}'[Configuration the output directory(defaults to "doc/api")]:dir:_files -/' \ + '(--dry-run)--validate-links[Display warnings for broken links]' \ + '(--validate-links)--dry-run[Try to generate the docs without saving them]' \ + '*:dir:_files -/' \ + && ret=0 + ;; + (fix) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-n --dry-run)'{-n,--dry-run}'[Preview the proposed changes but make no changes]' \ + '--apply[Apply the proposed changes]' \ + '--code=[Apply fixes for one or more diagnostics codes]:codes' \ + '*: :_files' \ + && ret=0 + ;; + (format) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-v --verbose)'{-v,--verbose}'[Show all options and flags with --help]' \ + '(-o --output)'{-o,--output}'[Set where to write formatted output]:format:_dart_format_output' \ + '--set-exit-if-changed[Return exit code 1 if there are any formatting changes]' \ + '*:file_or_directory:_files' \ + && ret=0 + ;; + (info) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(--no-remove-file-paths --remove-file-paths)--remove-file-paths[Remove file paths in displayed information]' \ + '(--no-remove-file-paths --remove-file-paths)--no-remove-file-paths[Do not remove file paths in displayed information]' \ + '*: :_files' \ + && ret=0 + ;; + (pub) + _dart_pub && ret=0 + ;; + (run) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-r --resident)'{-r,--resident}'[Enable faster startup times with the resident frontend compiler]' \ + '--observe=[Specify debug port and bind address]:port_address' \ + '--enable-vm-service=[Enable the VM service and listens on the specified port for connections(default port 8181)]:port_address' \ + '(--serve-devtools --no-serve-devtools)--serve-devtools[Serves an instance of the Dart DevTools debugger and profiler]' \ + '(--serve-devtools --no-serve-devtools)--no-serve-devtools[Do not serve an instance of the Dart DevTools debugger and profiler]' \ + '--pause-isolates-on-exit[Pause isolates on exit when running with --enable-vm-service]' \ + '--pause-isolates-on-unhandled-exceptions[Pause isolates when an unhandled exception is encountered when running with --enable-vm-service]' \ + '--warn-on-pause-with-no-debugger[Print a warning when an isolate pauses with no attached debugger when runnin with --enable-vm-service]' \ + '--timeline-streams=[Enables recording for specific timeline streams]:stream:_dart_run_timeline_streams' \ + '--pause-isolates-on-start[Pause isolates on start when running with --enable-vm-service]' \ + '(--enable-asserts --no-enable-asserts)--enable-asserts[Enable assert statements]' \ + '(--enable-asserts --no-enable-asserts)--no-enable-asserts[Do not enable assert statements]' \ + '--timeline-recorder=[Selects the timeline recorder to use]:recorder:(none ring endless startup systrace file callback)' \ + '--verbosity[Sets the verbosity level of the compilation]:level:(all error info warning)' \ + '*'{-d,--define=}'[Define an environment declaration]:key_value:' \ + '*: :_files' \ + && ret=0 + ;; + (test) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(- *)--version[Show the package:test version]' \ + '*'{-n,--name}'[A substring of the name of the test to run]:name' \ + '*'{-N,--plain-name}'[A plain-text substring of the name of the test to run]:plain_name' \ + '*'{-t,--tags}'[Run only tests with all of the specified tags]:tag' \ + '*'{-x,--exclude-tags}'[Do not run tests with any of the specified tags]:tag' \ + '(-p --platform)'{-p,--platform}'[The platform on which to run the tests]:platform:(vm chrome firefox edge node experimental-chrome-wasm)' \ + '(-c --compiler)'{-c,--compiler}'[The compiler to use to run tests]:compiler:(dart2js dart2wasm exe kernel source)' \ + '(-P --preset)'{-P,--preset}'[The configuration preset to use]:preset' \ + '(-j --concurrency)'{-j,--concurrency}'[The number of concurrent test suites run(defaults to 1)]:concurrency' \ + '--total-shards[The total number of invocations of the test runner being run]:number' \ + '--shard-index[The index of this test runner invocation]:index' \ + '--pub-serve=[The port of a pub serve instance serving "test/"]:port' \ + '(--ignore-timeouts --timeout)--timeout[The default test timeout]:timeout' \ + '(--ignore-timeouts --timeout)--ignore-timeouts[Ignore all timeouts]' \ + '--pause-after-load[Pause for debugging before any tests execute]' \ + '--debug[Run the VM and Chrome tests in debug mode]' \ + '--coverage=[Gather coverage and output it to the specified directory]:dir:_files -/' \ + '(--no-chain-stack-traces --chain-stack-traces)--chain-stack-traces[Use chained stack traces to provide greater exception]' \ + '(--no-chain-stack-traces --chain-stack-traces)--no-chain-stack-traces[Do not use chained stack traces to provide greater exception]' \ + '--no-retry[Do not rerun tests that have retry set]' \ + '--test-randomize-ordering-seed[Use the specified seed to randomize the execution order of test cases]:seed' \ + '(-r --reporter)'{-r,--reporter=}'[Set how to print test results]:reporter:_dart_test_reporter' \ + '--file-reporter[Enable an additional reporter writing test results to a file]:reporter_file' \ + '--verbose-trace[Emit stack traces with core library frames]' \ + '--js-trace[Emit raw JavaScript stack traces for browser tests]' \ + '(--color --no-color)--color[Use terminal colors]' \ + '(--color --no-color)--no-color[Do not use terminal colors]' \ + '*: :_files' \ + && ret=0 + ;; + esac + ;; + esac + + return ret +} + +(( $+functions[_dart_compile] )) || +_dart_compile() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_dart_compile_subcommands' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + local -a opts=( + '(- *)'{-h,--help}'[Print this usage information]' + '(-o --output)'{-o,--output}'[Write the output to file]:output:_files' + ) + + case $words[1] in + (aot-snapshot|exe|jit-snapshot|kernel) + opts+=( + '--verbosity[Sets the verbosity level of the compilation]:level:(all error info warning)' + '*'{-d,--define=}'[Define an environment declaration]:key_value:' + '(-p --packages)'{-p,--packages=}'[Get package locations from the specified file instead of .dart_tool/package_config.json]:config:_files' + ) + ;| + (aot-snapshot|exe) + opts+=( + '(-S --save-debugging-info)'{-S,--save-debugging-info=}'[Remove debugging information from the output and save it separately to the specified file]:file:_files' + '--target-os[Compile to a specific target operating system]:os:(android fuchsia ios linux macos windows)' + ) + ;| + (aot-snapshot) + opts+=( + '--enable-asserts[Enable assert statements]' + ) + ;; + (js) + opts+=( + '-O-[Set the compiler optimization level(defaults to -O1)]:level:(0 1 2 3 4)' + ) + ;; + esac + + opts+=('*:entry_point:_files') + + _arguments "$opts[@]" && ret=0 + ;; + esac + + return $ret +} + +(( $+functions[_dart_compile_subcommands] )) || +_dart_compile_subcommands() { + local -a commands=( + "aot-snapshot:Compile Dart to an AOT snapshot" + "exe:Compile Dart to a self-contained executable" + "jit-snapshot:Compile Dart to a JIT snapshot" + "js:Compile Dart to JavaScript" + "kernel:Compile Dart to a kernel snapshot" + ) + _describe -t commands 'command' commands "$@" +} + +(( $+functions[_dart_format_output] )) || +_dart_format_output() { + local -a outputs=( + "json:Print code and selection as JSON" + "none:Discard output" + "show:Print code to terminal" + "write:Overwrite formatted files on disk(default)" + ) + _describe -t outputs 'output' outputs "$@" +} + +(( $+functions[_dart_pub] )) || +_dart_pub() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-v --verbose)'{-v,--verbose}'[Print detailed logging]' \ + '(--color --no-color)--color[Use colors in terminal output]' \ + '(--color --no-color)--no-color[Do not use colors in terminal output]' \ + '(-C --directory)'{-d,--directory=}'[Run the subcommand in the directory]:dir:_files -/'\ + '1: :_dart_pub_subcommands' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + local -a opts=( + '(- *)'{-h,--help}'[Print this usage information]' + ) + + case $words[1] in + (add|downgrade|get|publish|remove|upgrade) + opts+=( + '(- *)'{-h,--help}'[Print this usage information]' + '(-n --dry-run)'{-n,--dry-run}'[Report what dependencies would change but do not change any]' + '(-C --directory)'{-C,--directory=}'[Run this in the directory]:dir:_files -/' + '*: :_files' + ) + ;| + (add|downgrade|get|upgrade) + opts+=( + '--offline[Use cached packages instead of accessing the network]' + ) + ;| + (add|get|remove|upgrade) + opts+=( + '--precompile[Build executables in immediate dependencies]' + ) + ;| + (get) + opts+=( + '--enforce-lockfile[Enforce pubspec.lock]' + ) + ;| + (publish) + opts+=( + '(-f --force)'{-f,--force}'[Publish without confirmation if there are no errors]' + ) + ;| + (upgrade) + opts+=( + '--major-versions[Upgrades packages to their latest resolvable versions and updates pubspec.yaml]' + ) + ;| + (cache) + _dart_pub_cache && return 0 + return 1 + ;; + (deps) + opts+=( + '(-s --style)'{-s,--style}'[How output should be displayed]:style:(compact tree list)' + '(--dev --no-dev)--dev[Include dev dependencies]' + '(--dev --no-dev)--no-dev[Do not include dev dependencies]' + '--executables[List all available executables]' + '--json[Output dependency information in a json format]' + '(-C --directory)'{-C,--directory=}'[Run this in the directory]:dir:_files -/' + ) + ;; + (global) + _dart_pub_global && return 0 + return 1 + ;; + (outdated) + opts+=( + '(--no-dependency-overrides --dependency-overrides)--dependency-overrides[Show resolutions with "dependency_overrides"]' + '(--no-dependency-overrides --dependency-overrides)--no-dependency-overrides[Do not show resolutions with "dependency_overrides"]' + '(--no-dev-dependencies --dev-dependencies)--dev-dependencies[Take dev dependencies into account]' + '(--no-dev-dependencies --dev-dependencies)--no-dev-dependencies[Do not take dev dependencies into account]' + '--json[Output the results using a json format]' + '(--no-prereleased --prereleases)--prereleases[Include prereleases in latest version]' + '(--no-prereleased --prereleases)--no-prereleases[Do not include prereleases in latest version]' + '(--no-show-all --show-all)--show-all[Include dependencies that are already fulfilling --mode]' + '(--no-show-all --show-all)--no-show-all[Do not include dependencies that are already fulfilling --mode]' + '(--no-transitive --transitive)--transitive[Show transitive dependencies]' + '(--no-transitive --transitive)--no-transitive[Do not show transitive dependencies]' + '(-C --directory)'{-C,--directory=}'[Run this in the directory]:dir:_files -/' ) + ;; + (token) + _dart_pub_token && return 0 + return 1 + ;; + esac + + _arguments "$opts[@]" && ret=0 + ;; + esac + + return $ret +} + +(( $+functions[_dart_pub_subcommands] )) || +_dart_pub_subcommands() { + local -a commands=( + "add:Add dependencies to 'pubspec.yaml'" + "cache:Work with the system cache" + "deps:Print package dependencies" + "downgrade:Downgrade the current package's dependencies to oldest versions" + "get:Get the current package's dependencies" + "global:Work with global packages" + "login:Log into pub.dev" + "logout:Log out of pub.dev" + "outdated:Analyze your dependencies to find which ones can be upgraded" + "publish:Publish the current package to pub.dev" + "remove:Removes dependencies from 'pubspec.yaml'" + "token:Manage authentication tokens for hosted pub repositories" + "upgrade:Upgrade the current package's dependencies to latest versions" + ) + _describe -t commands 'command' commands "$@" +} + +(( $+functions[_dart_pub_cache] )) || +_dart_pub_cache() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_dart_pub_cache_subcommands' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + local -a opts=( + '(- *)'{-h,--help}'[Print this usage information]' + '*: :_files' + ) + case $words[1] in + (add) + opts+=( + '--all[Install all matching versions]' + '(-v --version)'{-v,--version}'[Version constraint]:version' + ) + ;; + (clean) + opts+=( + '(-f --force)'{-f,--force}'[Do not ask for confirmation]' + ) + ;; + esac + + _arguments "$opts[@]" && ret=0 + ;; + esac + + return $ret +} + +(( $+functions[_dart_pub_cache_subcommands] )) || +_dart_pub_cache_subcommands() { + local -a commands=( + "add:Install a package" + "clean:Clears the global PUB_CACHE" + "repair:Reinstall cached packages" + ) + _describe -t commands 'command' commands "$@" +} + +(( $+functions[_dart_pub_global] )) || +_dart_pub_global() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_dart_pub_global_subcommands' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + local -a opts=( + '(- *)'{-h,--help}'[Print this usage information]' + '*: :_files' + ) + case $words[1] in + (activate) + opts+=( + '(-s --source)'{-s,--source}'[The source used to find the package]:source' + '--git-path[Path of git package in repository]:git_path' + '--git-ref[Git branch or commit to be retrieved]:git_ref' + '(-x --executable --noexecutables)--no-executables[Do not put executables on PATH]' + '(-x --executable --noexecutables)'{-x,--executable}'[Executable to place on PATH]' + '--overwrite[Overwrite executables from other packages with the same name]' + '(-u --hosted-url)'{-u,--hosted-url}'[A custom pub server URL for the package]:server' + ) + ;; + (run) + opts+=( + '(--enable-asserts --no-enable-asserts)--enable-asserts[Enable assert statements]' + '(--enable-asserts --no-enable-asserts)--no-enable-asserts[Do not enable assert statements]' + '*--enable-experiment=[Runs the executable in a VM with the given experiments enabled]' + ) + ;; + esac + + _arguments "$opts[@]" && ret=0 + ;; + esac + + return $ret +} + +(( $+functions[_dart_pub_global_subcommands] )) || +_dart_pub_global_subcommands() { + local -a commands=( + "activate:Make a package's executables globally available" + "deactivate:Remove a previously activated package" + "list:List globally activated packages" + "run:Run an executable from a globally activated package" + ) + _describe -t commands 'command' commands "$@" +} + +(( $+functions[_dart_pub_token] )) || +_dart_pub_token() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_dart_pub_token_subcommands' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + local -a opts=( + '(- *)'{-h,--help}'[Print this usage information]' + '*: :_files' + ) + case $words[1] in + (add) + opts+=( + '--env-var=[Read the secret token from this environment variable]:envvar' + ) + ;; + (remove) + opts+=( + '--all[Remove all secret tokens]' + ) + ;; + esac + + _arguments "$opts[@]" && ret=0 + ;; + esac + + return $ret +} + +(( $+functions[_dart_pub_token_subcommands] )) || +_dart_pub_token_subcommands() { + local -a commands=( + "add:Add an authentication token for a package repository" + "list:List servers for which a token exists" + "remove:Remove secret token for package repository at hosted-url" + ) + _describe -t commands 'command' commands "$@" +} + +(( $+functions[_dart_run_timeline_streams] )) || +_dart_run_timeline_streams() { + local -a streams=(all API Compiler CompilerVerbose Dart Debugger Embedder GC Isolate VM) + _values -s ',' streams $streams +} + +(( $+functions[_dart_test_reporter] )) || +_dart_test_reporter() { + local -a reporters=( + "compact:A single line, updated continuously" + "expanded:A separate line for each update" + "github:A custom reporter for GitHub Actions" + "json:A machine-readable format" + ) + _describe -t reporters 'reporter' reporters "$@" +} + +(( $+functions[_dart_subcommands] )) || +_dart_subcommands() { + local -a commands=( + "analyze:Analyze Dart code in a directory" + "compile:Compile Dart to various formats" + "create:Create a new Dart project" + "devtools:Open DevTools (optionally connecting to an existing application)" + "doc:Generate API documentation for Dart projects" + "fix:Apply automated fixes to Dart source code" + "format:Idiomatically format Dart source code" + "info:Show diagnostic information about the installed tooling" + "pub:Work with packages" + "run:Run a Dart program" + "test:Run tests for a project" + ) + _describe -t commands 'command' commands "$@" +} + +_dart "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_dget b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_dget new file mode 100644 index 00000000..4a507d01 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_dget @@ -0,0 +1,71 @@ +#compdef dget +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for dget 2.22.2 +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Kris Shannon +# * Shohei YOSHIDA +# +# ------------------------------------------------------------------------------ + +_dget() { + local context state line expl + local -A opt_args + + _arguments -A "-*" \ + '(- *)'{-h,--help}'[Show help message]' \ + '(- *)'{-v,--version}'[Print license, copyright, and version information and exit]' \ + '(-a --all)'{-a,--all}'[Package is a source package; download all binary packages]' \ + '(--no-conf -b --backup)'{-b,--backup}'[Move files that would be overwritten to ./backup]' \ + '(--no-conf -q --quiet)'{-q,--quiet}'[Suppress wget/curl output]' \ + '(--no-conf -x --extract -d --download-only --build)'{-d,--download-only}'[Do not extract downloaded source]' \ + '(--no-conf -x --extract -d --download-only --build)'{-x,--extract}'[Unpack downloaded source]' \ + '(--no-conf -u --allow-unauthenticated)'{-u,--allow-unauthenticated}'[Make no attempt to verify source package signature]' \ + '(--no-conf -x --extract -d --download-only --build)--build[Build package with dpkg-buildpackage after download]' \ + '(--no-conf)--path[Check this directory in addition to the apt archive]:DIR:_files -/' \ + '(--no-conf --insecure)--insecure[Do not check SSL certificates when downloading]' \ + '(--no-conf --no-cache)--no-cache[Disable server-side HTTP cache]' \ + "(--no-conf)--no-conf[Don't read devscripts config files]" \ + '(-)*:debian package or URL: _alternative "_deb_packages available" "_urls"' +} + +_dget "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_dhcpcd b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_dhcpcd new file mode 100644 index 00000000..0e6d2631 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_dhcpcd @@ -0,0 +1,59 @@ +#compdef dhcpcd +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for dhcpcd 9.4.1 (http://roy.marples.name/projects/dhcpcd/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# +# ------------------------------------------------------------------------------ + +_arguments \ + '(-b --background)'{-b,--background}'[Background immediately]' \ + '(-c --script)'{-c,--script}'[Use this script instead of the default]: :_files' \ + '(-D --duid)'{-d,--duid}'[Use a DHCP Unique Identifier]:id' \ + '(-d --debug)'{-d,--debug}'[Echo debug messages to the stderr and syslog]' \ + '(-E --lastlease)'{-E,--lastlease}'[If dhcpcd cannot obtain a lease, then try to use the last lease acquired for the interface]' \ + '--lastleaseextend[Same as the -E/--lastlease, but the lease will be retained even if it expires]' \ + \*{-e,--env}'[Push value to the environment for use in dhcpcd-run-hooks(8)]:env' \ + '(-g --reconfigure)'{-g,--reconfigure}'[dhcpcd will re-apply IP address, routing and run dhcpcd-run-hooks(8) for each interface]' \ + '(-F --fqdn)'{-F,--fqdn}'[Requests that the DHCP server updates DNS using FQDN instead of just a hostname]:fqdn' \ + '(-f --config)'{-f,--config}'[Specify a config to load instead of default]: :_files' \ + '(-h --hostname)'{-h,--hostname}'[Sends hostname to the DHCP server so it can be registered in DNS]:hostname' \ + '(-I --clientid)'{-I,--clientid}'[Send the clientid]:clientid' \ + '(-i --vendorclassid)'{-i,--vendorclassid}'[Override the DHCPv4 venderclassid field sent]:vendorclassid' \ + '(-j --logfile)'{-j,--logfile}'[Writes to the specified logfile]: :_files' \ + \*{-k,--release}'[Release its lease and de-configure the interface regardless of -p, --persistent option]: :_net_interfaces' \ + '(-l --leasetime)'{-l,--leasetime}'[Request a lease time of seconds. -1 represents an infinite lease time]:seconds' \ + '(-M --manager)'{-M,--manager}'[Start dhcpcd in Manager mode even if only one interface specified on the command line]' \ + '(-m --metric)'{-m,--metric}'[Metrics are used to prefer an interface over another one, lowest wins]:metric' \ + \*{-n,--rebind}'[Notifies dhcpcd to reload its configuration and rebind the specified interface]: :_net_interfaces' \ + \*{-N,--renew}'[Notifies dhcpcd to renew existing addresses on the specified interface]: :_net_interfaces' \ + \*{-o,--option}'[Request the DHCP option variable for use in dhcpcd-run-hooks]:option' \ + '(-p --persistent)'{-p,--persistent}"[Don't de-configure the interface and configuration at exit]" \ + '(-r --request)'{-r,--request}'[Request the address in the DHCP DISCOVER message]:address' \ + '(-s --inform)'{-s,--inform}'[Behaves exactly like -r, but sends a DHCP inform instead of a request]:address' \ + '--inform6[Performs a DHCPv6 Information Request]' \ + \*{-S,--static}'[Configures a static DHCP value]:value' \ + '(-t --timeout)'{-t,--timeout}'[Timeout after seconds]:seconds' \ + '(-u --userclass)'{-u,--userclass}'[Tags the DHCPv4 message with the userclass class]:class' \ + '(-v --vendor)'{-v,--vendor}'[Add an encapsulated vendor option]:vendor' \ + '(- *)--version[Display both program version and copyright information]' \ + '-w[Wait for an address to be assigned before forking to the background]' \ + '--waitip=[Wait for an address to assigned before forking to the background]: :(4 6)' \ + \*{-x,--exit}'[This will signal an existing dhcpcd process running on the interface to exit]: :_net_interfaces' \ + '(-y --reboot)'{-y,--reboot}'[Allow reboot seconds before moving to the discover phase if we have an old lease to use]:seconds' \ + '1:network interface:_net_interfaces' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_diana b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_diana new file mode 100644 index 00000000..b4e7c0ed --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_diana @@ -0,0 +1,150 @@ +#compdef diana +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Diana a command line interface to the aria2 daemon. (https://github.com/baskerville/diana). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Jindřich Pilař (https://github.com/JindrichPilar) +# +# ------------------------------------------------------------------------------ + +local GIDs PGIDs + +_diana_load_gids() { + GIDs=() + local downloads hashArr fileName + + downloads=$(diana list | cut -d' ' -f1) + + if [ ${#downloads} -eq "0" ]; then + return + fi + + hashArr=("${(f)$(echo "$downloads")}") + for ((i=1; i<=${#hashArr[@]}; i++)); do + fileName=$(diana files $hashArr[i] | grep "[X]" | rev | cut -d'/' -f1 | rev); + GIDs+=("$hashArr[i]:$fileName"); + done +} + +_diana_load_paused_gids() { + PGIDs=() + local downloads hashArr fileName + + downloads=$(diana paused | cut -d' ' -f1) + + if [ ${#downloads} -eq "0" ]; then + return + fi + + hashArr=("${(f)$(echo "$downloads")}") + for ((i=1; i<=${#hashArr[@]}; i++)); do + fileName=$(diana files $hashArr[i] | grep "[X]" | rev | cut -d'/' -f1 | rev); + PGIDs+=("$hashArr[i]:$fileName"); + done +} + +_diana_command_arguments() { + case $words[1] in + (remove) + _diana_load_gids + _describe -t output 'Downloads to delete' GIDs + ;; + (info) + _diana_load_gids + _describe -t output 'Downloads to get info' GIDs + ;; + (files) + _diana_load_gids + _describe -t output 'Get files for downloads' GIDs + ;; + (forcerm) + _diana_load_gids + _describe -t output 'Downloads to delete' GIDs + ;; + (pause) + _diana_load_gids + _describe -t output 'Downloads to pause' GIDs + ;; + (resume) + _diana_load_paused_gids + _describe -t output 'Downloads to resume' PGIDs + ;; + (preview) + _diana_load_gids + _describe -t output 'Downloads to preview' GIDs + ;; + esac + + +} + +_diana() { + local -a commands + + commands=( + "list:Output the list of active downloads." + "paused:Output the list of paused downloads." + "stopped:Output the list of stopped downloads." + "info:Output information regarding the given GIDs." + "files:Output the files owned by the downloads corresponding to the given GIDs." + "errors:Output the list of errors." + "stats:Output download bandwidth statistics." + "add:Download the given items (local or remote URLs to torrents, etc.)." + "remove:Remove the downloads corresponding to the given GIDs." + "forcerm:Forcibly remove the downloads corresponding to the given GIDs." + "pause:Pause the downloads corresponding to the given GIDs." + "resume:Resume the downloads corresponding to the given GIDs." + "preview:Preview all the files from all the downloads corresponding to the given GIDs." + "sleep:Pause all the active downloads." + "wake:Resume all the paused downloads." + "purge:Clear the list of stopped downloads and errors." + "clean:Stop seeding completed downloads." + ) + +_arguments -C \ + '1:cmd:->cmds' \ + '*:: :->args' \ + +case "$state" in + (cmds) + _describe -t commands 'commands' commands + ;; + (*) + _diana_command_arguments + ;; +esac +} + +_diana + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_direnv b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_direnv new file mode 100644 index 00000000..9edccb59 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_direnv @@ -0,0 +1,128 @@ +#compdef direnv +# ------------------------------------------------------------------------------ +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS OR THE AUTHOR BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for direnv 2.32.3 (https://direnv.net/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Nitai J. Perez +# +# ------------------------------------------------------------------------------ + +(( $+functions[_direnv_commands] )) || +_direnv_commands() { + local -a commands=( + 'allow:Grants direnv permission to load the given .envrc or .env file' + 'permit:Grants direnv permission to load the given .envrc or .env file' + 'grant:Grants direnv permission to load the given .envrc or .env file' + 'block:Revokes the authorization of a given .envrc or .env file' + 'deny:Revokes the authorization of a given .envrc or .env file' + 'revoke:Revokes the authorization of a given .envrc or .env file' + 'edit:Opens PATH_TO_RC or the current .envrc or .env into an $EDITOR and allow the file to be loaded afterwards' + 'exec:Executes a command after loading the first .envrc or .env found in DIR' + "fetchurl:Fetches a given URL into direnv's CAS" + 'help:shows this help' + 'hook:Used to setup the shell hook' + 'prune:removes old allowed files' + 'reload:triggers an env reload' + 'status:prints some debug status information' + 'stdlib:Displays the stdlib available in the .envrc execution context' + 'version:prints the version or checks that direnv is older than VERSION_AT_LEAST' + ) + + _describe 'command' commands +} + +_direnv() { + local curcontext="$curcontext" state line + typeset -A opt_args + local ret=1 + + _arguments -C \ + '1: :_direnv_commands' \ + '*:: :->command_args' && ret=0 + + case $state in + command_args) + case $words[1] in + (allow|permit|grant|block|deny|revoke|edit) + _arguments \ + '1:rc file:_files' \ + && ret=0 + ;; + (exec) + _arguments \ + '1:directory:_files -/' \ + '2:command:_command_names' \ + && ret=0 + ;; + (hook) + _arguments \ + '1:shell:(bash zsh fish tcsh elvish)' \ + && ret=0 + ;; + (fetchurl) + _arguments \ + '1:url:_urls' \ + '2:integrity hash' \ + && ret=0 + ;; + (version) + _arguments \ + '1:version at least' \ + && ret=0 + ;; + (help) + _arguments \ + '1:show private:(SHOW_PRIVATE)' \ + && ret=0 + ;; + (prune|reload|status|stdlib) + # do not complete + ret=0 + ;; + (*) + _default && ret=0 + ;; + esac + ;; + esac + + return ret +} + +_direnv "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_docpad b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_docpad new file mode 100644 index 00000000..5b6a4811 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_docpad @@ -0,0 +1,90 @@ +#compdef docpad +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for docpad v6.38.2 (https://github.com/bevry/docpad). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Changwoo Park (https://github.com/pismute) +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_docpad_subcommands() { + local -a commands=( + "run:run docpad on your project" + "init:initialize your project" + "generate:(re)generates your project" + "render:render the file at and output its results to stdout" + "watch:watches your project for changes, and (re)generates whenever a change is made" + "clean:ensure everything is cleaned correctly (will remove your out directory)" + "update:update your local DocPad and plugin installations to their latest compatible version" + "upgrade:update your local DocPad and plugin installations to their latest compatible version" + "install:install plugins" + "uninstall:uninstall a plugin" + "info:display the information about your docpad instance" + ) + + _describe -t commands 'command' commands "$@" +} + +_docpad() { + local ret=1 + + _arguments \ + '--outpath[a custom directory to place the rendered project]: :_files -/' \ + '--config[a custom configuration file to load in]: :_files' \ + '--env[the environment name to use for this instance, multiple names can be separated with a comma]' \ + '--log[the rfc log level to display]:level' \ + '(-v --verbose)'{-v,--verbose}'[set log level to 7]' \ + '(-d --debug)'{-d,--debug}'[output a log file]' \ + '--global[whether or not we should just fire global installation of docpad]' \ + '(--color --colour)'{--color,--colour}'[use color terminal output(default: true)]' \ + '--silent[do not write anything that is not essential]' \ + '--progress[output the progress as it occurs(default: true)]' \ + '--version[show version]' \ + '(- *)'{-h,--help}'[output usage information]'\ + '1: :_docpad_subcommands'\ + '*:: :_files' && ret=0 + + return ret +} + +_docpad "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_drush b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_drush new file mode 100644 index 00000000..d52921fc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_drush @@ -0,0 +1,191 @@ +#compdef drush +# ------------------------------------------------------------------------------ +# Copyright (c) 2014 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Drush (https://drushcommands.com/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Vasily Kraev (https://github.com/vasilykraev) +# +# ------------------------------------------------------------------------------ + +_drush() { + local curcontext='$curcontext' state line cmds ret=1 + integer NORMARG + typeset -A opt_args + + global_args=('--debug' '--verbose' '--yes' '--no' '--simulate' '--root=' '--uri=') + + _arguments -C \ + '(--*)'{--version,--version}'[Show drush version.]' \ + '(- *)'{-d,--debug}'[Display even more information, including internal messages.]' \ + '(- *)'{-v,--verbose}'[Display extra information about the command.]' \ + '(- *)'{-y,--yes}'[Assume "yes" as answer to all prompts.]' \ + '(- *)'{-n,--no}'[Assume "no" as answer to all prompts.]' \ + '(- *)'{-s,--simulate}'[Simulate all relevant actions (don'\''t actually change the system).]' \ + '(- *)'{-r,--root=}'[Drupal root directory to use (default: current directory).]' \ + '(- *)'{-l,--uri=}'[URI of the drupal site to use (only needed in multisite environments or when running on an alternate port).]' \ + '1: :->cmds' \ + '*::arg:->args' \ + && ret=0 + +case $state in + cmds) + _values 'drush command' \ + '(archive-dump)'{archive-dump,ard,arb}'[Backup your code, files, and database into a single file.]' \ + '(archive-restore)'{archive-restore,arr}'[Expand a site archive into a Drupal web site.]' \ + '(cache-clear)'{cache-clear,cc}'[Clear a specific cache, or all drupal caches.]' \ + '(core-status)'{core-status,status,st}'[Provides a birds-eye view of the current Drupal installation, if any.]' \ + '(core-cron)'{core-cron,cron}'[Run all cron hooks in all active modules for specified site.]' \ + '(core-execute)'{core-execute,exec}'[Execute a shell command. Usually used with a site alias.]' \ + '(drupal-directory)'{drupal-directory,dd}'[Return the filesystem path for modules/themes and other key folders.]' \ + 'help[Print this help message.]' \ + 'image-flush[Flush all derived images for a given style.]' \ + '(site-alias)'{site-alias,sa}'[Print an alias record.]' \ + '(site-install)'{site-install,si}'[Install Drupal along with modules/themes/configuration using the specified install profile.]' \ + 'test-clean[Clean temporary tables and files.]' \ + 'test-run[Run tests. Note that you must use the --uri option.]' \ + '(updatedb)'{updatedb,updb}'[Apply any database updates required (as with running update.php).]' \ + '(variable-delete)'{variable-delete,vdel}'[Delete a variable.]' \ + '(variable-get)'{variable-get,vget}'[Get a list of some or all site variables and values.]' \ + '(variable-set)'{variable-set,vset}'[Set a variable.]' \ + '(pm-list)'{pm-list,pml}'[Show a list of available extensions (modules and themes).]' \ + '(pm-disable)'{pm-disable,dis}'[Disable one or more extensions (modules or themes). Disable dependent extensions as well.]' \ + '(pm-download)'{pm-download,dl}'[Download projects from drupal.org or other sources.]' \ + '(pm-enable)'{pm-enable,en}'[Enable one or more extensions (modules or themes). Enable dependent extensions as well.]' \ + 'pm-uninstall[Uninstall one or more modules.]' \ + 'pm-update[Update Drupal core and contrib projects and apply any pending database updates (Same as pm-updatecode + updatedb).]' \ + '(sql-cli)'{sql-cli,sqlc}'[Open a SQL command-line interface using Drupals credentials.]' \ + 'sql-drop[Drop all tables in a given database.]' \ + 'sql-dump[Exports the Drupal DB as SQL using mysqldump or equivalent.]' \ + '(sql-query)'{sql-query,sqlq}'[Execute a query against the site database.]' \ + 'sql-sync[Copy and import source database to target database. Transfers via rsync.]' \ + '(user-login)'{user-login,uli}'[Display a one time login link for the given user account (defaults to uid 1).]' \ + '(user-password)'{user-password,upwd}'[(Re)Set the password for the user account with the specified name.]' \ + '(devel-reinstall)'{devel-reinstall,dre}'[Disable, Uninstall, and Install a list of projects. (devel)]' \ + '(devel-token)'{devel-token,token}'[List available tokens (devel)]' \ + '(generate-content)'{generate-content,genc}'[Create content. (devel_generate)]' \ + '(generate-menus)'{generate-menus,genm}'[Create menus and menu items. (devel_generate)]' \ + '(generate-terms)'{generate-terms,gent}'[Create terms in specified vocabulary. (devel_generate)]' \ + '(generate-users)'{generate-users,genu}'[Create users. (devel_generate)]' \ + '(generate-vocabs)'{generate-vocabs,genv}'[Create vocabularies. (devel_generate)]' \ + '(features-diff)'{features-diff,fd}'[Show the difference between the default and overridden state of a feature.]' \ + '(features-export)'{features-export,fe}'[Export a feature from your site into a module.]' \ + '(features-list)'{features-list,fl}'[List all the available features for your site.]' \ + '(features-revert)'{features-revert,fr}'[Revert a feature module on your site.]' \ + '(features-revert-all)'{features-revert-all,fra}'[Revert all enabled feature module on your site.]' \ + '(features-update)'{features-update,fu}'[Update a feature module on your site.]' \ + '(features-update-all)'{features-update-all,fua}'[Update all feature modules on your site.]' \ + && ret=0 + ;; + args) + case $line[1] in + (archive-dump|ard) + _arguments \ + '(--description)--description=[Filter out extensions that are provided by drupal core.]' \ + '(--destination)--destination=[The full path and filename in which the archive should be stored. If omitted, it will be saved to the drush-backups directory.]' \ + '(--no-core)--no-core[Exclude Drupal core, so the backup only contains the site specific stuff.]' \ + '(--pipe)--pipe[Only print the destination of the archive. Useful for scripts that don'\''t pass --destination.]' \ + '(--tar-options)--tar-options=[Options passed thru to the tar command.]' \ + && ret=0 + compadd -a global_args + ;; + (archive-restore|arr) + _arguments \ + '(--db-prefix)--db-prefix[An optional table prefix to use during restore.]' \ + '(--db-su)--db-su[Account to use when creating the new database. Optional.]' \ + '(--db-su-pw)--db-su-pw[Password for the "db-su" account. Optional.]' \ + '(--db-url)--db-url=[A Drupal 6 style database URL indicating the target for database restore. If not provided, the archived settings.php is used. ]' \ + '(--destination)--destination[Specify where the Drupal site should be expanded, including the docroot. Defaults to the current working directory.]' \ + '(--overwrite)--overwrite[Allow drush to overwrite any files in the destination.]' \ + && ret=0 + compadd -a global_args + ;; + (user-password|upwd) + _arguments \ + '--password=:Set the password for the username someuser.' \ + && ret=0 + ;; + (help) + _values 'commands' 'arb' 'archive-dump' 'archive-restore' 'ard' 'arr' 'cache-clear' 'cc' 'core-cron' 'core-execute' 'core-status' 'cron' 'dd' 'devel-reinstall' 'devel-token' 'dis' 'dl' 'dre' 'drupal-directory' 'en' 'exec' 'fd' 'fe' 'features-diff' 'features-export' 'features-list' 'features-revert' 'features-revert-all' 'features-update' 'features-update-all' 'fl' 'fr' 'fra' 'fu' 'fua' 'genc' 'generate-content' 'generate-menus' 'generate-terms' 'generate-users' 'generate-vocabs' 'genm' 'gent' 'genu' 'genv' 'help' 'image-flush' 'pm-disable' 'pm-download' 'pm-enable' 'pm-list' 'pm-uninstall' 'pm-update' 'pml' 'sa' 'si' 'site-alias' 'site-install' 'sql-cli' 'sql-drop' 'sql-dump' 'sql-query' 'sql-sync' 'sqlc' 'sqlq' 'st' 'status' 'test-clean' 'test-run' 'token' 'uli' 'updatedb' 'updb' 'upwd' 'user-login' 'user-password' 'variable-delete' 'variable-get' 'variable-set' 'vdel' 'vget' 'vset' + ;; + (cc) + _values 'options' 'all' 'drush' 'theme-registry' 'menu' 'css-js' 'block' + ;; + (pm-list|pml) + _arguments \ + '(--core)--core[Filter out extensions that are not in drupal core.]' \ + '(--no-core)--no-core[Filter out extensions that are provided by drupal core.]' \ + '(--pipe)--pipe[Returns a whitespace delimited list of the names of the resulting extensions.]' \ + '(--status)--status=-[Filter by extension status. Choices: enabled, disabled and/or "not installed".]:status:(enabled disabled)' \ + '(--type)--type=-[Filter by extension type. Choices: module, theme.]:type:(module theme)' \ + && ret=0 + ;; + (pm-disable|dis) + _modules=( $(drush pml --status=enabled --pipe) ) + if [[ $_modules != "" ]]; then + _values 'enabled modules' $_modules + fi + ;; + (pm-enable|en) + _arguments -C \ + '--resolve-dependencies[Attempt to download any missing dependencies. At the moment, only works when the module name is the same as the project name.]' \ + '--skip[Skip automatic downloading of libraries (c.f. devel).]' && ret=0 + _modules=( $(drush pml --status="disabled,not installed" --pipe) ) + if [[ $_modules != "" ]]; then + _values -s 'not yet enabled modules' $_modules && ret=0 + fi + ;; + (*) + _values 'Global options' \ + {-d,--debug}'[Display even more information, including internal messages.]' \ + {-v,--verbose}'[Display extra information about the command.]' \ + {-y,--yes}'[Assume "yes" as answer to all prompts.]' \ + {-n,--no}'[Assume "no" as answer to all prompts.]' \ + {-s,--simulate}'[Simulate all relevant actions (don'\''t actually change the system).]' \ + {-r,--root=}'[Drupal root directory to use (default: current directory).]' \ + {-l,--uri=}'[URI of the drupal site to use (only needed in multisite environments or when running on an alternate port).]' + ;; + esac + ;; +esac +} + +_drush '$@' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ecdsautil b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ecdsautil new file mode 100644 index 00000000..2724a0bb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ecdsautil @@ -0,0 +1,53 @@ +#compdef ecdsautil +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for ecdsaultils v0.4.0 (https://github.com/freifunk-gluon/ecdsautils) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Robinhuett +# +# ------------------------------------------------------------------------------ + +_ecdsautil_args() { + case $words[1] in + (sign) + _arguments '1:somefile:_files' + ;; + (verify) + _arguments '-s[signature]:secret:_files' '-p[publickey]:pubkey:_files' +'-n[signaturecount]:signaturecount:""' ':file:_files' + ;; + esac +} + +_ecdsautil() { + local -a commands + + commands=( + "help:Show help" + "generate-key:generate a new secret on stdout" + "show-key:output public key of secret read from stdin" + "sign:sign file" + "verify:verify signature of file" + ) + + _arguments -C \ + '1:cmd:->cmds' \ + '*:: :->args' \ + + case "$state" in + (cmds) + _describe -t commands 'commands' commands + ;; + (*) + _ecdsautil_args + ;; + esac +} + +_ecdsautil "$@" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_emacs b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_emacs new file mode 100644 index 00000000..4683c331 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_emacs @@ -0,0 +1,105 @@ +#compdef emacs +# ------------------------------------------------------------------------------ +# Copyright (c) 2022 Github zsh-users - https://github.com/zsh-users +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for emacs 29. (https://www.gnu.org/software/emacs/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei YOSHIDA (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_arguments \ + '--batch[do not do interactive display, implies -q]' \ + '--chdir[change to directory]: :_files -/' \ + '(--daemon --bg-daemon --fg-daemon)--daemon[start a server in the background]' \ + '(--daemon --bg-daemon --fg-daemon)--bg-daemon=-[start a named server in the background]::name' \ + '(--daemon --bg-daemon --fg-daemon)--fg-daemon=-[start a named server in the foreground]' \ + '--debug-init[enable Emacs Lisp debugger for init file]' \ + '(-d --display)'{-d,--display}'[use X server DISPLAY]:display' \ + '--module-assertions[assert behavior of dynamic modules]' \ + '--dump-file[read dumped state from FILE]: :_files' \ + '(- *)--fingerprint[output fingerprint and exit]' \ + '--seccomp=[read Seccomp BPF filter from FILE]: :_files' \ + '--no-build-details[do not add build details such as time stamps]' \ + '--no-desktop[do not load a saved desktop]' \ + '(-q --no-init-file)'{-q,--no-init-file}'[loader neither ~/.emacs nor default.el]' \ + '(-nl --no-loadup)'{-nl,--no-loadup}'[do not load loadup.el]' \ + '--no-site-file[do not load site-start.el]' \ + '--no-x-resources[do not load X resources]' \ + '(-nsl --no-site-lisp)'{-nsl,--no-site-lisp}'[do not add site-lisp directories to load-path]' \ + '--no-splash[do not display a splash screen on startup]' \ + '(-nw --no-window-system)'{-nw,--no-window-system}'[do not communicate with X, ignoring $DISPLAY]' \ + '--init-directory=[use DIR when looking for the Emacs init files]: :_files -/' \ + '(-Q --quick)'{-Q,--quick}'[equivalent to -q --no-site-file --no-site-lisp --no-splash --no-x-resources]' \ + '--script[run FILE as an Emacs Lisp script]: :_files' \ + '(-t --terminal)'{-t,--terminal}'[use DEVICE for terminal IO]: :_files' \ + '(-u --user)'{-u,--user}'[load ~USER/.emacs instead of your own]' \ + \*{-L,--directory}'[prepend DIR to load-path(with :DIR, append DIR)]: :_files -/' \ + {--eval,--execute}'[evaluate Emacs Lisp expression EXPR]:expr' \ + \*{--file,--find-file,--visit}'[visit FILE]: :_files' \ + \*{-f,--funcall}'[call Emacs Lisp function FUNC with no arguments]:func' \ + '--kill[exit without asking for confirmation]' \ + \*{-l,--load}'[load Emacs Lisp FILE using the load function]: :_files' \ + '(-bg --background-color)'{-bg,--background-color}'[window background color]:color' \ + '(-D --basic-display)'{-D,--basic-display}'[disable many display features]' \ + '(-bg --border-color)'{-bg,--border-color}'[main border color]:color' \ + '(-bw --border-width)'{-bw,--border-width}'[width of main border]' \ + '--color=-[override color mode for character terminals]:: :(auto never always ansi8)' \ + '(-cr --cursor-color)'{-cr,--cursor-color}'[color of the Emacs cursor indicating point]:color' \ + '(-fn --font)'{-fn,--font}'[default font, must be fixed-width]:font' \ + '(-fg --foreground)'{-fg,--foreground}'[window foreground color]:color' \ + '(-fh --fullheight)'{-fh,--fullheight}'[make the first frame high as the screen]' \ + '(-fs --fullscreen)'{-fs,--fullscreen}'[make the first frame fullscreen]' \ + '(-fw --fullwidth)'{-fw,--fullwidth}'[make the first frame wide as the screen]' \ + '(-mm --maximized)'{-mm,--maximized}'[make the first frame maximized]' \ + '(-g --geometry)'{-g,--geometry}'[window geometry]:geometry' \ + '(-nbi --no-bitmap-icon)'{-nbi,--no-bitmap-icon}'[do not use picture of gnu for Emacs icon]' \ + '--iconic[start Emacs in iconified state]' \ + '(-ib --internal-border)'{-ib,--internal-border}'[width between text and main border]:width' \ + '(-lsp --line-spacing)'{-lsp,--line-spacing}'[additional space to put between lines]' \ + '(-ms --mouse-color)'{-ms,--mouse-color}'[mouse cursor color in Emacs window]:color' \ + '(-T --name --title)'{-T,--name,--title}'[title for initial Emacs frame]:title' \ + '(-nbc,--no-blinking-cursor)'{-nbc,--no-blinking-cursor}'[disable blinking cursor]' \ + '(-r -rv --reverse-video)'{-r,-rv,--reverse-video}'[switch foreground and background]' \ + '(-vb --vertical-scroll-bars)'{-vb,--vertical-scroll-bars}'[enable vertical scroll bars]' \ + '--xrm[set additional X resources]:resource' \ + '--parent-id[set parent window]:xid' \ + '(- *)--help{display help and exit}' \ + '(- *)--version[output version information and exit]' \ + '*: :_files' + + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_emacsclient b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_emacsclient new file mode 100644 index 00000000..47ef5771 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_emacsclient @@ -0,0 +1,66 @@ +#compdef emacsclient +# +# ------------------------------------------------------------------------------ +# Copyright (c) 2022 Github zsh-users - https://github.com/zsh-users +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for emacsclient 29 +# - https://www.gnu.org/software/emacs/manual/html_node/emacs/Invoking-emacsclient.html +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei YOSHIDA (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_arguments -s -n : \ + '(- *)'{-V,--version}'[Print version information and exit]' \ + '(- *)'{-H,--help}'[Print this usage information message and exit]' \ + '(-nw -t --tty)'{-nw,-t,--tty}'[Open a new Emacs frame on the current terminal]' \ + '(-c --create-frame)'{-c,--create-frame}'[Create a new frame instead of trying to use the current Emacs frame]' \ + '(-r --reuse-frame)'{-r,--reuse-frame}'[Create a new frame if none exists, otherwise use the current Emacs frame]' \ + '(-F --frame-parameters)'{-F,--frame-parameters=}'[Set the parameters of a new frame]:alist' \ + '(-e --eval)'{-e,--eval}'[Evaluate as Emacs Lisp expressions]' \ + '(-n --no-wait)'{-n,--no-wait}'[Returns immediately without waiting for finish]' \ + '(-w --timeout)'{-w,--timeout=}'[Seconds to wait before timing out]:seconds' \ + '(-q --quiet)'{-q,--quiet}"[Don't display messages on success]" \ + '(-u --suppress-output)'{-u,--suppress-output}"[Don't display return values from the server]" \ + '(-d --display)'{-d,--display=}'[Tell the server to display the files on the given display]:display:_x_display' \ + '--parent-id=[Open in parent window ID, via XEmbed]' \ + '(-s --socket-name)'{-s,--socket-name=}'[Set filename of the UNIX socket for communication]: :_files' \ + '(-f --server-file)'{-f,--server-file=}'[Set filename of the TCP authentication file]: :_files' \ + '(-a --alternate-editor)'{-a,--alternate-editor=}'[Editor to fallback to if the server is not running if EDITOR is the empty string]:editor:_files' \ + '(-T --tramp)'{-T,--tramp=}'[PREFIX to prepend to filenames sent by emacsclient for locating files remotely via Tramp]:prefix' \ + '*: :_files' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_emulator b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_emulator new file mode 100644 index 00000000..18ad13bb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_emulator @@ -0,0 +1,137 @@ +#compdef emulator +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for emulator (Android Emulator) 12.0 +# (https://developer.android.com/studio/run/emulator-command). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# +# ------------------------------------------------------------------------------ + + +typeset -A opt_args +local context state line curcontext="$curcontext" + +_list_avds() { + local -a _avds=($HOME/.android/avd/*.ini(N.:t:r)) + echo "${_avds[@]}" +} + +# TODO All image options are contextual to -sysdir value +# TODO All skin options are contextual to -skindir value +# TODO snapshot options are mutually exclusive +# TODO Use '-snapshot-list' output for snapshot names +# TODO -logcat: use completer from _adb +# TODO Complete options with device values +# TODO Complete -prop +_arguments \ + '(- : *)-version[display emulator version number]' \ + '(- : *)-help[display help information]' \ + '(- : *)-help-disk-images[about disk images]' \ + '(- : *)-help-keys[supported key bindings]' \ + '(- : *)-help-debug-tags[debug tags for -debug ]' \ + '(- : *)-help-char-devices[character specification]' \ + '(- : *)-help-environment[environment variables]' \ + '(- : *)-help-keyset-file[key bindings configuration file]' \ + '(- : *)-help-virtual-device[virtual device management]' \ + '(- : *)-help-sdk-images[about disk images when using the SDK]' \ + '(- : *)-help-build-images[about disk images when building Android]' \ + '(- : *)-help-all[prints all help content]' \ + '(- : *)-help-'{version,list-avds,sysdir,system,writable-system,image,datadir,kernel,ramdisk,initdata,data,partition-size,cache,no-cache,nocache,sdcard,snapstorage,no-snapstorage,snapshot,no-snapshot,no-snapshot-save,no-snapshot-load,snapshot-list,no-snapshot-update-time,wipe-data,avd,skindir,skin,noskin,no-skin,memory,cores,accel,no-accel,netspeed,netdelay,netfast,trace,show-kernel,shell,no-jni,nojni,logcat,noaudio,no-audio,audio,raw-keys,radio,port,ports,onion,onion-alpha,onion-rotation,scale,dpi-device,http-proxy,timezone,dns-server,cpu-delay,no-boot-anim,no-window,report-console,gps,keyset,shell-serial,tcpdump,bootchart,charmap,prop,shared-net-id,nand-limits,memcheck,qemu,verbose}'[print option-specific help]' \ + '-list-avds[list available AVDs]' \ + '-sysdir[search for system disk images in the directory]: :_files -/' \ + '(-system -image)'{-system,-image}'[read initial system image from the file]: :_files -g "*.img"' \ + '-writable-system[make system image writable after '\''adb remount'\'']' \ + '-datadir[write user data into the directory]: :_files -/' \ + '-kernel[use specific emulated kernel]: :_files' \ + '-ramdisk[ramdisk image (default /ramdisk.img]: :_files -g "*.img"' \ + '-initdata[same as '\''-init-data '\'']: :_files' \ + '-data[data image (default /userdata-qemu.img]: :_files -g "*.img"' \ + '-partition-size[system/data partition size]:size (in MBs)' \ + '(-no-cache -nocache)-cache[cache partition image (default is temporary file)]: :_files -g "*.img"' \ + '(-cache -no-cache -nocache)'{-no-cache,-nocache}'[disable the cache partition]' \ + '-sdcard[SD card image (default /sdcard.img]: :_files -g "*.img"' \ + '(-no-snapstorage)-snapstorage[file that contains all state snapshots (default /snapshots.img)]: :_files -g "*.img"' \ + '(-snapstorage)-no-snapstorage[do not mount a snapshot storage file (this disables all snapshot functionality)]' \ + '-snapshot[name of snapshot within storage file for auto-start and auto-save (default '\''default-boot'\'')]:snapshot name' \ + '-no-snapshot[perform a full boot and do not do not auto-save, but qemu vmload and vmsave operate on snapstorage]' \ + '-no-snapshot-save[do not auto-save to snapshot on exit: abandon changed state]' \ + '-no-snapshot-load[do not auto-start from snapshot: perform a full boot]' \ + '-snapshot-list[show a list of available snapshots]' \ + '-no-snapshot-update-time[do not do try to correct snapshot time on restore]' \ + '-wipe-data[reset the user data image (copy it from initdata)]' \ + '-avd[use a specific android virtual device]:android virtual device name:($(_list_avds))' \ + '-skindir[search skins in (default /skins)]: :_files -/' \ + '-skin[select a given skin]' \ + '(-noskin -no-skin)'{-noskin,-no-skin}'[don'\''t use any emulator skin]' \ + '-memory[physical RAM size in MBs]:size (in MBs)' \ + '-cores[Set number of CPU cores to emulator]:number' \ + '(-no-accel)-accel[Configure emulation acceleration]:mode' \ + '(-accel)-no-accel[Same as '\''-accel off'\'']' \ + '-netspeed[maximum network download/upload speeds]:speed' \ + '-netdelay[network latency emulation]:delay' \ + '-netfast[disable network shaping]' \ + '-trace[enable code profiling (F9 to start)]:trace name' \ + '-show-kernel[display kernel messages]' \ + '-shell[enable root shell on current terminal]' \ + {-no-jni,-nojni}'[disable JNI checks in the Dalvik runtime]' \ + '-logcat[enable logcat output with given tags]:logcat tags' \ + '(-audio -noaudio -no-audio)'{-noaudio,-no-audio}'[disable audio support]' \ + '(-noaudio -no-audio)-audio[use specific audio backend]:audio backend' \ + '-raw-keys[disable Unicode keyboard reverse-mapping]' \ + '-radio[redirect radio modem interface to character device]:device' \ + '-port[TCP port that will be used for the console]:port number' \ + '-ports[TCP ports used for the console and adb bridge]:console port,adb port' \ + '-onion[use overlay PNG image over screen]: :_files -g "*.(png|PNG)"' \ + '-onion-alpha[specify onion-skin translucency]:percentage' \ + '-onion-rotation[specify onion-skin rotation]:rotation:((1 2 3 4))' \ + '-scale[scale emulator window]:scale' \ + '-dpi-device[specify device'\''s resolution in dpi (default 165)]:dpi' \ + '-http-proxy[make TCP connections through a HTTP/HTTPS proxy]:proxy' \ + '-timezone[use this timezone instead of the host'\''s default]:timezone' \ + '-dns-server[use this DNS server(s) in the emulated system]:DNS servers' \ + '-cpu-delay[throttle CPU emulation]:CPU delay' \ + '-no-boot-anim[disable animation for faster boot]' \ + '-no-window[disable graphical window display]' \ + '-report-console[report console port to remote socket]: :_socket' \ + '-gps[redirect NMEA GPS to character device]:device' \ + '-keyset[specify keyset file name]: :_files' \ + '-shell-serial[specific character device for root shell]:device' \ + '-tcpdump[capture network packets to file]: :_files' \ + '-bootchart[enable bootcharting]:timeout' \ + '-charmap[use specific key character map]: :_files' \ + '*-prop[set system property on boot]:name=value' \ + '-shared-net-id[join the shared network, using IP address 10.1.2.]:number' \ + '-nand-limits[enforce NAND/Flash read/write thresholds]:limits' \ + '-memcheck[enable memory access checking]:flags' \ + '-qemu[pass arguments to qemu]:arguments' \ + '-verbose[same as '\''-debug-init'\'']' \ + '*'{-debug,-debug-,-debug-no-}'[enable/disable specific debug messages]:tag' \ + '1: :->cmds' \ + '*:: :->args' && ret=0 + +case $state in + cmds) + local -a _avds=($(_list_avds)) + for ((i=1; i<=${#_avds[@]}; i++)); do + _avds[i]="@${_avds[i]}" + done + _values 'avds' "${_avds[@]}" + ;; +esac + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_envdir b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_envdir new file mode 100644 index 00000000..e4524019 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_envdir @@ -0,0 +1,57 @@ +#compdef envdir +# ------------------------------------------------------------------------------ +# Copyright (c) 2016, Github zsh-users (https://github.com/zsh-users) +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for envdir (https://github.com/jezdez/envdir). +# It completes its few options and then a directory and command. +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Daniel Hahler +# +# ------------------------------------------------------------------------------ + +local -a args=( + '(-h --help)'{-h+,--help}'[show this help message and exit]' + '(-)'--version'[display version information and exit]' + '(-)1:directory: _path_files -/' + '(-)2:command: _command_names -e' + '*::arguments: _precommand' +) +_arguments -S $args + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_exportfs b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_exportfs new file mode 100644 index 00000000..1265e327 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_exportfs @@ -0,0 +1,51 @@ +#compdef exportfs +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for nfs's exportfs - maintain table of exported NFS file systems. +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Timofey Titovets +# +# ------------------------------------------------------------------------------ +_exportfs() { + _values -w 'option' \ + '(-i)-a[Export or unexport all directories]' \ + '(-a -r -u)-i[Ignore the /etc/exports file and files under /etc/exports.d directory]' \ + '(-i)-r[Reexport all directories]' \ + '(-i)-u[Unexport one or more directories]' \ + '-f[Flush everything out of export table]' \ + '-o[option1,option2.. Specify a list of export options]' \ + '-s[Display the current export list suitable for /etc/exports]' \ + '-v[Be verbose]' +} +_exportfs "$@" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fab b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fab new file mode 100644 index 00000000..232314dd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fab @@ -0,0 +1,109 @@ +#compdef fab +# ------------------------------------------------------------------------------ +# Copyright (c) 2015 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Fabric (https://www.fabfile.org/) +# +# Source: https://github.com/vhbit/fabric-zsh-autocomplete +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Valerii Hiora (https://github.com/vhbit) +# +# ------------------------------------------------------------------------------ + + +local curcontext=$curcontext state line +declare -A opt_args + +declare target_list +target_list=(`fab --shortlist 2>/dev/null`) + +_targets() { + _describe -t commands "fabric targets" target_list +} + +output_levels=( + 'status: Status messages, i.e. noting when Fabric is done running, if the user used a keyboard interrupt, or when servers are disconnected from. These messages are almost always relevant and rarely verbose.' + 'aborts: Abort messages. Like status messages, these should really only be turned off when using Fabric as a library, and possibly not even then. Note that even if this output group is turned off, aborts will still occur – there just won’t be any output about why Fabric aborted!' + 'warnings: Warning messages. These are often turned off when one expects a given operation to fail, such as when using grep to test existence of text in a file. If paired with setting env.warn_only to True, this can result in fully silent warnings when remote programs fail. As with aborts, this setting does not control actual warning behavior, only whether warning messages are printed or hidden.' + 'running: Printouts of commands being executed or files transferred, e.g. [myserver] run: ls /var/www. Also controls printing of tasks being run, e.g. [myserver] Executing task ''foo''.' + 'stdout: Local, or remote, stdout, i.e. non-error output from commands.' + 'stderr: Local, or remote, stderr, i.e. error-related output from commands.' + 'user: User-generated output, i.e. local output printed by fabfile code via use of the fastprint or puts functions.' +) + +_arguments -w -S -C \ + '(-)'{-h,--help}'[show this help message and exit]: :->noargs' \ + '(-)'{-V,--version}'[show program'\''s version number and exit]: :->noargs' \ + '(-)--list[print list of possible commands and exit]: :->noargs' \ + '(-)--shortlist[print non-verbose list of possible commands and exit]: :->noargs' \ + '(--reject-unknown-hosts)--reject-unknown-hosts[reject unknown hosts]' \ + '(--no-pty)--no-pty[do not use pseudo-terminal in run/sudo]' \ + "(-d+ --display=-)"{-d+,--display=-}"[print detailed info about a given command]: :_targets" \ + '(-D --disable-known-hosts)'{-D,--disable-known-hosts}'[do not load user known_hosts file]' \ + '(-r --reject-unknown-hosts)'{-r,--reject-unknown-hosts}'[reject unknown hosts]' \ + '(-u+ --user=-)'{-u+,--user=-}'[username to use when connecting to remote hosts]: :' \ + '(-p+ --password=-)'{-p+,--password=-}'[password for use with authentication and/or sudo]: :' \ + '(-H+ --hosts=-)'{-H+,--hosts=-}'[comma separated list of hosts to operate on]: :' \ + '(-R+ --roles=-)'{-R+,--roles=-}'[comma separated list of roles to operate on]: :' \ + '(-a --no-agent)'{-a,--no-agent}'[don'\''t use the running SSH agent]' \ + '(-k --no-keys)'{-k,--no-keys}'[don'\''t load private key files from ~/.ssh/]' \ + '(-w --warn-only)'{-w,--warn-only}'[warn instead of abort, when commands fail]' \ + '-i+[path to SSH private key file. May be repeated]: :_files' \ + "(-f+ --fabfile=)"{-f+,--fabfile=}"[Python module file to import]: :_files -g *.py" \ + '(-c+ --config=-)'{-c+,--config=-}'[specify location of config file to use]: :_files' \ + '(-s+ --shell=-)'{-s+,--shell=-}'[specify a new shell, defaults to ''/bin/bash -l -c'']: :' \ + '(--ssh-config-path=)--ssh-config-path=[ssh config path]: :_files' \ + '(--hide=-)--hide=-[comma-separated list of output levels to hide]: :->levels' \ + '(--show=-)--show=-[comma-separated list of output levels to show]: :->levels' \ + '*::: :->subcmds' && return 0 + +if [[ CURRENT -ge 1 ]]; then + case $state in + noargs) + _message "nothing to complete";; + levels) + _describe -t commands "output levels" output_levels;; + *) + _targets;; + esac + + return +fi + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fail2ban-client b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fail2ban-client new file mode 100644 index 00000000..df9cef49 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fail2ban-client @@ -0,0 +1,339 @@ +#compdef fail2ban-client +# ------------------------------------------------------------------------------ +# Copyright (c) 2020 Github zsh-users - https://github.com/zsh-users +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for fail2ban-client (https://www.fail2ban.org/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Felix Neumärker +# +# ------------------------------------------------------------------------------ + +_f2bc_jails() { + LANG=C fail2ban-client status 2> /dev/null | sed -n -e 's/.*Jail list:\s\+//' -e 'T' -e 's/,\s\+/\'$'\n/g' -e 'p' +} + +_complete_f2bc_cmds() { + local cmds=( + 'unban:unbans all IP addresses' + 'set:set property' + 'get:get property' + 'status:gets the current status of the server' + 'reload:reloads the configuration/jails' + 'restart:restarts the server' + 'start:starts the server and the jails' + 'stop:stops all jails and terminate the server' + 'ping:tests if the server is alive' + 'flushlogs:flushes the logtarget if a file and reopens it' + 'help:return this output' + 'version:return the server version' + ) + + _describe -V "fail2ban commands" cmds +} + +_complete_f2bc_cmdargs() { + local f2barg="$words[$NORMARG]" + case "$f2barg" in + unban) + local jail + if (( $words[(I)(--all)] == 0 )) ; then + for jail in $(_f2bc_jails) ; do + _complete_f2bc_ips $jail + done + local unban_opts=(--all) + _describe -o "unban options" unban_opts + else + _nothing + fi + ;; + (set|get)) + if (( $NORMARG + 1 == $CURRENT )) ; then + _complete_f2bc_jails + _complete_f2bc_settings + else + _complete_f2bc_jail${f2barg} + fi + ;; + status) + if (( $NORMARG + 1 == $CURRENT )) ; then + _complete_f2bc_jails + elif (( $NORMARG + 2 == $CURRENT )) ; then + _values "flavor" basic cymru + else + _nothing + fi + ;; + esac +} + +_complete_f2bc_jails() { + local jails=($(_f2bc_jails)) + _describe -V "jails" jails +} + +_complete_f2bc_ips() { + local ips=("${(@f)$(LANG=C fail2ban-client status $1 2> /dev/null | sed -n -e 's/^.*Banned IP list:\s\+//' -e 'T' -e 's/\s\+/\'$'\n/g' -e 'p')}") + if [[ -n "${ips[@]}" ]] ; then + _describe -t "f2b_jail_$1" -V "banned ips of jail $1" ips + else + _nothing + fi +} + +_complete_f2bc_jailset() { + if (( $NORMARG + 2 == $CURRENT )) ; then + case $words[$NORMARG+1] in + loglevel) + local loglevel=(CRITICAL ERROR WARNING NOTICE INFO DEBUG TRACEDEBUG HEAVYDEBUG) + _describe -V "loglevel" loglevel ;; + logtarget) + local logtarget=(STDOUT STDERR SYSLOG) + _describe -V "logtarget" logtarget + _files ;; + syslogsocket) + local syslogsocket=(auto) + _describe -V "logtarget" syslogsocket + _files ;; + dbfile) + _files ;; + dbpurgeage) + _message "sets the max age in that history of bans will be kept" ;; + *) + # jail + local jailsettings=( + unbanip + banip + action + addaction + addfailregex + addignoreip + addignoreregex + addjournalmatch + addlogpath + bantime + datepattern + delaction + delfailregex + delignoreip + delignorerexgex + deljournalmatch + dellogpath + findtime + idle + ignorecache + ignorecommand + ignoreself + logencoding + maxlines + maxretry + usedns + ) + _describe -t "f2b_jail_setting" -V "jail setting" jailsettings ;; + esac + else + local jail="$words[$NORMARG+1]" + + if (( $NORMARG + 3 == $CURRENT )) ; then + case $words[$NORMARG+2] in + unbanip) + _complete_f2bc_ips "$jail" ;; + delfailregex) + _complete_f2bc_regex fail "$jail" ;; + delignorerexgex) + _complete_f2bc_regex ignore "$jail" ;; + dellogpath) + local filelist=("${(@f)$(LANG=C fail2ban-client status $jail 2> /dev/null | sed -n -e 's/^.*File list:\s\+//' -e 'T' -e 's/\s\+/\'$'\n/g' -e 'p')}") + + if [[ -n "${filelist[@]}" ]] ; then + _describe -t "f2b_filelist" -V "filelist of jail $1" filelist + else + _nothing + fi ;; + idle) + _values 'fail2ban idle' on off ;; + ignoreself) + _values 'fail2ban ignoreself' true false ;; + delignoreip) + local ignoreips=("${(@f)$(fail2ban-client get "$jail" ignoreip 2> /dev/null | sed -e 's/^[|`]-\s\+//p')}") + if [[ -n "${ignoreips[@]}" ]] ; then + _describe -t "f2b_ignoreip" -V "fail2ban ignored ips" ignoreips + else + _nothing + fi ;; + delaction|action) + _complete_f2bc_action "$jail" ;; + addlogpath) + _files ;; + *) + _message "No completion for ${words[NORMARG+2]}" ;; + esac + elif (( $NORMARG + 4 == $CURRENT )) ; then + case $words[$NORMARG+2] in + action) + _complete_f2bc_actionproperties "$jail" $words[$NORMARG+3] ;; + addaction) + _files ;; + *) + _nothing ;; + esac + else + _nothing + fi + fi +} + +_complete_f2bc_jailget() { + if (( $NORMARG + 2 == $CURRENT )) ; then + case $words[$NORMARG+1] in + (loglevel|logtarget|syslogsocket|dbfile|dbpurgeage)) + _nothing ;; + *) + # jail + local jailprops=( + logpath + logencoding + journalmatch + ignoreself + ignoreip + ignorecommand + failregex + ignoreregex + findtime + bantime + datepattern + usedns + maxretry + maxlines + actions + action + actionproperties + actionmethods + ) + _describe -t "f2b_jail_props" -V "jail properties" jailprops ;; + esac + else + local jail="$words[$NORMARG+1]" + + if (( $NORMARG + 3 == $CURRENT )) ; then + case $words[$NORMARG+2] in + (action|actionproperties|actionmethods)) + _complete_f2bc_action "$jail" ;; + *) + _nothing ;; + esac + elif (( $NORMARG + 4 == $CURRENT )) ; then + case $words[$NORMARG+2] in + (action|actionproperties|actionmethods)) + _complete_f2bc_actionproperties "$jail" $words[$NORMARG+3] ;; + *) + _nothing ;; + esac + else + _nothing + fi + fi +} + +_complete_f2bc_action() { + local jailactions=("${(@f)$(fail2ban-client get $1 actions 2>/dev/null | sed -e '1d' -e 's/,\s\+/\'$'\n/g')}") + + if [[ -n "${jailactions[@]}" ]] ; then + _describe -t "f2b_jail_actions" -V "jail actions" jailactions + else + _nothing + fi +} + +_complete_f2bc_actionproperties() { + local default_actionproperties=( + actionstart + actionstop + actioncheck + actionban + actionunban + timeout + ) + local all_actionproperties=("${(@f)$(fail2ban-client get $1 actionproperties $2 2>/dev/null | sed -e '1d' -e 's/,\s\+/\'$'\n/g')}") + local add_actionproperties=("${(@)all_actionproperties:|default_actionproperties}") + + _describe -t "f2b_actions_defprops" -V "default action properties" default_actionproperties + + if [[ -n "${add_actionproperties[@]}" ]] ; then + _describe -t "f2b_actions_remprops" -V "additional action properties" add_actionproperties + else + _nothing + fi +} + +_complete_f2bc_regex() { + local regex=("${(@f)$(fail2ban-client get $2 ${1}regex 2> /dev/null | sed -n -e 's/[|`]- \[\([0-9]\+\)\]:\s\+/\1:/p')}") + if [[ -n "${regex[@]}" ]] ; then + _describe -t "f2b_regex" -V "jail $2 ${1}regex" regex + else + _nothing + fi +} + +_complete_f2bc_settings() { + local setargs=(loglevel logtarget syslogsocket dbfile dbpurgeage) + _describe -t "f2b_settings" -V "fail2ban-client settings" setargs +} + +integer NORMARG + +_arguments -A "-*" -n \ + '-c[configuration directory]:_files -/' \ + '-s[socket path]:_files' \ + '-p[pidfile path]:_files' \ + '--loglevel[logging level]:(CRITICAL ERROR WARNING, NOTICE INFO, DEBUG, TRACEDEBUG HEAVYDEBUG)' \ + '--logtarget[logging target]:(stdout stderr syslog sysout)' \ + '--syslogsocket:_files' \ + '-d[dump configuration]' \ + '(--dp --dump-pretty)'{--dp,--dump-pretty}'[dump the configuration using more human readable representation]' \ + '(-t --test)'{-t,--test}'[test configuration]' \ + '-i[interactive mode]' \ + '-v[increase verbosity]' \ + '-q[decrease verbosity]' \ + '-x[force execution of the server (remove socket file)]' \ + '-b[start server in background]' \ + '-f[start server in foreground]' \ + '--str2sec[convert time abbreviation format to seconds]:_message str2sec' \ + '(-h --help)'{-h,--help}'[display this help message]' \ + '(-V --version)'{-V,--version}'[print the version]' \ + '1:fail2ban command:_complete_f2bc_cmds' \ + '*:fail2ban command argument:_complete_f2bc_cmdargs' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: set et sw=2 ts=2 ft=zsh: diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ffind b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ffind new file mode 100644 index 00000000..eb58fb16 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ffind @@ -0,0 +1,62 @@ +#compdef ffind +# ------------------------------------------------------------------------------ +# Copyright (c) 2017 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for ffind (https://github.com/jaimebuelta/ffind). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Sergei Eremenko (https://github.com/SmartFinn) +# +# ------------------------------------------------------------------------------ + +_arguments -C \ + '(-h --help)'{-h,--help}'[show help message and exit]' \ + '--version[show version number and exit]' \ + '-p[match whole path, not only name of files]' \ + '--nocolor[do not display color]' \ + '--nosymlinks[do not follow symlinks]' \ + '--hidden[do not ignore hidden directories]' \ + '-c[force case sensitive]' \ + '-i[force case insensitive]' \ + '--delete[delete files found]' \ + '--exec[execute the given command with the file found]:command:_command_names' \ + '--module[execute the given module with the file found]:module_name args:' \ + '--command[execute the given python program with the file found]:program:_files' \ + '--ignore-vcs[ignore version control system files and directories]' \ + '-f[experimental fuzzy search]' \ + '--return-results[for testing purposes only]' \ + '1:directory to search:_path_files -/' \ + '*:filepattern:' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fleetctl b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fleetctl new file mode 100644 index 00000000..542d7cfa --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fleetctl @@ -0,0 +1,123 @@ +#compdef fleetctl +# ------------------------------------------------------------------------------ +# Copyright (c) 2009-2015 Robby Russell and contributors (see +# https://github.com/ohmyzsh/ohmyzsh/graphs/contributors) +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for fleetctl (https://github.com/coreos/fleet). +# +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Remi Paulmier (https://github.com/shtouff) +# +# ------------------------------------------------------------------------------ + +# fleetctl zsh completion + +local -a _1st_arguments +_1st_arguments=( + 'cat:Output the contents of a submitted unit' + 'destroy:Destroy one or more units in the cluster' + 'fd-forward:Proxy stdin and stdout to a unix domain socket' + 'help:Show a list of commands or help for one command' + 'journal:Print the journal of a unit in the cluster to stdout' + 'list-machines:Enumerate the current hosts in the cluster' + 'list-unit-files:List the units that exist in the cluster.' + 'list-units:List the current state of units in the cluster' + 'load:Schedule one or more units in the cluster, first submitting them if necessary.' + 'ssh:Open interactive shell on a machine in the cluster' + 'start:Instruct systemd to start one or more units in the cluster, first submitting and loading if necessary.' + 'status:Output the status of one or more units in the cluster' + 'stop:Instruct systemd to stop one or more units in the cluster.' + 'submit:Upload one or more units to the cluster without starting them' + 'unload:Unschedule one or more units in the cluster.' + 'version:Print the version and exit' +) + +__task_list () +{ + local expl + declare -a tasks + + tasks=(cat destroy fd-forward help journal list-machines list-unit-files \ + list-units load ssh start status stop submit unload version) + + _wanted tasks expl 'help' compadd $tasks +} + +__unit_list () +{ + _wanted application expl 'command' compadd $(command fleetctl list-units | \ + tail -n +2 | awk '{print $1}') +} + +local expl + +local curcontext="$curcontext" state line +local -A opt_args + +_arguments -C \ + ':command:->command' \ + '*::options:->options' + +case $state in + (command) + _describe -t commands "gem subcommand" _1st_arguments + return + ;; + + (options) + case $line[1] in + (help) + _arguments ':feature:__task_list' + ;; + + (destroy|journal|start|status|stop|unload|cat) + _arguments '*:feature:__unit_list' + ;; + + (load|submit) + _arguments '*:file:_files -g *.service' + ;; + + (ssh) + _arguments '*:host:_hosts' + ;; + + (*) + _arguments '*:file:_files' + ;; + esac + ;; +esac + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_flutter b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_flutter new file mode 100644 index 00000000..e0452612 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_flutter @@ -0,0 +1,1087 @@ +#compdef flutter +# ------------------------------------------------------------------------------ +# MIT License +# +# Copyright (c) 2018 Nickolay Simonov +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for the Flutter.io sdk's cli tool 3.13.0 (https://flutter.dev) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Nikolai Simonov (https://github.com/NiKoTron) +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ +_flutter() { + typeset -A opt_args + local context state line + + local curcontext="$curcontext" + + local ret=1 + + _arguments -C -A "-*" \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-v --verbose)'{-v,--verbose}'[Noisy logging, including all shell commands executed]' \ + '--prefixed-errors[Causes lines sent to stderr to be prefixed with "ERROR:"]' \ + '--quiet[Reduce the amount of output from some commands]' \ + '(--no-wrap --wrap)--wrap[Whether to use output word wrapping]' \ + '(--wrap --no-wrap)--no-wrap[Whether to use output word wrapping]' \ + '--wrap-column=[Set the output wrap column]:number:' \ + '(-d --device-id)'{-d,--device-id}'[Target device id or name (prefixes allowed)]:id' \ + '--version[Reports the version of this tool]' \ + '--machine[When used with the "--version" flag, outputs the information using JSON]' \ + '(--no-color --color)--color[Whether to use terminal colors]' \ + '(--color --no-color)--no-color[Whether to use terminal colors]' \ + '(--no-version-check --version-check)--version-check[Allow Flutter to check for updates when this command runs]' \ + '(--version-check --no-version-check)--no-version-check[Not allow Flutter to check for updates when this command runs]' \ + '--suppress-analytics[Suppress analytics reporting when this command runs]' \ + '(--enable-telemetry)--disable-telemetry[Disable telemetry reporting each time a flutter command runs]' \ + '(--disable-telemetry)--enable-telemetry[Enable telemetry reporting each time a flutter command runs]' \ + '--packages[Path to your ".packages" file. (required, since the current directory does not contain a ".packages" file)]' \ + '--local-engine-src-path=[Path to your engine src directory]: :_path_files -/' \ + '--local-engine=[Specific version of the engine]:version' \ + '--local-web-sdk=[Specific version of the Web SDK]:version' \ + '--show-test-device=[List the special "flutter-tester" device in device listings]' \ + '--show-web-server-device=[List the special "web-server" device in device listings]' \ + '--ci[Enable a set of CI-specific test debug settings]' \ + '1: :_flutter_root_commands' \ + '*::arg:->args' \ + && ret=0 + + case "$state" in + (args) + case $words[1] in + (help) + _arguments \ + '1: :_flutter_root_commands' \ + && ret=0 + ;; + (analyze) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--current-package[Include the lib/main.dart file from the current directory, if any. (defaults to on)]' \ + '--no-current-package[Include the lib/main.dart file from the current directory, if any. (defaults to on)]' \ + '--watch[Run analysis continuously, watching the filesystem for changes]' \ + '--write=[Also output the results to a file]: :_files ' \ + '--pub[Whether to run "flutter packages get" before executing this command. (defaults to on)]' \ + '--no-pub[Whether to run "flutter packages get" before executing this command. (defaults to on)]' \ + '--congratulate[When analyzing, show output even when there are no errors/warnings/hints/lints (defaults to on)]' \ + '--no-congratulate[When analyzing, show output even when there are no errors/warnings/hints/lints(defaults to on)]' \ + '--preamble[When analyzing, display the number of files that will be analyzed. (defaults to on)]' \ + '--no-preamble[When analyzing, display the number of files that will be analyzed. (defaults to on)]' \ + '(--no-fatal-infos --fatal-infos)--fatal-infos[Treat info level issues as fatal]' \ + '(--no-fatal-infos --fatal-infos)--no-fatal-infos[Not treat info level issues as fatal]' \ + '(--no-fatal-warnings --fatal-warnings)--fatal-warnings[Treat warning level issues as fatal]' \ + '(--no-fatal-warnings --fatal-warnings)--no-fatal-warnings[Not treat warning level issues as fatal]' \ + && ret=0 + ;; + (assemble) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + {-d,--define=}'[Allows passing configuration to a target]: :' \ + '--performance-measurement-file[Output individual target performance to a JSON file]' \ + {-i,--input=}'[Allows passing additional input]: :' \ + '--depfile=[A file path where a depfile will be written]: :_path_files' \ + '--build-inputs=[A file path where a newline-separated file containing all inputs used will be written after a build]: :_path_files' \ + '--build-outputs=[A file path where a newline-separated file containing all outputs used will be written after a build]: :_path_files' \ + '(-o --output)'{-o,--output=}'[A directory where output files will be written]: :_path_files -/' \ + '*--dart-define=[Additional key-value pairs that will be available as constants]:' \ + '--dart-define-from-file=[The path of a json format file where flutter define a global constant pool]: :_files -g "*.json"' \ + '--resource-pool-size=[The maximum number of concurrent tasks the build system will run]:number:' \ + && ret=0 + ;; + (attach) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--debug[Build a debug version of your app (default mode)]' \ + '--profile[Build a version of your app specialized for performance profiling]' \ + '(-t --target)'{-t,--target=}'[The main entry-point file of the application, as run on the device.(defaults to "lib/main.dart")]::_files -g "*.dart"' \ + '--device-vmservice-port=[Look for vmservice connections only from the specified port]:port:' \ + '--host-vmservice-port=[When a device-side vmservice port is forwarded to a host-side port]:port:' \ + '*--dart-define=[Additional key-value pairs that will be available as constants]:' \ + '--dart-define-from-file=[The path of a json format file where flutter define a global constant pool]: :_files -g "*.json"' \ + '--device-user=[Identifier number for a user or work profile on Android only]:id:' \ + '--null-assertions[Perform additional null assertions on the boundaries of migrated and un-migrated code]' \ + '--no-null-assertions[Not perform additional null assertions on the boundaries of migrated and un-migrated code]' \ + '--debug-url=[The URL at which the observatory is listening]:url:' \ + '--app-id=[The package name (Android) or bundle identifier (iOS) for the app]:app_id:' \ + '--pid-file=[Specify a file to write the process id to]: :_files' \ + '--track-widget-creation[Track widget creation locations. (defaults to on)]' \ + '--no-track-widget-creation[Not rack widget creation locations. (defaults to on)]' \ + '--dds-port=[When this value is provided, the Dart Development Service (DDS) will be bound to the provided port]:port:' \ + '--device-timeout=[Time in seconds to wait for devices to attach]:seconds:' \ + '--device-connection=[Discover devices based on connection type]:type:_flutter_device_connection_types' \ + && ret=0 + ;; + (bash-completion) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(--no-overwrite --overwrite)--overwrite[Overwritten completion setup if it already exists]' \ + '(--overwrite --no-overwrite)--no-overwrite[Not overwritten completion setup if it already exists]' \ + && ret=0 + ;; + (build) + _flutter_build && ret=0 + ;; + (config) + _arguments \ + '(-h --help)'{-h,--help}'[Print this usage information]' \ + '--analytics[Enable or disable reporting anonymously tool usage statistics and crash reports]' \ + '--no-analytics[Enable or disable reporting anonymously tool usage statistics and crash reports]' \ + '--clear-ios-signing-cert[Clear the saved development certificate choice used to sign apps for iOS device deployment]' \ + '--android-sdk=[The Android SDK directory]: :_path_files -/' \ + '--android-studio-dir=[The Android Studio install directory]: :_path_files -/' \ + '--jdk-dir=[The Java Development Kit installation directory]: :_path_files -/' \ + '--build-dir=[The relative path to override a projects build directory]: :_path_files -/' \ + '(--no-enable-web --enable-web)--enable-web[Enable Flutter for web]' \ + '(--no-enable-web --enable-web)--no-enable-web[Disable Flutter for web]' \ + '(--no-enable-linux-desktop --enable-linux-desktop)--enable-linux-desktop[Enable support for desktop on Linux]' \ + '(--no-enable-linux-desktop --enable-linux-desktop)--no-enable-linux-desktop[Disable support for desktop on Linux]' \ + '(--no-enable-macos-desktop --enable-macos-desktop)--enable-macos-desktop[Enable support for desktop on macOS]' \ + '(--no-enable-macos-desktop --enable-macos-desktop)--no-enable-macos-desktop[Disable support for desktop on macOS]' \ + '(--no-enable-windows-desktop --enable-windows-desktop)--enable-windows-desktop[Enable support for desktop on Windows]' \ + '(--no-enable-windows-desktop --enable-windows-desktop)--no-enable-windows-desktop[Disable support for desktop on Windows]' \ + '(--no-single-widget-reload-optimization --single-widget-reload-optimization)--single-widget-reload-optimization[Enable Hot reload optimization for a single widget]' \ + '(--no-single-widget-reload-optimization --single-widget-reload-optimization)--no-single-widget-reload-optimization[Disable Hot reload optimization for a single widget]' \ + '(--no-enable-android --enable-android)--enable-android[Enable Flutter for Android]' \ + '(--no-enable-android --enable-android)--no-enable-android[Disable Flutter for Android]' \ + '(--no-enable-ios --enable-ios)--enable-ios[Enable Flutter for iOS]' \ + '(--no-enable-ios --enable-ios)--no-enable-ios[Disable Flutter for iOS]' \ + '(--no-enable-fuchsia --enable-fuchsia)--enable-fuchsia[Enable Flutter for Fuchsia]' \ + '(--no-enable-fuchsia --enable-fuchsia)--no-enable-fuchsia[Disable Flutter for Fuchsia]' \ + '(--no-enable-custom-devices --enable-custom-devices)--enable-custom-devices[Enable Early support for custom device types]' \ + '(--no-enable-custom-devices --enable-custom-devices)--no-enable-custom-devices[Disable Early support for custom device types]' \ + '--clear-features[Remove all configured features and restore them to the default values]' \ + && ret=0 + ;; + + (create) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(--pub --no-pub)--pub[Whether to run "flutter packages get" after the project has been created. (defaults to on)]' \ + '(--pub --no-pub)--no-pub[Whether to run "flutter packages get" after the project has been created. (defaults to on)]' \ + '(--offline --no-offline)--offline[Offline mode when "flutter packages get" is run]' \ + '(--offline --no-offline)--no-offline[Offline mode when "flutter packages get" is run]' \ + '(--overwrite --no-overwrite)--overwrite[When performing operations, overwrite existing files]' \ + '(--overwrite --no-overwrite)--no-overwrite[When performing operations, not overwrite existing files]' \ + "--description=[The description to use for your new Flutter project. (defaults to 'A new Flutter project.')]::" \ + "--org=[The organization responsible for new Flutter project, in reverse domain name notation.(defaults to 'com.example')]::" \ + '--project-name=[The project name for this new Flutter project]:name:' \ + '(-i --ios-language)'{-i,--ios-language=}'[iOS project language]: :_flutter_ios_languages' \ + '(-a --android-language)'{-a,--android-language=}'[Android project language]: :_flutter_android_languages' \ + '--platforms=[The platforms supported by this project]:platforms:_flutter_platforms' \ + '(-t --template=)'{-t,--template=}'[Specify the type of project to create]: :_flutter_project_templates' \ + '(-s --sample=)'{-s,--sample=}'[Specifies the Flutter code sample to use as the "main.dart" for an application]:id:' \ + '(-e --empty)'{-e,--empty}'[Specifies creating using an application template with a main.dart that is minimal]' \ + '--list-samples=[Specifies a JSON output file for a listing of Flutter code samples that can be created with "--sample"]: :_path_files' \ + && ret=0 + ;; + (custom-devices) + _flutter_custom_devices && ret=0 + ;; + (daemon) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--listen-on-tcp-port=[If specified, the daemon will be listening for commands on the specified port instead of stdio]:port:' \ + && ret=0 + ;; + (debug-adapter) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--dds-port=[When this value is provided, the Dart Development Service (DDS) will be bound to the provided port]:port:' \ + '(--no-test --test)--test[use the "flutter test" debug adapter to run tests]' \ + '(--no-test --test)--no-test[not use the "flutter test" debug adapter to run tests]' \ + && ret=0 + ;; + (devices) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--machine[Output device information in machine readable structured JSON format]' \ + "--device-timeout=[Time in seconds to wait for devices to attach]:seconds:" \ + '--device-connection=[Discover devices based on connection type]:type:_flutter_device_connection_types' \ + && ret=0 + ;; + (doctor) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + "--android-licenses[Run the Android SDK manager tool to accept the SDK's licenses]" \ + && ret=0 + ;; + (drive) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--debug[Build a debug version of your app (default mode)]' \ + '--profile[Build a version of your app specialized for performance profiling]' \ + '--release[Build a release version of your app]' \ + '*--dart-define=[Additional key-value pairs that will be available as constants]:' \ + '--flavor[Build a custom app flavor as defined by platform-specific build setup]:flavor' \ + '--web-renderer=[The renderer implementation to use when building for the web]: :_flutter_web_renderers' \ + '--no-web-resources-cdn[Do not use Web static resources hosted on a CDN]' \ + '--trace-startup[Start tracing during startup]' \ + '(--cache-startup-profile --no-cache-startup-profile)--cache-startup-profile[Caches the CPU profile collected before the first frame for startup analysis]' \ + '(--cache-startup-profile --no-cache-startup-profile)--no-cache-startup-profile[Not caches the CPU profile collected before the first frame for startup analysis]' \ + '--verbose-system-logs[Include verbose logging from the Flutter engine]' \ + '--cache-sksl[Cache the shader in the SkSL format instead of in binary or GLSL formats]' \ + '--dump-skp-on-shader-compilation[Cache the shader in the SkSL format instead of in binary or GLSL formats]' \ + '--purge-persistent-cache[Removes all existing persistent caches]' \ + '--route[Which route to load when running the app]' \ + '--use-application-binary=[Specify a pre-built application binary to use when running]::_files -g "*.apk"' \ + '(--no-start-paused --start-paused)--start-paused[Start in a paused mode and wait for a debugger to connect]' \ + '(--no-start-paused --start-paused)--no-start-paused[Not tart in a paused mode and wait for a debugger to connect]' \ + '--endless-trace-buffer[Enable tracing to an infinite buffer, instead of a ring buffer]' \ + '--trace-systrace[Enable tracing to the system tracer]' \ + '--trace-skia[Enable tracing of Skia code]' \ + '--no-enable-dart-profiling[Disable the Dart VM sampling CPU profiler]' \ + '--enable-software-rendering[Enable rendering using the Skia software backend]' \ + '--skia-deterministic-rendering[provide completely deterministic Skia rendering]' \ + *{-a,--dart-entrypoint-args=}'[Pass a list of arguments to the Dart entrypoint at application startup]: :' \ + '--web-launch-url=[The URL to provide to the browser]: :' \ + '(-t --target=)'{-t,--target=}'[The main entry-point file of the application, as run on the device.(defaults to "lib/main.dart")]: :_files -g "*.dart"' \ + '--device-vmservice-port=[Look for vmservice connections only from the specified port]:port:' \ + '--host-vmservice-port=[When a device-side vmservice port is forwarded to a host-side port]:port:' \ + '--pub[Whether to run "flutter packages get" before executing this command. (defaults to on)]' \ + '--no-pub[Whether to run "flutter packages get" before executing this command. (defaults to on)]' \ + '--track-widget-creation[Track widget creation locations. (defaults to on)]' \ + '--no-track-widget-creation[Not rack widget creation locations. (defaults to on)]' \ + '--device-user=[Identifier number for a user or work profile on Android only]:id:' \ + '--device-timeout=[Time in seconds to wait for devices to attach]:seconds:' \ + '--device-connection=[Discover devices based on connection type]:type:_flutter_device_connection_types' \ + '--dds-port=[the Dart Development Service (DDS) will be bound to the provided port]:port:' \ + *{-P,--android-project-arg=}'[Additional arguments specified as key=value that are passed directly to the gradle project]: :' \ + '--multidex[indicates that the app should be built with multidex support(defaults to on)]' \ + '--no-multidex[indicates that the app should not be built with multidex support(defaults to on)]' \ + '--no-keep-app-running[Will not keep the Flutter application running when done testing]' \ + '--keep-app-running[Will keep the Flutter application running when done testing]' \ + '--use-existing-app=[Connect to an already running instance via the given observatory URL]' \ + '--driver=[The test file to run on the host]: :_files' \ + '--build[If necessary, build the app before running. (defaults to on)]' \ + '--no-build[If necessary, not build the app before running]' \ + '--screenshot=[Directory location to write screenshots on test failure]::_path_files -/' \ + '--driver-port=[The port where Webdriver server is launched at(default to "4444")]:port:' \ + '(--no-headless --headless)--headless[Launch driver browser in headless mode(defaults to on)]' \ + '(--no-headless --headless)--no-headless[Not launch driver browser in headless mode]' \ + '--browser-name=[Name of the browser where tests will be executed]: :(android-chrome chrome edge firefox ios-safari safari)' \ + '--browser-dimension=[The dimension of the browser when running a Flutter Web test(defaults to "1600,1024")]: :' \ + '(--no-android-emulator --android-emulator)--android-emulator[Perform Flutter Driver testing using an Android Emulator]' \ + '(--no-android-emulator --android-emulator)--no-android-emulator[Not perform Flutter Driver testing using an Android Emulator]' \ + '--chrome-binary=[Location of the Chrome binary]::_files' \ + '--write-sksl-on-exit[Attempts to write an SkSL file when the drive process is finished to the provided file, overwriting it if necessary]' \ + '*--test-arguments=[Additional arguments to pass to the Dart VM running The test script]: :' \ + '--profile-memory=[Launch devtools and profile application memory, writing the output data as JSON]::_files -g "*.json"' \ + '--timeout=[Timeout the test after the given number of seconds]:seconds' \ + && ret=0 + ;; + (emulators) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--launch[The full or partial ID of the emulator to launch]' \ + '--cold[Used with the "--launch" flag to cold boot the emulator instance (Android only)]' \ + '--create[Creates a new Android emulator based on a Pixel device]' \ + '--name[Used with the "--create" flag. Specifies a name for the emulator being created]' \ + && ret=0 + ;; + (gen-l10n) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--arb-dir=[The directory where template arb files are located]::_path_files -/' \ + '--output-dir=[The directory where the generated localization classes will be written]::_path_files -/' \ + '--template-arb-file=[The path of template arb file]::_files' \ + '--output-localization-file=[The filename for the output localization and localizations delegate classes]::_files -g "*.dart"' \ + '--untranslated-messages-file=[The file that describes the localization messages have not been translated yet]::_files' \ + '--output-class=[The Dart class name to use for the output localization and localizations delegate classes]:class:' \ + '--preferred-supported-locales=[The list of preferred supported locales for the application]::' \ + '--header=[The header to prepend to the generated Dart localizations files]:header:' \ + '--header-file=[The header to prepend to the generated Dart localizations files]::_files' \ + '(--no-use-deferred-loading --use-deferred-loading)--use-deferred-loading[Generate the Dart localization file as deferred]' \ + '(--no-use-deferred-loading --use-deferred-loading)--no-use-deferred-loading[Not generate the Dart localization file as deferred]' \ + '--gen-inputs-and-outputs-list=[the tool generates a JSON file containing the tools inputs and outputs]::_path_files -/' \ + '(--no-synthetic-package --synthetic-package)--synthetic-package[Generate files as a synthetic package]' \ + '(--no-synthetic-package --synthetic-package)--no-synthetic-package[Not generate files as a synthetic package]' \ + '--project-dir=[the directory of the root Flutter project]::_path_files -/' \ + '(--no-required-resource-attributes --required-resource-attributes)--required-resource-attributes[Requires all resource ids to contain a corresponding resource attribute]' \ + '(--no-required-resource-attributes --required-resource-attributes)--no-required-resource-attributes[Requires all resource ids to contain a corresponding resource attribute]' \ + '(--no-nullable-getter --nullable-getter)--nullable-getter[The localizations class getter is nullable]' \ + '(--no-nullable-getter --nullable-getter)--no-nullable-getter[The localizations class getter is not nullable]' \ + '--format["dart format" is run after generating the localization files]' \ + '--use-escaping[use escaping for message]' \ + '--suppress-warnings[all warnings will be suppressed]' \ + && ret=0 + ;; + (install) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--debug[Build a debug version of your app]' \ + '--profile[Build a version of your app specialized for performance profiling]' \ + '--release[Build a release version of your app(default mode)]' \ + '--use-application-binary=[Specify a prebuild application binary to use when running]: :_files -g "*.apk"' \ + '--device-timeout=[Time in seconds to wait for devices to attach]:seconds:' \ + '--device-connection=[Discover devices based on connection type]:type:_flutter_device_connection_types' \ + '--device-user=[Identifier number for a user or work profile on Android only]:id:' \ + '--flavor[Build a custom app flavors as defined by platform-specific build setup]:flavor' \ + '(--no-uninstall-only --uninstall-only)--uninstall-only[Uninstall the app if already on the device. Skip install]' \ + '(--no-uninstall-only --uninstall-only)--no-uninstall-only[Uninstall the app if already on the device. Skip install]' \ + && ret=0 + ;; + (logs) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-c --clear)'{-c,--clear}'[Clear log history before reading from logs]' \ + '--device-timeout=[Time in seconds to wait for devices to attach]:seconds:' \ + '--device-connection=[Discover devices based on connection type]:type:_flutter_device_connection_types' \ + && ret=0 + ;; + (precache) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-a --all-platforms)'{-a,--all-platforms}'[Precache artifacts for all platforms]' \ + '(-f --force)'{-f,--force}'[Force re-downloading of artifacts]' \ + '(--no-ios --ios)--ios[Precache artifacts for iOS development]' \ + '(--no-ios --ios)--no-ios[Not precache artifacts for iOS development]' \ + '(--no-web --web)--web[Precache artifacts for web development]' \ + '(--no-web --web)--no-web[Not precache artifacts for web development]' \ + '(--no-linux --linux)--linux[Precache artifacts for Linux desktop development]' \ + '(--no-linux --linux)--no-linux[Not recache artifacts for Linux desktop development]' \ + '(--no-windows --windows)--windows[Precache artifacts for Windows desktop development]' \ + '(--no-windows --windows)--no-windows[Not precache artifacts for Windows desktop development]' \ + '(--no-macos --macos)--macos[Precache artifacts for macOS desktop development]' \ + '(--no-macos --macos)--no-macos[Not precache artifacts for macOS desktop development]' \ + '(--no-fuchsia --fuchsia)--fuchsia[Precache artifacts for Fuchsia development]' \ + '(--no-fuchsia --fuchsia)--no-fuchsia[Not precache artifacts for Fuchsia development]' \ + '(--no-universal --universal)--universal[Precache artifacts required for any development platform]' \ + '(--no-universal --universal)--no-universal[Not precache artifacts required for any development platform]' \ + && ret=0 + ;; + (pub) + _flutter_pub && ret=0 + ;; + (run) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--debug[Build a debug version of your app (default mode)]' \ + '--profile[Build a version of your app specialized for performance profiling]' \ + '--release[Build a release version of your app]' \ + '*--dart-define=[Additional key-value pairs that will be available as constants]: ' \ + '--flavor[Build a custom app flavor as defined by platform-specific build setup]:flavor' \ + '--web-renderer=[The renderer implementation to use when building for the web]: :_flutter_web_renderers' \ + '--no-web-resources-cdn[Do not use Web static resources hosted on a CDN]' \ + '--use-application-binary=[Specify a pre-built-application binary to use when running]: :_files' \ + '--trace-startup[Start tracing during startup]' \ + '(--cache-startup-profile --no-cache-startup-profile)--cache-startup-profile[Caches the CPU profile collected before the first frame for startup analysis]' \ + '(--cache-startup-profile --no-cache-startup-profile)--no-cache-startup-profile[Not caches the CPU profile collected before the first frame for startup analysis]' \ + '--verbose-system-logs[Include verbose logging from the Flutter engine]' \ + '--cache-sksl[Cache the shader in the SkSL format instead of in binary or GLSL formats]' \ + '--dump-skp-on-shader-compilation[Cache the shader in the SkSL format instead of in binary or GLSL formats]' \ + '--purge-persistent-cache[Removes all existing persistent caches]' \ + '--route[Which route to load when running the app]' \ + '(--no-start-paused --start-paused)--start-paused[Start in a paused mode and wait for a debugger to connect]' \ + '(--no-start-paused --start-paused)--no-start-paused[Not start in a paused mode and wait for a debugger to connect]' \ + '--endless-trace-buffer[Enable tracing to an infinite buffer, instead of a ring buffer]' \ + '--trace-systrace[Enable tracing to the system tracer]' \ + '--trace-skia[Enable tracing of Skia code]' \ + '--no-enable-dart-profiling[Disable the Dart VM sampling CPU profiler]' \ + '--enable-software-rendering[Enable rendering using the Skia software backend]' \ + '--skia-deterministic-rendering[When combined with --enable-software-rendering, provides 100% deterministic Skia rendering]' \ + *{-a,--dart-entrypoint-args=}'[Pass a list of arguments to the Dart entrypoint at application startup]: :' \ + '--web-launch-url=[The URL to provide to the browser]: :' \ + '(-t= --target=)'{-t=,--target=}'[The main entry-point file of the application, as run on the device.(defaults to "lib/main.dart")]: :_files -g "*.dart"' \ + '--device-vmservice-port=[Look for vmservice connections only from the specified port]:port:' \ + '--host-vmservice-port=[When a device-side vmservice port is forwarded to a host-side port]:port:' \ + '--pub[Whether to run "flutter packages get" before executing this command. (defaults to on)]' \ + '--no-pub[Whether to run "flutter packages get" before executing this command. (defaults to on)]' \ + '--track-widget-creation[Track widget creation locations. (defaults to on)]' \ + '--no-track-widget-creation[Not rack widget creation locations. (defaults to on)]' \ + '--device-user=[Identifier number for a user or work profile on Android only]:id:' \ + '--device-timeout=[Time in seconds to wait for devices to attach]:seconds:' \ + '--device-connection=[Discover devices based on connection type]: :_flutter_device_connection_types' \ + '--dds-port=[When this value is provided, the Dart Development Service (DDS) will be bound to the provided port]:port:' \ + *{-P,--android-project-arg=}'[Additional arguments specified as key=value that are passed directly to the gradle project via the -P flag]: :' \ + '--multidex[indicates that the app should be built with multidex support(defaults to on)]' \ + '--no-multidex[indicates that the app should not be built with multidex support(defaults to on)]' \ + '--ignore-deprecation[Indicates that the app should ignore deprecation warnings and continue to build using deprecated APIs]' \ + '--no-await-first-frame-when-tracing[Just dump the trace as soon as the application is running]' \ + '--use-test-fonts[Enable (and default to) the "Ahem" font]' \ + '--no-use-test-fonts[Not enable (and default to) the "Ahem" font]' \ + '--no-build[Do not build the app before running]' \ + '--no-hot[Run without support for hot reloading]' \ + '--pid-file=[Specify a file to write the process id to]: :_files' \ + && ret=0 + ;; + (screenshot) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-o --out)'{-o,--out=}'[Location to write the screenshot]: :_files' \ + '--vm-service-url=[The VM Service URL to which to connect]' \ + '--type=[The type of screenshot to retrieve]:type:(device rasterizer skia)' \ + '--device-timeout=[Time in seconds to wait for devices to attach]:seconds:' \ + '--device-connection=[Discover devices based on connection type]:type:_flutter_device_connection_types' \ + && ret=0 + ;; + (symbolize) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-d --debug-info)'{-d,--debug-info=}'[A path to the symbols file generated with "--split-debug-info"]: :_files' \ + '(-i --input)'{-i,--input=}'[A file path containing a Dart stack trace]: :_files' \ + '(-o --output)'{-o,--output=}'[A file path for a symbolized stack trace to be written to]: :_files' \ + && ret=0 + ;; + (test) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--pub[Run "flutter packages get" before executing this command(defaults to on)]' \ + '--no-pub[Not to run "flutter packages get" before executing this command]' \ + '--track-widget-creation[Track widget creation locations]' \ + '--no-track-widget-creation[Not track widget creation locations]' \ + '*--dart-define=[Additional key-value pairs that will be available as constants]:' \ + '--dart-define-from-file=[The path of a json format file where flutter define a global constant pool]: :_files -g "*.json"' \ + '--web-renderer=[The renderer implementation to use when building for the web]: :_flutter_web_renderers' \ + '--device-user=[Identifier number for a user or work profile on Android only]:id:' \ + '--flavor[Build a custom app flavor as defined by platform-specific build setup]:flavor' \ + '--name=[A regular expression matching substrings of the names of tests to run]' \ + '--plain-name=[A plain-text substring of the names of tests to run]' \ + *{-t,--tags=}'[Run only tests associated with the specified tags]:tag:' \ + *{-x,--exclude-tags=}'[Run only tests that do not have the specified tags]:tag:' \ + '--start-paused[Start in a paused mode and wait for a debugger to connect]' \ + '(--no-run-skipped --run-skipped)--run-skipped[Run skipped tests instead of skipping them]' \ + '(--no-run-skipped --run-skipped)--no-run-skipped[Not run skipped tests instead of skipping them]' \ + '--coverage[Whether to collect coverage information]' \ + '--merge-coverage[Whether to merge coverage data with "coverage/lcov.base.info" (Requires lcov)]' \ + '--branch-coverage[Whether to collect branch coverage information]' \ + '--coverage-path=[Where to store coverage information (if coverage is enabled). (defaults to "coverage/lcov.info")]::_files' \ + '--update-goldens[Whether "matchesGoldenFile()" calls within your test methods should update the golden files]' \ + '(-j --concurrency)'{-j,--concurrency=}'[The number of concurrent test processes to run]:nums:' \ + '(--test-assets --no-test-assets)--test-assets[Build the assets bundle for testing]' \ + '(--test-assets --no-test-assets)--no-test-assets[Not build the assets bundle for testing]' \ + '--test-randomize-ordering-seed[The seed to randomize the execution order of test cases within test files]' \ + '--total-shards[Tests can be sharded with the "--total-shards" and "--shard-index" arguments]' \ + '--shard-index[Tests can be sharded with the "--total-shards" and "--shard-index" arguments]' \ + {-r,--reporter=}'[Set how to print test results]: :(compact expanded github json)' \ + '--file-reporter[Enable an additional reporter writing test results to a file]' \ + '--timeout=[The default test timeout, specified either in seconds (e.g. "60s"). Defaults to "30s"]:seconds:' \ + '--dds-port=[the Dart Development Service (DDS) will be bound to the provided port]:port:' \ + && ret=0 + ;; + (upgrade) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-f --force)'{-f,--force}'[Force upgrade the flutter branch, potentially discarding local changes]' \ + '--verify-only[Checks for any new Flutter updates, without actually fetching them]' \ + && ret=0 + ;; + (*) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + && ret=0 + ;; + esac + ;; + esac + + return ret +} + +(( $+functions[_flutter_root_commands] )) || +_flutter_root_commands() { + local -a commands=( + "analyze:Analyze the project's Dart code." + 'assemble:Assemble and build flutter resources.' + 'attach:Attach to a running application.' + 'bash-completion:Output command line shell completion setup scripts.' + 'build:Flutter build commands.' + 'channel:List or switch flutter channels.' + 'clean:Delete the build/ directory.' + 'config:Configure Flutter settings.' + 'create:Create a new Flutter project.' + 'custom-devices:List, reset, add and delete custom devices' + 'daemon:Run a persistent, JSON-RPC based server to communicate with devices.' + 'debug-adapter:Run a Debug Adapter Protocol server to communicate with the Flutter tool' + 'downgrade:Downgrade Flutter to the last active version for the current channel' + 'devices:List all connected devices.' + 'doctor:Show information about the installed tooling.' + 'drive:Runs Flutter Driver tests for the current project.' + 'emulators:List, launch and create emulators.' + 'gen-l10n:Generate localizations for the current project.' + 'help:Display help information for flutter.' + 'install:Install a Flutter app on an attached device.' + 'logs:Show log output for running Flutter apps.' + "precache:Populates the Flutter tool's cache of binary artifacts." + 'pub:Commands for managing Flutter packages.' + 'run:Run your Flutter app on an attached device.' + 'screenshot:Take a screenshot from a connected device.' + 'symbolize:Symbolize a stack trace from an AOT-compiled Flutter app.' + 'test:Run Flutter unit tests for the current project.' + 'upgrade:Upgrade your copy of Flutter.' + ) + _describe -t commands 'command' commands "$@" +} + +(( $+functions[_flutter_build] )) || +_flutter_build() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_flutter_build_entities' \ + '*:: :->args' \ + && ret=0 + + case $state in + (args) + local opts=( + '(- *)'{-h,--help}'[Print this usage information]' + '(--debug --profile --release)--debug[Build a debug version of your app]' + '(--debug --profile --release)--profile[Build a version of your app specialized for performance profiling]' + '(--debug --profile --release)--release[Build a release version of your app(default mode)]' + '--no-tree-shake-icons[Not use Tree shake icon fonts]' + '--flavor[Build a custom app flavor as defined by platform-specific build setup]:flavor' + '--build-number[An identifier used as an internal version number]:build_number' + '(-o --output)'{-o,--output}'[The absolute path to the directory where the repository is generated]:dir:_files -/' + '(--no-pub)--pub[Run "flutter pub get" before executing this command]' + '(--pub)--no-pub[Do not run "flutter pub get" before executing this command]' + '--split-debug-info[Split debug info]: :_files -/' + '--obfuscate[Remove identifiers and replace them with randomized values for code obfuscation]' + '*--dart-define=[Additional key-value pairs that will be available as constants]:' + '--dart-define-from-file=[The path of a json format file where flutter define a global constant pool]: :_files -g "*.json"' + '--no-track-widget-creation[Not track widget creation locations]' + '(--no-null-assertions)--null-assertions[Perform additional null assertions on the boundaries of migrated and un-migrated code]' + '(--null-assertions)--no-null-assertions[Not perform additional null assertions on the boundaries of migrated and un-migrated code]' + + ) + case $words[1] in + (aar) + opts+=( + '--target-platform=[The target platform for which the project is compiled]: :(android-arm android-arm64 android-x86 android-x64)' + \*{-P,--android-project-arg}'[Additioanl arguments specified as key=value that are passed to gradle -P option]:arg' + ) + ;; + (apk|appbundle) + opts+=( + '--build-name=[A string used as the version number shown to users]:build_name' + '(--no-analyze-size)--analyze-size[Produce additional profile information for artifact output size]' + '(--analyze-size)--no-analyze-size[Not produce additional profile information for artifact output size]' + '--code-size-directory=[The location to write code size analysis files]: :_files -/' + \*{-P,--android-project-arg}'[Additioanl arguments specified as key=value that are passed to gradle -P option]:arg' + '--no-multidex[the app is not built with multidex support]' + '--ignore-deprecation[the app should ignore deprecation warnings and continue to build using deprecated APIs]' + '--split-per-abi[Split the APKs per ABIs]' + '--target-platform=[The target platform for which the project is compiled]: :(android-arm android-arm64 android-x86 android-x64)' + ) + if [[ $words[1] == "apk" ]]; then + opts+=( + '--config-only[Generate build files used by flutter but do not build any artifacts]' + ) + else + opts+=( + '--no-deferred-components[Disable building with deferred components]' + '--no-validate-deferred-components[Do not validate deferred component]' + ) + fi + ;; + (bundle) + opts+=( + '--depfile[A file path where a depfile will be written]:depfile:_files' + '--target-platform=[The target platform for which the project is compiled]: :(android-arm android-arm64 android-x86 android-x64)' + '--asset-dir[The output directory for the kernel_blob.bin file]: :_files -/' + ) + ;; + (fuchsia) + ;; + (ios) + opts+=( + '--code-size-directory=[The location to write code size analysis files]: :_files -/' + '--no-codesign[Do not codesign the application bundle]' + '--config-only[Update the project configuration without performing a build]' + '--simulator[Build for the iOS simulator instead of the device]' + ) + ;; + (linux) + opts+=( + '(--no-analyze-size)--analyze-size[Produce additional profile information for artifact output size]' + '(--analyze-size)--no-analyze-size[Not produce additional profile information for artifact output size]' + '--code-size-directory=[The location to write code size analysis files]: :_files -/' + '(-t --target)'{-t,--target=}'[The main entry-point file of the application]:file:_files' + '--build-name=[A string used as the version number shown to users]:build_name' + '--target-platform=[The target platform for which the project is compiled]: :(linux-arm64 linux-x64)' + '--target-sysroot=[The root filesystem path of target platform]: :_files -/' + ) + ;; + (macos) + opts+=( + '--build-name=[A string used as the version number shown to users]:build_name' + '--config-only[Update the project configuration without performing a build]' + ) + ;; + (web) + opts+=( + '(-t --target)'{-t,--target=}'[The main entry-point file of the application]:file:_files' + '--no-native-null-assertions[Disable additional runtime null checks in web applications]' + '--base-href[Overrides the href attribute of the base tag in web/index.html]' + '--pwa-strategy=[The caching strategy to be used by the PWA service worker]: :(none offline-first)' + '--web-renderer=[The renderer implementation to use when building for the web]: :_flutter_web_renderers' + '(--no-web-resources-cdn)--web-resources-cdn[Use Web static resources hosted on a CDN]' + '(--web-resources-cdn)--no-web-resources-cdn[Do not Web static resources hosted on a CDN]' + '--csp[Disable dynamic generation of code in the generated output]' + '(--no-source-maps)--source-maps[Generate a sourcemap file]' + '(--source-maps)--no-source-maps[Do not generate a sourcemap file]' + '--dart2js-optimization=[Sets the optimization level used for Dart compilation to JavaScript]: :(O0 O1 O2 O3 O4)' + '--dump-info[Passes "--dump-info" to the JavaScript compiler]' + '--no-frequency-based-minification[Disables the frequency based minifier]' + ) + ;; + (windows) + opts+=( + '--build-name=[A string used as the version number shown to users]:build_name' + ) + ;; + esac + + _arguments $opts && ret=0 + ;; + esac + + return ret +} + +(( $+functions[_flutter_build_entities] )) || +_flutter_build_entities() { + local -a entities=( + "aar:Build a repository containing an AAR and a POM file." + "apk:Build an Android APK file from your app." + "appbundle:Build an Android App Bundle file from your app." + "bundle:Build the Flutter assets directory from your app." + "fuchsia:Build the Fuchsia target." + "ios:Build an iOS application bundle (Mac OS X host only)." + "linux:Build a Linux desktop application." + "macos:Build a macOS desktop application." + "web:Build a web application bundle" + "windows:Build a Windows desktop application." + ) + _describe -t entities 'entity' entities "$@" +} + +(( $+functions[_flutter_custom_devices] )) || +_flutter_custom_devices() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_flutter_custom_devices_subcommands' \ + '*:: :->args' \ + && ret=0 + + case $state in + (args) + case $words[1] in + (add) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--check[Make sure the config actually works]' \ + '--json=[Add the custom device described by this JSON encoded string]:json' \ + '--ssh[Add a ssh-device]' \ + && ret=0 + ;; + (*) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + && ret=0 + esac + ;; + esac + + return ret +} + +(( $+functions[_flutter_custom_devices_subcommands] )) || +_flutter_custom_devices_subcommands() { + local -a subcmds=( + "add:Add a new device the custom devices config file" + "delete:Delete a device from the config file" + "list:List the currently configured custom devices, both enabled and disabled, reachable or not" + "reset:Reset the config file to the default" + ) + _describe -t subcmds 'subcommands' subcmds "$@" +} + +(( $+functions[_flutter_project_templates] )) || +_flutter_project_templates() { + local -a templates=( + "app:(default) Generate a Flutter application" + "module:Generate a shareable Flutter project containing modular Dart code" + "package:Generate a shareable Flutter project containing modular Dart code" + "plugin:Generate a shareable Flutter project containing an API in Dart code with a platform-specific implementation for Android, for iOS code, or for both" + "plugin_ffi:Generate a shareable Flutter project containing an API in Dart code with a platform-specific implementation through dart:ffi for Android, iOS, Linux, macOS, Windows, or any combination of these" + "skeleton:Generate a List View / Detail View Flutter application that follows community best practices" + ) + _describe -t templates 'template' templates "$@" +} + +(( $+functions[_flutter_platforms] )) || +_flutter_platforms() { + local -a platforms=("ios" "android" "windows" "linux" "macos" "web") + _values -s , "platforms" $platforms +} + +(( $+functions[_flutter_ios_languages] )) || +_flutter_ios_languages() { + local -a languages=( + "objc:Objective-C" + "swift:(default) Swift" + ) + _describe -t languages 'language' languages "$@" +} + +(( $+functions[_flutter_android_languages] )) || +_flutter_android_languages() { + local -a languages=( + "java:Java" + "kotlin:(default) Kotlin" + ) + _describe -t languages 'language' languages "$@" +} + +(( $+functions[_flutter_pub] )) || +_flutter_pub() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_flutter_pub_subcommands' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (add|remove) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--offline[Use cached packages instead of accessing the network]' \ + '(-n --dry-run)'{-n,--dry-run}'[Report what dependencies would change but do not change any]' \ + '--precompile[Build executables in immediate dependencies]' \ + '(-C --directory)'{-C,--directory=}'[Run this in the given directory]:dir:_files -/' \ + && ret=0 + ;; + (cache) + _flutter_pub_cache && ret=0 + ;; + (deps) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-s --style)'{-s,--style=}'[How output should be displayed]:style:(tree list compact)' \ + '(--no-dev)--dev[Include dev dependencies]' \ + '(--dev)--no-dev[Not include dev dependencies]' \ + '--executables[List all available executables]' \ + '--json[Output dependency information in a json format]' \ + '(-C --directory)'{-C,--directory=}'[Run this in the given directory]:dir:_files -/' \ + && ret=0 + ;; + (downgrade) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--offline[Use cached packages instead of accessing the network]' \ + '(-n --dry-run)'{-n,--dry-run}'[Report what dependencies would change but do not change any]' \ + '(-C --directory)'{-C,--directory=}'[Run this in the given directory]:dir:_files -/' \ + && ret=0 + ;; + (get) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--offline[Use cached packages instead of accessing the network]' \ + '(-n --dry-run)'{-n,--dry-run}'[Report what dependencies would change but do not change any]' \ + '--enforce-lockfile[Enforce pubspec.lock]' \ + '--precompile[Build executables in immediate dependencies]' \ + '(-C --directory)'{-C,--directory=}'[Run this in the given directory]:dir:_files -/' \ + && ret=0 + ;; + (global) + _flutter_pub_global && ret=0 + ;; + (outdated) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(--no-dependency-overrides)--dependency-overrides[Show resolution with `dependency_overrides`]' \ + '(--dependency-overrides)--no-dependency-overrides[Not show resolution with `dependency_overrides`]' \ + '(--no-dev-dependencies)--dev-dependencies[Take the dependencies into account]' \ + '(--dev-dependencies)--no-dev-dependencies[Not take the dependencies into account]' \ + '--json[Output the results using a json format]' \ + '(--no-prereleases)--prereleases[Include prereleases in latest version]' \ + '(--prereleases)--no-prereleases[Not include prereleases in latest version]' \ + '--show-all[Include dependencies that are already fulfilling --mode]' \ + '--transitive[Show transitive dependencies]' \ + '(-C --directory)'{-C,--directory=}'[Run this in the given directory]:dir:_files -/' \ + && ret=0 + ;; + (publish) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-n --dry-run)'{-n,--dry-run}'[Report what dependencies would change but do not change any]' \ + '(-f --force)'{-f,--force}'[Publish without confirmation if there are no errors]' \ + '--skip-validation[Publish without validation and resolution]' \ + '(-C --directory)'{-C,--directory=}'[Run this in the given directory]:dir:_files -/' \ + && ret=0 + ;; + (run) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--enable-asserts[Enable assert statements]' \ + '--enable-experiment=[Run the executable in a VM with the given experiments enabled]:experiment' \ + '(-C --directory)'{-C,--directory=}'[Run this in the given directory]:dir:_files -/' \ + && ret=0 + ;; + (token) + _flutter_pub_token && ret=0 + ;; + (upgrade) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--offline[Use cached packages instead of accessing the network]' \ + '(-n --dry-run)'{-n,--dry-run}'[Report what dependencies would change but do not change any]' \ + '--precompile[Build executables in immediate dependencies]' \ + '--major-versions[Upgrades packages to their latest resolvable versions]' \ + '(-C --directory)'{-C,--directory=}'[Run this in the given directory]:dir:_files -/' \ + && ret=0 + ;; + (uploader) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--package=[The package whose uploaders will be modified]:package' \ + '(-C --directory)'{-C,--directory=}'[Run this in the given directory]:dir:_files -/' \ + && ret=0 + ;; + (*) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + && ret=0 + esac + ;; + esac + + return ret +} + +(( $+functions[_flutter_pub_subcommands] )) || +_flutter_pub_subcommands() { + local -a subcommands=( + "add:Add a dependency to pubspec.yaml" + "cache:Work with the Pub system cache" + "deps:Print package dependencies" + "downgrade:Downgrade packages in a Flutter project" + "get:Get packages in a Flutter project" + "global:Work with Pub global packages" + "login:Log into pub.dev" + "logout:Log out of pub.dev" + "outdated:Analyze dependencies to find which ones can be upgraded" + "pub:Pass the remaining arguments to Dart's 'pub' tool" + "publish:Publish the current package to pub.dartlang.org" + "remove:Removes a dependency from the current package" + "run:Run an executable from a package" + "test:Run the 'test' package" + "token:Manage authentication tokens for hosted pub repositories" + "upgrade:Upgrade the current package's dependencies to latest versions" + "uploader:Manage uploaders for a package on pub.dev" + "version:Print Pub version" + ) + _describe -t subcommands 'subcommand' subcommands "$@" +} + +(( $+functions[_flutter_pub_cache] )) || +_flutter_pub_cache() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_flutter_pub_cache_subcommand' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (add) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--all[Install all matching versions]'\ + '(-v --version)'{-v,--version}'[Version constraint]:version' \ + && ret=0 + ;; + (clean) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-f --force)'{f,--force}'[Do not ask for confirmation]' \ + && ret=0 + ;; + (repair) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + && ret=0 + ;; + esac + ;; + esac + + return ret +} + +(( $+functions[_flutter_pub_cache_subcommand] )) || +_flutter_pub_cache_subcommand() { + local -a subcommands=( + "add:Install a package" + "clean:Clears the global PUB_CACHE" + "repair:Reinstall cached packages" + ) + _describe -t subcommands 'subcommand' subcommands "$@" +} + +(( $+functions[_flutter_pub_global] )) || +_flutter_pub_global() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_flutter_pub_global_subcommand' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (activate) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-s --source)'{-s,--source}'[The source used to find the package]:source:(git hosted path)' \ + '--git-path[Path of git package in repository]:path' \ + '--git-ref[Git branch or commit to bbe retrieved]:ref' \ + '(-x --executable)--no-executables[Do not put executables on PATH]' \ + '(--no-executables)'{-x,--executable}'[Executables to place on PATH]' \ + '--overwrite[Overwrite executables from other packages with the same name]' \ + '(-u --hosted-url)'{-u,--hosted-url}'[A custom pub server URL for the package]:URL' \ + && ret=0 + ;; + (run) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--enable-asserts[Enable assert statements]' \ + '--enable-experiment=[Run the executable in a VM with the given experiments enabled]' \ + && ret=0 + ;; + (*) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + && ret=0 + esac + ;; + esac + + return ret +} + +(( $+functions[_flutter_pub_global_subcommand] )) || +_flutter_pub_global_subcommand() { + local -a subcommands=( + "activate:Make a package's executables globally available" + "deactivate:Remove a previously activated package" + "list:List globally activated packages" + "run:Run an executable from a globally activated package" + ) + _describe -t subcommands 'subcommand' subcommands "$@" +} + +(( $+functions[_flutter_pub_token] )) || +_flutter_pub_token() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_flutter_pub_token_subcommand' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (add) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--env-var[Read the secret token from this environment variable when making requests]:env' \ + && ret=0 + ;; + (remove) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--all[Remove all secret tokens]' \ + && ret=0 + ;; + (*) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + && ret=0 + esac + ;; + esac + + return ret +} + +(( $+functions[_flutter_pub_token_subcommand] )) || +_flutter_pub_token_subcommand() { + local -a subcommands=( + "add:Add authentication tokens for a package repository" + "list:List servers for which a token exists" + "remove:Remove secret token for package repository" + ) + _describe -t subcommands 'subcommand' subcommands "$@" +} + +(( $+functions[_flutter_web_renderers] )) || +_flutter_web_renderers() { + local -a renderers=( + 'auto:HTML renderer on mobile devices' + 'canvaskit:CanvasKit renderer' + 'html:HTML renderer' + 'skwasm:Experimental skwasm renderer' + ) + _describe -t renderers 'renderers' renderers "$@" +} + +(( $+functions[_flutter_device_connection_types] )) || +_flutter_device_connection_types() { + local -a types=( + 'attached:Only searches for devices connected by USB or built-in' + 'both:Searches for both attached and wireless devices' + 'wireless:Only searches for devices connected wirelessly' + ) + _describe -t types 'types' types "$@" +} + +_flutter "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fvm b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fvm new file mode 100644 index 00000000..e522d063 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fvm @@ -0,0 +1,198 @@ +#compdef fvm +# ------------------------------------------------------------------------------ +# Copyright (c) 2022 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for fvm. (https://github.com/fluttertools/fvm) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_fvm() { + typeset -A opt_args + local context state line + local curcontext="$curcontext" + local ret=1 + + _arguments -C -A "-*" \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--verbose[Print verbose output]' \ + '(- *)--version[current version]' \ + '1: :_fvm_subcommands' \ + '*::arg:->args' \ + && ret=0 + + case "$state" in + (args) + case $words[1] in + (help) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '1: :_fvm_subcommands' \ + && ret=0 + ;; + (config) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-c --cache-path)'{-c,--cache-path}'[Set the path which FVM will cache the version.Priority over FVM_HOME]::_path_files -/' \ + '(-s --skip-setup --no-skip-setup)'{-s,--skip-setup}'[Skip setup after a version install]' \ + '(-s --skip-setup --no-skip-setup)--no-skip-setup[No skip setup after a version install]' \ + '(-g --git-cache --no-git-cache)'{-g,--git-cache}'[Will cache a local version of Flutter repo for faster version install]' \ + '(-g --git-cache --no-git-cache)--no-git-cache[Will not cache a local version of Flutter repo for faster version install]' \ + && ret=0 + ;; + (destroy|doctor|flavor|list|releases) + _arguments -C \ + '(- *)'{-h,--help}'[Print this usage information]' \ + && ret=0 + ;; + (dart) + _arguments \ + '1: :_fvm_run_dart' \ + '*: :_normal' \ + && ret=0 + ;; + (exec) + _arguments \ + '*::args:_normal' \ + && ret=0 + ;; + (flutter) + _arguments \ + '1: :_fvm_run_flutter' \ + '*: :_normal' \ + && ret=0 + ;; + (global) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '*::args:_fvm_installed_versions' \ + && ret=0 + ;; + (install) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-s --skip-setup)'{-s,--skip-setup}'[Skips Flutter setup after install]' \ + '1: :_fvm_versions' \ + && ret=0 + ;; + (remove) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '--force[Skips version global check]' \ + '1: :_fvm_installed_versions' \ + && ret=0 + ;; + (spawn) + _arguments \ + '1: :_fvm_installed_versions' \ + '2: :_fvm_run_flutter' \ + '*: :_normal' \ + && ret=0 + ;; + (use) + _arguments \ + '(- *)'{-h,--help}'[Print this usage information]' \ + '(-f --force)'{-f,--force}'[Skips command guards that does Flutter project checks]' \ + '(-p --pin)'{-p,--pin}'[If version provided is a channel. Will pin the latest release of the channel]' \ + '--flavor[Sets version for a project flavor]' \ + '(-s --skip-setup)'{-s,--skip-setup}'[Skips Flutter setup after install]' \ + '1: :_fvm_installed_versions' \ + && ret=0 + ;; + esac + ;; + esac + + return ret +} + +(( $+functions[_fvm_subcommands] )) || +_fvm_subcommands() { + local -a commands=( + 'config:Set configuration for FVM' + 'dart:Proxies Dart Commands' + 'destroy:Destroy FVM cache by deleting FVM directory' + 'doctor:Shows information about environment, and project configuration' + 'exec:Executes scripts with the configured Flutter SDK' + 'flavor:Switches between different project flavors' + 'flutter:Proxies Flutter Commands' + 'global:Sets Flutter SDK Version as a global' + 'install:Installs Flutter SDK version' + 'list:Lists installed Flutter SDK Versions' + 'releases:View all Flutter SDK releases available for install' + 'remove:Removes Flutter SDK Version' + 'spawn:Spawns a command on a Flutter version' + 'use:Sets Flutter SDK Version you would like to use in a project' + ) + _describe -t commands 'command' commands "$@" +} + +(( $+functions[_fvm_versions] )) || +_fvm_versions() { + local -a versions + versions=($(fvm releases | awk '/[0-9]+\.[0-9]+\.[0-9]+/{ sub(/^[^│]*│ /, ""); print $1}')) + versions=(master beta stable $versions) + _describe 'versions' versions +} + +(( $+functions[_fvm_installed_versions] )) || +_fvm_installed_versions() { + local -a versions + versions=($(fvm list | sed -e '1,2d')) + _describe 'installed_versions' versions +} + +(( $+functions[_fvm_run_flutter] )) || +_fvm_run_flutter() { + local begin=$(($CURRENT - 1)) + if (( $+functions[_flutter] )); then + compset -n $begin + _flutter "$@" + fi +} + +(( $+functions[_fvm_run_dart] )) || +_fvm_run_dart() { + local begin=$(($CURRENT - 1)) + if (( $+functions[_dart] )); then + compset -n $begin + _dart "$@" + fi +} + +_fvm "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fwupdmgr b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fwupdmgr new file mode 100644 index 00000000..f02280fb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_fwupdmgr @@ -0,0 +1,179 @@ +#compdef fwupdmgr +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for fwupdmgr 1.8.12 (https://github.com/hughsie/fwupd). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_fwupdmgr() { + local context state state_descr line + typeset -A opt_args + local ret=1 + + _arguments -C \ + '(- : *)'{-h,--help}'[display help information]' \ + '(- : *)'{-v,--version}'[display version information]' \ + {-v,--verbose}'[show extra debugging information]' \ + --offline'[schedule installation for next reboot when possible]' \ + --allow-reinstall'[allow re-installing existing firmware versions]' \ + --allow-older'[allow downgrading firmware versions]' \ + --allow-branch-switch'[allow switching firmware branch]' \ + --force'[override warnings and force the action]' \ + '(-y, --assume-yes)'{-y,--assume-yes}'[answer yes to all questions]' \ + --sign'[sign the uploaded data with the client certificate]' \ + --no-unreported-check'[do not check for unreported history]' \ + --no-metadata-check'[do not check for old metadata]' \ + --no-reboot-check'[do not check for reboot after update]' \ + --no-safety-check'[do not perform device safety checks]' \ + --no-device-prompt'[do not prompt for devices]' \ + --no-history'[do not write to the history database]' \ + --show-all'[show all results]' \ + --disable-ssl-strict'[ignore SSL strict checks when downloading files]' \ + --ipfs'[only use IPFS when downloading files]' \ + --filter'[filter with a set of device flags using a ~ prefix to exclude]:filter' \ + --json'[output in JSON format]' \ + --no-authenticate'[do not prompt for authentication]' \ + '(-): :->command' \ + '(-)*:: :->arguments' \ + && ret=0 + + case $state in + (command) + _fwupdmgr_commands + ;; + (arguments) + case $words[1] in + (activate|downgrade|emulation-tag|emulation-untag|get-releases|get-updates|reinstall|update|verify|verify-update) + _arguments \ + '1::device_id or GUID:_fwupdmgr_device_ids' \ + && ret=0 + ;; + (clear-results|get-results|unlock) + _arguments \ + '1:device_id or GUID:_fwupdmgr_device_ids' \ + && ret=0 + ;; + (device-emulate|device-test|emulation-load|emulation-save|get-details|set-approved-firmware) + _arguments \ + '*::files:_files' \ + && ret=0 + ;; + (disable-remote|modify-remote) + _arguments \ + '1:remote ID:_fwupdmgr_remote_ids' \ + && ret=0 + ;; + (install) + _arguments \ + '1:device_id or GUID:_fwupdmgr_device_ids' \ + '2:version' \ + && ret=0 + ;; + (local-install) + _arguments \ + '1:file:_files' \ + '2:device_id or GUID:_fwupdmgr_device_ids' \ + && ret=0 + ;; + (refresh) + _arguments \ + '1:file or remote ID:_alternative _files _fwupdmgr_remote_ids' \ + && ret=0 + ;; + (switch-branch) + _arguments \ + '1:device_id or GUID:_fwupdmgr_device_ids' \ + '2:branch' \ + && ret=0 + ;; + esac + ;; + esac + + return ret +} + +(( $+functions[_fwupdmgr_commands] )) || +_fwupdmgr_commands() { + local -a commands=( + 'activate:activate devices' + 'block-firmware:blocks a specific firmware from being installed' + 'clear-results:clears the results from the last update' + 'device-emulate:emulate a device using a JSON manifest' + 'device-test:test a device using a JSON manifest' + 'disable-remote:disables a given remote' + 'downgrade:downgrades the firmware on a device' + 'emulation-load:load device emulation data' + 'emulation-save:save device emulation data' + 'emulation-tag:adds devices to watch for future emulation' + 'emulation-untag:removes devices to watch for future emulation' + 'enable-remote:enables a given remote' + 'get-approved-firmware:gets the list of approved firmware' + 'get-bios-settings:retrieve BIOS settings' + 'get-blocked-firmware:gets the list of blocked firmware' + 'get-details:gets details about a firmware file' + 'get-devices:get all devices that support firmware updates' + 'get-history:show history of firmware updates' + 'get-plugins:get all enabled plugins registered with the system' + 'get-releases:gets the releases for a device' + 'get-remotes:gets the configured remotes' + 'get-results:gets the results from the last update' + 'get-topology:get all devices according to the system topology' + 'get-updates:gets the list of updates for connected hardware' + 'inhibit:inhibit the system to prevent upgrades' + 'install:install a firmware file on this hardware' + 'local-install:install a firmware file on this hardware' + 'modify-config:modifies a daemon configuration value' + 'modify-remote:modifies a given remote' + 'quit:asks the daemon to quit' + 'refresh:refresh metadata from remote server' + 'security:gets the host security attributes' + 'report-history:share firmware history with the developers' + 'set-approved-firmware:sets the list of approved firmware' + 'set-bios-setting:sets one or more BIOS settings' + 'switch-branch:switch the firmware branch on device' + 'sync-bkc:sync firmware versions to the host best known configuration ' + 'unblock-firmware:unblocks a specific firmware from being installed' + 'uninhibit:uninhibit the system to allow upgrades' + 'unlock:unlocks the device for firmware access' + 'update:updates all firmware to latest versions available' + 'verify:gets the cryptographic hash of the dumped firmware' + 'verify-update:update the stored metadata with current ROM contents' + ) + _describe -t commands commands commands +} + +(( $+functions[_fwupdmgr_device_ids] )) || +_fwupdmgr_device_ids() { + # TODO add device name as description + local -a devices + devices=($(_call_program devices fwupdmgr get-devices | awk '/Device ID/||/DeviceId/{print $NF}')) + _describe -t devices 'device ID' devices +} + +(( $+functions[_fwupdmgr_remote_ids] )) || +_fwupdmgr_remote_ids() { + # TODO add remote description + local -a remotes + remotes=($(_call_program remotes fwupdmgr get-remotes | awk '/Remote ID/{print $NF}')) + _describe -t remotes 'remote ID' remotes +} + +_fwupdmgr "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_gas b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_gas new file mode 100644 index 00000000..48f6838a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_gas @@ -0,0 +1,69 @@ +#compdef gas +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for gas (https://github.com/walle/gas). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Fredrik Wallgren +# +# ------------------------------------------------------------------------------ + +local curcontext="$curcontext" state line cmds ret=1 + +_arguments -C \ + '(- 1 *)'{-v,--version}'[display version information]' \ + '(-h|--help)'{-h,--help}'[show help information]' \ + '1: :->cmds' \ + '*: :->args' && ret=0 + +case "$state" in + (cmds) + cmds=( + "version:Prints Gas's version" + "use:Uses author" + "show:Shows your current user" + "list:Lists your authors" + "import:Imports current user to gasconfig" + "help:Describe available tasks or one specific task" + "delete:Deletes author" + "add:Adds author to gasconfig" + ) + _describe -t commands 'gas command' cmds && ret=0 + ;; + (args) + case "$line[1]" in + (use|delete) + _values -S , 'authors' $(cat ~/.gas | sed -n -e 's/^\[\(.*\)\]/\1/p') && ret=0 + ;; + esac + ;; +esac + +return ret + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ghc b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ghc new file mode 100644 index 00000000..4d01430b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ghc @@ -0,0 +1,618 @@ +#compdef ghc ghci ghc-pkg +# ------------------------------------------------------------------------------ +# Copyright (c) 2014 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for ghc (https://www.haskell.org/ghc/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Gérard Milmeister +# * Philip Dexter +# +# ------------------------------------------------------------------------------ + +local state +local WORDS + +# +# ghci +# + +_ghc_ghci () { _ghc_compiler } + +# +# ghc +# + +_ghc_compiler () +{ + _arguments \ + "-no-hs-main[Don't assume this program contains main]" \ + "-no-user-package-conf[Don't load the user's package config file]" \ + '(- *)'{--help,-\?}'[Show help information]' \ + '*-I-[Add directory to path for #include files]:directory:_files -/' \ + '*-X-[Language flags]:flag:_ghc_language_flags' \ + '*-d-[Debugging options]:flag:_ghc_debugging_options' \ + '*-f-[Compiler options]:flag:_ghc_compiler_flags' \ + '*-hide-package[Hide package]:Package:_ghc_pkg_list_packages' \ + '*-trust[Expose package and set it to be trusted]:Package:_ghc_pkg_list_packages' \ + '*-distrust[Expose package and set it to be distrusted]:Package:_ghc_pkg_list_packages' \ + '*-distrust-all[Distrust all packages by default]' \ + '*-i-[Add directory to import path]:directory:->ghc_include_directory' \ + '*-package[Expose package]:Package:_ghc_pkg_list_packages' \ + '*:file:_files -g \*.\{lhs,hs,hc,c,s\}' \ + '--info[Display information about the compiler]' \ + '--show-options[Display the supported command line options]' \ + '--interactive[Interactive mode]' \ + '--make[Compile and link a complete Haskell program]:file:_files -g "*.{lhs,hs,hc,c,s}"' \ + '--numeric-version[Display GHC version (numeric only)]' \ + '--print-libdir[Display GHC library directory]' \ + '--show-iface[Show interface]:file:_files -g "*.hi"' \ + {--supported-languages,--supported-extensions}'[Display the supported language extensions]' \ + '-C[Stop after generating C]' \ + '-E[Stop after generating preprocessed, de-litted Haskell]' \ + '-H[Minimum heap size]:size:' \ + '-M[Output Makefile rules]' \ + '-O-[Enable optimization]:level:(0 1 2)' \ + '-Rghc-timing[Summarise timing stats for GHC]' \ + '-S[Stop after generating assembler]' \ + '-V[Display GHC version]' \ + '-W[Enable normal warnings]' \ + '-Wall[Enable almost all warnings]' \ + '-Werror[Make warnings fatal]' \ + '-Wwarn[Make warnings non-fatal]' \ + '-c[Stop after generating object files]' \ + '-eventlog[Enable runtime event tracing]' \ + '-debug[Use the debugging runtime]' \ + "-dylib-install-name[On Darwin/macOS only, set the install name]" \ + '-dynamic[Use dynamic Haskell libraries]' \ + '-dynamic-too[Build dynamic object files as well as static object files during compilation]' \ + '-dynosuf[Set the output suffix for dynamic object files]' \ + '-dynload[Select one of a number of modes for finding shared libraries at runtime]' \ + '--mk-dll[DLL-creation mode (Windows only)]' \ + '-framework-path[On Darwin/macOS/iOS only, add dir to the list of directories searched for frameworks]' \ + '-shared[Generate a shared library (as opposed to an executable)]' \ + '-staticlib[On Darwin/macOS/iOS only, generate a standalone static library (as opposed to an executable)]' \ + '-e[Evaluate expression]' \ + '-hide-all-packages[Hide all packages by default]' \ + '-hpcdir[Directory to deposit .mix files during compilation (default is .hpc)]' \ + '-n[Do a dry run]' \ + '-o[Set output filename]:file:_files' \ + '-outputdir[Set output directory]:directory:_files -/' \ + '-package-name[Compile to be part of package]' \ + '-hide-all-packages[Hide all packages by default]' \ + '-package-db[Add file to the package db stack]:file:_files' \ + '-clear-package-db[Clear the package db stack]' \ + '-msse2[(x86 only) Use SSE2 for floating point]' \ + '-monly-\[432\]-regs[(x86 only) give some registers back to the C compiler]' \ + '-no-global-package-db[Remove the global package db from the stack]' \ + '-global-package-db[Add the global package db to the stack]' \ + "-no-user-package-db[Remove the user's package db from the stack]" \ + "-user-package-db[Add the user's package db to the stack]" \ + "-no-auto-link-packages[Don't automatically link in the base and rts packages]" \ + '-optL[pass option to the literate pre-processor]' \ + '-optP[pass option to cpp (with -cpp only)]' \ + '-optF[pass option to the custom pre-processor]' \ + '-optc[pass option to the C compiler]' \ + '-optlo[pass option to the LLVM optimiser]' \ + '-optlc[pass option to the LLVM compiler]' \ + '-optm[pass option to the mangler]' \ + '-opta[pass option to the assembler]' \ + '-optl[pass option to the linker]' \ + '-optdll[pass option to the DLL generator]' \ + '-optwindres[pass option to windres.]' \ + '-prof[Turn on profiling]' \ + '-pgmL[Use cmd as the literate pre-processor]' \ + '-pgmP[Use cmd as the C pre-processor (with -cpp only)]' \ + '-pgmc[Use cmd as the C compiler]' \ + '-pgms[Use cmd as the splitter]' \ + '-pgml[Use cmd as the linker]' \ + '-pgmdll[Use cmd as the DLL generator]' \ + '-pgmF[Use cmd as the pre-processor (with -F only)]' \ + '-pgmwindres[Use cmd as the program for embedding manifests on Windows]' \ + '-pgmlibtool[Use cmd as the command for libtool (with -staticlib only)]' \ + '-rtsopts[Only a minimum of safe options can be given to RTS]' \ + '-rtsopts=[Control whether the RTS behavior can be tweaked via command-line flags and the GHCRTS environment variable (none, some, or all)]' \ + '-with-rtsopts=[Set the default RTS options]' \ + '-threaded[Use the threaded runtime]' \ + '-ticky[Turn on ticky-ticky profiling]' \ + '-tmpdir[Set the directory for temporary files]:directory:_files -/' \ + '-v-[Control verbosity]:level:(0 1 2 3 4 5)' \ + '-w[Disable all warnings]' \ + '-x[Override default behaviour for source files]:suffix:(hs lhs hc c s o hspp)' \ + '-hcsuf[Set the suffix to use for intermediate]:suffix:' \ + '-hidir[Set directory for interface files]:directory:_files -/' \ + '-hisuf[Set the suffix to use for interface files]:suffix:' \ + '-odir[Set directory for object files]:directory:_files -/' \ + '-ohi[Set the filename in which to put the interface]:filename:_files -/' \ + '-osuf[Set the output file suffix]:suffix:' \ + '-stubdir[Redirect FFi stub files]:directory:_files -/' \ + '-dumpdir[Redirect dump files]:directory:_files -/' \ + '-outputdir[Set output directory]:directory:_files -/' \ + '-keep-hc-files[Retain intermediate .hc files]' \ + '-keep-llvm-files[Retain intermediate LLVM .ll files]' \ + '-keep-s-files[Retain intermediate .s files]' \ + '-keep-raw-s-files[Retain intermediate .raw_s files]' \ + '-keep-tmp-files[Retain all intermediate temporary files]' \ + '-static[Use static Haskell libraries]' \ + '-split-objs[Split objects (for libraries)]' \ + '-no-link[Omit linking]' \ + '-main-is[Set main module and function]:function:' \ + '*-L-[Add dir to the list of directories searched for libraries]:directory:_files -/' \ + '*-l-[Link in library]:library:->library' + + [[ -n "$state" ]] && + case "$state" in + ghc_include_directory) _ghc_include_directory ;; + library) + _wanted libraries expl library \ + compadd - \ + ${^=LD_LIBRARY_PATH:-/usr/lib /usr/local/lib}/lib*.(a|so*)(:t:fr:s/lib//) \ + && ret=0 + esac +} + + +_ghc_include_directory () +{ + compset -P '*:' + compset -S ':*' + _path_files -r': ' -/ +} + +_ghc_compiler_flags () +{ + local _ghc_compiler_flags_list + _ghc_compiler_flags_list=( + 'ghci-hist-size:Set the number of entries GHCi keeps for \:history' + 'print-explicit-foralls:Print explicit forall quantification in types' + 'print-explicit-kinds:Print explicit kind foralls and kind arguments in types' + {no-,}'break-on-error:Break on uncaught exceptions and errors' + {no-,}'break-on-exception:Break on any exception thrown' + {no-,}'case-merge:Enable case-merging' + {no-,}'defer-type-errors:Defer as many type errors as possible until runtime' + {no-,}'dicts-strict:Make dictionaries strict' + {no-,}'do-eta-reduction:Enable eta-reduction' + {no-,}'do-lambda-eta-expansion:Enable lambda eta-reduction' + 'eager-blackholing:Turn on eager blackholing' + {no-,}'enable-rewrite-rules:Switch on all rewrite rules (including rules generated by automatic specialisation of overloaded functions)' + 'error-spans:Output full span in error messages' + 'ext-core:Generate .hcr external Core file' + 'force-recomp:Turn off recompilation checking' + {no-,}'float-in:Turn on the float-in transformation' + {no-,}'full-laziness:Turn on full laziness (floating bindings outwards)' + {no-,}'fun-to-thunk:Allow worker-wrapper to convert a function closure into a thunk if the function does not use any of its arguments. Off by default.' + {no-,}'glasgow-exts:Enable most language extensions' + {no-,}'helpful-errors:Make suggestions for mis-spelled names' + 'history-size:Set simplification history size' + {no-,}'ignore-asserts:Ignore assertions in the source' + {no-,}'ignore-interface-pragmas:Ignore pragmas in interface files' + {no-,}'loopification:Turn saturated self-recursive tail-calls into local jumps in the generated assembly' + {no-,}'late-dmd-anal:Run demand analysis again, at the end of the simplification pipeline' + {no-,}'liberate-case:Turn on the liberate-case transformation' + 'liberate-case-threshold=:Set the size threshold for the liberate-case transformation (default 200)' + 'no-liberate-case-threshold:Set the size threshold for the liberate-case transformation (default 200)' + {no-,}'max-relevant-bindings=N:Set the maximum number of bindings to display in type error messages (default 6).' + 'max-worker-args=:If a worker has that many arguments, none will be unpacked anymore (default 10)' + 'max-simplifier-iterations=:Set the max iterations for the simplifier' + 'no-asm-mangling:Turn off assembly mangling' + 'no-black-holing:Turn off black holing' + "no-hi-version-check:Don't complain about .hi file mismatches" + 'no-implicit-import-qualified:Turn off implicit qualified import of everything in GHCi' + 'no-print-bind-contents:Turn off printing of binding contents in GHCi' + 'no-opt-coercion:Turn off the coercion optimiser' + 'no-ghci-history:Do not use the load/store the GHCi command history from/to ghci_history' + 'no-ghci-sandbox:Turn off the GHCi sandbox. Means computations are run in the main thread, rather than a forked thread' + 'no-gen-manifest:Do not generate a manifest file (Windows only)' + 'no-embed-manifest:Do not embed the manifest in the executable (Windows only)' + "no-shared-implib:Don't generate an import library for a DLL (Windows only)" + 'no-pre-inlining:Turn off pre-inlining' + 'no-state-hack:Turn off the "state hack" whereby any lambda with a real-world state token as argument is considered to be single-entry' + {no-,}'print-bind-result:Turn on printing of binding results in GHCi' + {no-,}'print-evld-with-show:Enable usage of Show instances in \:print' + 'unregisterised:Unregisterised compilation' + 'asm:Use the native code generator' + 'via-C:Compile via C' + 'no-code:Omit code generation' + 'byte-code:Generate byte-code' + 'object-code:Generate object code' + 'hpc:Turn on Haskell program coverage instrumentation' + 'PIC:Generate position-independent code' + 'plugin=:Load a plugin exported by a given module' + 'plugin-opt=:Give arguments to a plugin module' + 'context-stack=:Set the limit for context reduction (default is 20)' + 'type-function-depth=:Set the limit for type function reductions (default is 200)' + 'force-recomp:Turn off recompilation checking' + {no-,}"omit-interface-pragmas:Don't generate interface pragmas" + 'package-trust:Enable Safe Haskell trusted package requirement for trustworthy modules' + {no-,}'pedantic-bottoms:Make GHC be more precise about its treatment of bottom' + {no-,}'disambiguate-record-fields:Enable record field disambiguation' + {no-,}'irrefutable-tuples:Make tuple pattern matching irrefutable' + {no-,}'vectorise:Enable vectorisation of nested data parallelism' + {no-,}'avoid-vect:Enable vectorisation avoidance' + {no-,}'excess-precision:Enable excess intermediate precision' + {no-,}'prof-auto:Auto-add SCCs to all bindings not marked INLINE' + {no-,}'prof-auto-top:Auto-add SCCs to all top-level bindings not marked INLINE' + {no-,}'prof-auto-exported:Auto-add SCCs to all exported bindings not marked INLINE' + {no-,}'prof-cafs:Auto-add SCCs to all CAFs' + {no-,}'prof-count-entries:Collect entry counts' + 'simplifier-phases:Set the number of phases for the simplifier (default 2)' + 'simpl-tick-factor=:Set the percentage factor for simplifier ticks (default 100)' + {no-,}'spec-constr:Turn on the SpecConstr transformation' + {no-,}'spec-constr-threshold=:Set the size threshold for the SpecConstr transformation (default 200)' + {no-,}'spec-constr-count=:Set the maximum number of specialisations that will be created for any one function by the SpecConstr transformation (default 3)' + 'strictness=before=:Run an additional strictness analysis before a simplifier phase' + {no-,}'static-argument-transformation:Turn on the static argument transformation' + {no-,}'unbox-strict-fields:Flatten strict constructor fields' + {no-,}'unbox-small-strict-fields:Flatten strict constructor fields with a pointer-sized representation' + {no-,}'unfolding-creation-threshold:Tweak unfolding settings' + {no-,}'unfolding-fun-discount:Tweak unfolding settings' + {no-,}'unfolding-keeness-factor:Tweak unfolding settings' + {no-,}'unfolding-use-threshold:Tweak unfolding settings' + {no-,}'warn-warnings-deprecations:Warn about uses of functions & types that have warnings or deprecated pragmas' + {no-,}'warn-deprecated-flags:Warn about uses of commandline flags that are deprecated' + {no-,}'warn-duplicate-exports:Warn when an entity is exported multiple times' + {no-,}'warn-hi-shadowing:Warn when a .hi file in the current directory shadows a library' + {no-,}'warn-implicit-prelude:Warn when the Prelude is implicitly imported' + {no-,}'warn-incomplete-patterns:Warn when a pattern match could fail' + {no-,}'warn-incomplete-record-updates:Warn when a record update could fail' + {no-,}'warn-missing-fields:Warn when fields of a record are uninitialised' + {no-,}'warn-missing-methods:Warn when class methods are undefined' + {no-,}'warn-missing-signatures:Warn about top-level functions without signatures' + {no-,}'warn-duplicate-constraints:Warn when a constraint appears duplicated in a type signature' + {no-,}'warn-identities:Warn about uses of Prelude numeric conversions that are probably the identity (and hence could be omitted)' + {no-,}'warn-incomplete-uni-patterns:Warn when a pattern match in a lambda expression or pattern binding could fail' + {no-,}'warn-lazy-unlifted-bindings:(Deprecated) warn when a pattern binding looks lazy but must be strict' + {no-,}'warn-missing-import-lists:Warn when an import declaration does not explicitly list all the names brought into scope' + {no-,}'warn-missing-local-sigs:Warn about polymorphic local bindings without signatures' + {no-,}'warn-monomorphism-restriction:Warn when the Monomorphism Restriction is applied' + {no-,}'warn-name-shadowing:Warn when names are shadowed' + {warn-orphans,warn-auto-orphans}':Warn when the module contains orphan instance declarations or rewrite rules' + {no-,}'warn-overlapping-patterns:Warn about overlapping patterns' + {no-,}'warn-tabs:Warn if there are tabs in the source file' + {no-,}'warn-type-defaults:Warn when defaulting happens' + {no-,}"warn-unrecognised-pragmas:Warn about uses of pragmas that GHC doesn't recognise" + {no-,}'warn-unused-binds:Warn about bindings that are unused' + {no-,}'warn-unused-imports:Warn about unnecessary imports' + {no-,}"warn-unused-matches:Warn about variables in patterns that aren't used" + {no-,}'warn-unused-do-bind:Warn about do bindings that appear to throw away values of types other than ()' + {no-,}'warn-wrong-do-bind:Warn about do bindings that appear to throw away monadic values that you should have bound instead' + {no-,}'warn-unsafe:Warn if the module being compiled is regarded to be unsafe' + {no-,}'warn-safe:Warn if the module being compiled is regarded to be safe' + {no-,}'warn-amp:Warn on definitions conflicting with the Applicative-Monad Proposal (AMP)' + {no-,}'warn-typed-holes:Enable holes in expressions' + ) + _describe -t flags 'ghc' _ghc_compiler_flags_list || compadd "$@" +} + +_ghc_debugging_options () +{ + local _ghc_debugging_options_list + _ghc_debugging_options_list=( + "dump-hi:Dump the new interface to stdout" + "dump-hi-diffs:Show the differences vs. the old interface" + "dump-minimal-imports:Dump a minimal set of imports" + "core-lint:Turn on internal sanity checking" + "dump-asm:Dump assembly" + "dump-bcos:Dump interpreter byte code" + "dump-cmm:Dump C-- output" + "dump-cpranal:Dump output from CPR analysis" + "dump-cse:Dump CSE output" + "dump-deriv:Dump deriving output" + "dump-ds:Dump desugarer output" + 'dump-flatC:Dump "flat" C' + "dump-foreign:Dump foreign export stubs" + "dump-hpc:Dump after instrumentation for program coverage" + "dump-inlinings:Dump inlining info" + "dump-occur-anal:Dump occurrence analysis output" + "dump-opt-cmm:Dump the results of C-- to C-- optimising passes" + "dump-parsed:Dump parse tree" + "dump-prep:Dump prepared core" + "dump-rn:Dump renamer output" + "dump-rules:Dump rules" + "dump-simpl:Dump final simplifier output" + "dump-simpl-phases:Dump output from each simplifier phase" + "dump-simpl-iterations:Dump output from each simplifier iteration" + "dump-spec:Dump specialiser output" + "dump-splices:Dump TH spliced expressions" + "dump-stg:Dump final STG" + "dump-stranal:Dump strictness analyser output" + "dump-tc:Dump typechecker output" + "dump-types:Dump type signatures" + "dump-worker-wrapper:Dump worker-wrapper output" + "dump-if-trace:Trace interface files" + "dump-tc-trace:Trace typechecker" + "dump-to-file:Dump to files instead of stdout" + "dump-core-stats:Print a one-line summary of the size of the Core program at the end of the optimisation pipeline" + "dump-llvm:Dump LLVM intermediate code" + "dump-rule-firings:Dump rule firing info" + "dump-rule-rewrites:Dump detailed rule firing info" + "dump-vect:Dump vectoriser input and output" + "dump-strsigs:Dump strictness signatures" + "dump-vt-trace:Trace vectoriser" + "dump-rn-trace:Trace renamer" + "dump-rn-stats:Renamer stats" + "dump-simpl-stats:Dump simplifier stats" + "suppress-all:In core dumps, suppress everything (except for uniques) that is suppressible" + "suppress-uniques:Suppress the printing of uniques in debug output (easier to use diff)" + "suppress-idinfo:Suppress extended information about identifiers where they are bound" + "suppress-module-prefixes:Suppress the printing of module qualification prefixes" + "suppress-type-signatures:Suppress type signatures" + "suppress-type-applications:Suppress type applications" + "suppress-coercions:Suppress the printing of coercions in Core dumps to make them shorter" + "no-debug-output:Suppress unsolicited debugging output" + "ppr-debug:Turn on debug printing (more verbose)" + "ppr-noprags:Don't output pragma info in dumps" + "ppr-user-length:Set the depth for printing expressions in error msgs" + "ppr-colsNNN:Set the width of debugging output. For example -dppr-cols200" + "ppr-case-as-let:Print single alternative case expressions as strict lets" + "source-stats:Dump haskell source stats" + "cmm-lint:C-- pass sanity checking" + "stg-lint:STG pass sanity checking" + "stg-stats:Dump STG stats" + "verbose-core2core:Show output from each core-to-core pass" + "verbose-stg2stg:Show output from each STG-to-STG pass" + "show-passes:Print out each pass name as it happens" + "faststring-stats:Show statistics for fast string usage when finished" + ) + _describe -t flags 'ghc' _ghc_debugging_options_list || compadd "$@" +} + + +_ghc_language_flags () +{ + local _ghc_language_flags_list + _ghc_language_flags_list=( + "AllowAmbiguousTypes:Allow the user to write ambiguous types, and the type inference engine to infer them" + "Arrows:Enable arrow notation extension" + "AutoDeriveTypeable:Automatically derive Typeable instances for every datatype and type class declaration" + "BangPatterns:Enable bang patterns" + "ConstraintKinds:Enable a kind of constraints" + "CPP:Enable the C preprocessor" + "ConstrainedClassMethods:Enable constrained class methods" + "DataKinds:Enable datatype promotion" + "DefaultSignatures:Enable default signatures" + "DeriveDataTypeable:Enable deriving for the Data and Typeable classes" + "DeriveGeneric:Enable deriving for the Generic class" + "DisambiguateRecordFields:Enable record field disambiguation" + "EmptyCase:Allow empty case alternatives" + "EmptyDataDecls:Enable empty data declarations" + "ExistentialQuantification:Enable existential quantification" + "ExplicitForAll:Enable explicit universal quantification" + "ExplicitNamespaces:Enable using the keyword type to specify the namespace of entries in imports and exports" + "ExtendedDefaultRules:Use GHCi's extended default rules in a normal module" + "FlexibleContexts:Enable flexible contexts" + "FlexibleInstances:Enable flexible instances" + "ForeignFunctionInterface:Enable foreign function interface" + "FunctionalDependencies:Enable functional dependencies" + "GADTs:Enable generalised algebraic data types" + "GADTSyntax:Enable generalised algebraic data type syntax" + "GeneralizedNewtypeDeriving:Enable newtype deriving" + "Generics:Enable generic classes" + "ImplicitParams:Enable Implicit Parameters" + "ImpredicativeTypes:Enable impredicative types" + "IncoherentInstances:Enable incoherent instances" + "InterruptibleFFI:Enable interruptible FFI" + "KindSignatures:Enable kind signatures" + "LambdaCase:Enable lambda-case expressions" + "LiberalTypeSynonyms:Enable liberalised type synonyms" + "MonadComprehensions:Enable monad comprehensions" + "MonoLocalBinds:Enable do not generalise local bindings" + "MultiParamTypeClasses:Enable multi parameter type classes" + "MultiWayIf:Enable multi-way if-expressions" + "NamedFieldPuns:Enable record puns" + "NegativeLiterals:Enable support for negative literals" + "NewQualifiedOperators:Enable new qualified operator syntax" + "NoImplicitPrelude:Don't implicitly import Prelude" + "NoMonoPatBinds:Make pattern bindings polymorphic" + "NoMonomorphismRestriction:Disable the monomorphism" + "NoNPlusKPatterns:Disable support for n+k patterns" + "NoTraditionalRecordSyntax:Disable support for traditional record syntax (as supported by Haskell 98) C {f = x}" + "NullaryTypeClasses:Enable nullary (no parameter) type classes" + "NumDecimals:Enable support for 'fractional' integer literals" + "OverlappingInstances:Enable overlapping instances" + "OverloadedLists:Enable overloaded lists" + "OverloadedStrings:Enable overloaded string literals" + "PArr:Enable parallel arrays" + "PackageImports:Enable package-qualified imports" + "ParallelArrays:Enable parallel arrays" + "ParallelListComp:Enable parallel list comprehensions" + "PatternGuards:Enable pattern guards" + "PolyKinds:Enable kind polymorphism" + "PolymorphicComponents:Enable polymorphic components for data constructors" + "QuasiQuotes:Enable quasiquotation" + "Rank2Types:Enable rank-2 types" + "RankNTypes:Enable rank-N types" + "RebindableSyntax:Employ rebindable syntax" + "RecordWildCards:Enable record wildcards" + "RecursiveDo:Enable recursive do (mdo) notation" + "RelaxedPolyRec:Relaxed checking for mutually-recursive polymorphic functions" + "Safe:Enable the Safe Haskell Safe mode" + "ScopedTypeVariables:Enable lexically-scoped type variables" + "StandaloneDeriving:Enable standalone deriving" + "TemplateHaskell:Enable Template Haskell" + "TransformListComp:Enable transform list comprehensions" + "TypeFamilies:Enable type families" + "TypeOperators:Enable type operators" + "TypeSynonymInstances:Enable type synonyms" + "Trustworthy:Enable the Safe Haskell Trustworthy mode" + "UnboxedTuples:Enable unboxed tuples" + "UndecidableInstances:Enable undecidable instances" + "UnicodeSyntax:Enable unicode syntax" + "UnliftedFFITypes:Enable unlifted FFI types" + "Unsafe:Enable Safe Haskell Unsafe mode" + "ViewPatterns:Enable view patterns" + 'MagicHash:Allow "#" as a postfix modifier on identifiers' + ) + _describe -t flags 'ghc' _ghc_language_flags_list || compadd "$@" +} + +# +# ghc-pkg +# + +_ghc_pkg () +{ + WORDS=() + for w in $words[1,(($CURRENT - 1))]; do + if [[ $w != --* ]]; then WORDS+=$w; fi + done + _arguments '*:command:_ghc_pkg_command' +} + +_ghc_pkg_command() +{ + local -a _ghc_pkg_cmds + _ghc_pkg_cmds=( + "register:Register the package using package description" + "update:Register the package (overwriting existing package)" + "unregister:Unregister the specified package" + "expose:Expose the specified package" + "hide:Hide the specified package" + "list:List registered packages" + "find-module:List registered packages exposing module" + "latest:Prints the highest registered version of a package" + "check:Check the consistency of package dependencies and list broken packages" + "describe:Give the registered description for the specified package" + "field:Extract the specified field of the package description" + "dump:Dump the registered description for every package" + ) + + if (( $#WORDS == 1 )); then + _describe -t commands 'command' _ghc_pkg_cmds || compadd "$@" + else + local curcontext="$curcontext" + cmd="${${_ghc_pkg_cmds[(r)$WORDS[2]:*]%%:*}}" + if (( $#cmd )); then + _arguments \ + "--user[Use current user's package database]" \ + '--global[User the global package database]' \ + {-f,--package-conf=}'[Use the specified package config file]:Package config file:_files' \ + '--no-user-package-conf[Never reader the user package config]' \ + {-V,--version}'[Output version information and exit]' \ + '--force[Ignore missing directories and libraries only]' \ + {-g,--auto-ghci-libs}'[Automatically build libs for GHCi]' \ + {-?,--help}'[Display this help and exit]' \ + '--simple-output[Print output in easy-to-parse format for some commands]' \ + '--names-only[Only print package names, not versions]' \ + '--ignore-case[Ignore case for substring matching]' \ + '*:argument:_ghc_pkg_'$cmd + else + _message "unknown ghc-pkg command: $WORDS[2]" + fi + fi +} + +_ghc_pkg_unregister () { _ghc_pkg_list_packages } + +_ghc_pkg_expose () { _ghc_pkg_list_packages } + +_ghc_pkg_hide () { _ghc_pkg_list_packages } + +_ghc_pkg_latest () { _ghc_pkg_list_packages } + +_ghc_pkg_describe () { _ghc_pkg_list_packages } + +_ghc_pkg_field () +{ + _ghc_pkg_available_packages + if (( $#WORDS == 2 )); then + compadd "$@" -a -- _ghc_pkg_packages + elif (( $#WORDS == 3 )); then + compset -P '*,' + compset -S ',*' + compadd "$@" -S ',' -q -- \ + name version license copyright maintainer \ + stability homepage package-url description \ + category author exposed exposed-modules \ + hidden-modules import-dirs hs-libraries \ + extra-libraries extra-ghci-libraries include-dirs \ + includes depends hugs-options cc-options ld-options \ + framework-dirs frameworks haddock-interfaces \ + haddock-html + fi +} + +_ghc_pkg_register () { _files } + +_ghc_pkg_update () { _files } + +_ghc_pkg_list () { _ghc_pkg_list_packages } + +_ghc_pkg_find-module () +{ + if (( $#WORDS == 2)); then + if ( [[ ${+_ghc_modules} -eq 0 ]] || _cache_invalid GHC_MODULES ) && + ! _retrieve_cache GHC_MODULES; + then + _ghc_modules=( $(ghc-pkg dump | sed -n '/^exposed-modules:/{s/^exposed-modules:[ ]\+\(.*\)$/\1/;s/ /\n/;p;be};b;:e;n;/^ /{s/^[ ]\+\(.*\)$/\1/;s/ /\n/;p;be}') ) + _store_cache GHC_MODULES _ghc_modules + fi + compadd "$@" -a -- _ghc_modules + fi +} + +_ghc_pkg_dump () {} + +_ghc_pkg_check () {} + +_ghc_pkg_available_packages () +{ + if ( [[ ${+_ghc_pkg_packages_pkgs} -eq 0 ]] || _cache_invalid GHC_PACKAGES ) && + ! _retrieve_cache GHC_PACKAGES; + then + _ghc_pkg_packages=( $(ghc-pkg list --simple-output --names-only) ) + _store_cache GHC_PACKAGES _ghc_pkg_packages + fi +} + +_ghc_pkg_list_packages () +{ + _ghc_pkg_available_packages + compadd "$@" -a -- _ghc_pkg_packages +} + + +# +# dispatcher +# + +case $service in + ghc) + _ghc_compiler + ;; + ghci) + _ghc_ghci + ;; + ghc-pkg) + _ghc_pkg + ;; +esac diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_gist b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_gist new file mode 100644 index 00000000..1db566ee --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_gist @@ -0,0 +1,126 @@ +#compdef gist +# ------------------------------------------------------------------------------ +# Copyright (c) 2017 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for gist (https://github.com/defunkt/gist) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Akira Maeda +# * Patrick Ziegler +# * Shivam Mehta +# +# ------------------------------------------------------------------------------ + +local curcontext="$curcontext" state line ret=1 +typeset -A opt_args + +_arguments -C \ + '(--login)--login[Authenticate gist on this computer.]' \ + '(-f --filename)'{-f,--filename}'[Sets the filename and syntax type.]:NAME' \ + '(-t --type)'{-t,--type}'[Sets the file extension and syntax type.]:EXT' \ + '(-p --private --no-private)'{-p,--private}'[Makes your gist private.]' \ + '(--no-private -p --private)'--no-private'[Makes your gist no private.]' \ + '(-d --description)'{-d,--description}'[Adds a description to your gist.]:DESCRIPTION' \ + '(-s --shorten)'{-s,--shorten}'[Shorten the gist URL using git.io.]' \ + '(-u --update)'{-u,--update}'[Update an existing gist.]:URL ID:user_gists' \ + '(-c --copy)'{-c,--copy}'[Copy the resulting URL to the clipboard]' \ + '(-e --embed)'{-e,--embed}'[Copy the embed code for the gist to the clipboard]' \ + '(-o --open --no-open)'{-o,--open}'[Open the resulting URL in a browser]' \ + '(--no-open -o --open)'--no-open'[No open the resulting URL in a browser]' \ + '(-P --paste)'{-P,--paste}'[Paste from the clipboard to gist]' \ + '(-R --raw)'{-R,--raw}'[Display raw URL of the new gist]' \ + '(-l --list)'{-l,--list}'[List all gists for user ]::user' \ + '(-h --help)'{-h,--help}'[print options help]' \ + '(-v --version)'{-v,--version}'[print version]' \ + '(-r --read)'{-r,--read}'[Read a gist and print out the contents]:user gists:user_gists' \ + '*: :_files' && ret=0 + +_user_gists_cache_policy() { + # rebuild if cache is more than a day old + local -a oldp + oldp=( "$1"(mh+1) ) + (( $#oldp )) +} + +user_gists() { + local update_policy ret=1 + zstyle -s ":completion:${curcontext}:" cache-policy update_policy + if [[ -z "$update_policy" ]]; then + zstyle ":completion:${curcontext}:" cache-policy _user_gists_cache_policy + fi + + # stores the gists of the logged in user in the format ID[Description] + _list=() + _cached_gists="user_gists" + + # retrieve/Write gists from/to cache + if _cache_invalid $_cached_gists || ! _retrieve_cache $_cached_gists; then + _gists=$(gist -l) + + if [ $? -eq 0 ]; then + _store_cache $_cached_gists _gists + else + # some error occurred, the user is probably not logged in + # set _gists to an empty string so that no completion is attempted + _gists="" + fi + else + _retrieve_cache $_cached_gists + fi + + if [ -n "$_gists" ]; then + echo "$_gists" | while read -r line; do + # Splitting the gist -l output + url="$(echo "$line" | cut -d " " -f 1 | cut -d "/" -f 4)" + # gists w/o descriptions can have only one column in the output, those + # have their description set to an empty string + description="$(echo "$line" | awk '{if(NF > 1){$1=""; print $0}}')" + + _list+=( "${url}[${description}]" ) + done + + _values "gists" $_list + ret=0 + fi + + return ret +} + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_git-flow b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_git-flow new file mode 100644 index 00000000..55bc63ce --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_git-flow @@ -0,0 +1,444 @@ +#compdef git-flow +#description Git Flow branching model +# ------------------------------------------------------------------------------ +# Copyright (c) 2010-2015 Justin Hileman +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for git-flow (https://github.com/nvie/gitflow). +# +# Source: https://github.com/bobthecow/git-flow-completion +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Justin Hileman (https://github.com/bobthecow) +# * Yusuke Muraoka (https://github.com/jbking) +# * Vincent Driessen (https://github.com/nvie) +# * Zifei Tong (https://github.com/chevalun) +# * Ben O'Hara (https://github.com/benohara) +# +# ------------------------------------------------------------------------------ + + +_git-flow () +{ + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments -C \ + ':command:->command' \ + '*::options:->options' + + case $state in + (command) + + local -a subcommands + subcommands=( + 'init:Initialize a new git repo with support for the branching model.' + 'feature:Manage your feature branches.' + 'release:Manage your release branches.' + 'hotfix:Manage your hotfix branches.' + 'support:Manage your support branches.' + 'version:Shows version information.' + ) + _describe -t commands 'git flow' subcommands + ;; + + (options) + case $line[1] in + + (init) + _arguments \ + -f'[Force setting of gitflow branches, even if already configured]' \ + -d'[Use default branch naming conventions and prefixes]' + ;; + + (version) + ;; + + (hotfix) + __git-flow-hotfix + ;; + + (release) + __git-flow-release + ;; + + (feature) + __git-flow-feature + ;; + + (support) + __git-flow-support + ;; + + esac + ;; + esac +} + +__git-flow-release () +{ + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments -C \ + ':command:->command' \ + '*::options:->options' + + case $state in + (command) + + local -a subcommands + subcommands=( + 'start:Start a new release branch.' + 'finish:Finish a release branch.' + 'list:List all your release branches. (Alias to `git flow release`)' + 'publish:Publish this release branch to origin.`)' + 'track:Track a release branch from origin.`)' + ) + _describe -t commands 'git flow release' subcommands + _arguments \ + -v'[Verbose (more) output]' + ;; + + (options) + case $line[1] in + + (start) + _arguments \ + -F'[Fetch from origin before performing finish]'\ + ':version:__git_flow_version_list' + ;; + + (finish) + _arguments \ + -F'[Fetch from origin before performing finish]' \ + -s'[Sign the release tag cryptographically]'\ + -u'[Use the given GPG-key for the digital signature (implies -s)]'\ + -m'[Use the given tag message]'\ + -n'[Don'\''t tag this release]'\ + -p'[Push to $ORIGIN after performing finish]'\ + -k'[Keep branch after performing finish]'\ + ':version:__git_flow_version_list' + ;; + + (publish) + _arguments \ + ':version:__git_flow_version_list' + ;; + + (track) + _arguments \ + ':version:__git_flow_version_list' + ;; + + + + *) + _arguments \ + -v'[Verbose (more) output]' + ;; + esac + ;; + esac +} + +__git-flow-hotfix () +{ + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments -C \ + ':command:->command' \ + '*::options:->options' + + case $state in + (command) + + local -a subcommands + subcommands=( + 'start:Start a new hotfix branch.' + 'finish:Finish a hotfix branch.' + 'list:List all your hotfix branches. (Alias to `git flow hotfix`)' + 'publish:Publish this hotfix branch to origin`)' + ) + _describe -t commands 'git flow hotfix' subcommands + _arguments \ + -v'[Verbose (more) output]' + ;; + + (options) + case $line[1] in + + (start) + _arguments \ + -F'[Fetch from origin before performing finish]'\ + ':hotfix:__git_flow_version_list'\ + ':branch-name:__git_branch_names' + ;; + + (finish) + _arguments \ + -F'[Fetch from origin before performing finish]' \ + -s'[Sign the release tag cryptographically]'\ + -u'[Use the given GPG-key for the digital signature (implies -s)]'\ + -m'[Use the given tag message]'\ + -p'[Push to $ORIGIN after performing finish]'\ + ':hotfix:__git_flow_hotfix_list' + ;; + + (publish) + _arguments \ + ':hotfix:__git_flow_hotfix_list' + ;; + + *) + _arguments \ + -v'[Verbose (more) output]' + ;; + esac + ;; + esac +} + +__git-flow-feature () +{ + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments -C \ + ':command:->command' \ + '*::options:->options' + + case $state in + (command) + + local -a subcommands + subcommands=( + 'start:Start a new feature branch.' + 'finish:Finish a feature branch.' + 'list:List all your feature branches. (Alias to `git flow feature`)' + 'publish:Publish this feature branch to origin.' + 'track:Track a feature branch from origin.' + 'diff:Show a diff of changes since this feature branched off.' + 'rebase:Rebase a feature branch on top of develop.' + 'checkout:Check out (switch to) the given feature branch.' + 'pull:Pull a feature branch from a remote peer.' + ) + _describe -t commands 'git flow feature' subcommands + _arguments \ + -v'[Verbose (more) output]' + ;; + + (options) + case $line[1] in + + (start) + _arguments \ + -F'[Fetch from origin before performing finish]'\ + ':feature:__git_flow_feature_list'\ + ':branch-name:__git_branch_names' + ;; + + (finish) + _arguments \ + -F'[Fetch from origin before performing finish]' \ + -r'[Finish branch by rebasing first]'\ + -k'[Keep branch after performing finish]'\ + -D'[Force delete feature branch after finish]'\ + ':feature:__git_flow_feature_list' + ;; + + (publish) + _arguments \ + ':feature:__git_flow_feature_list'\ + ;; + + (track) + _arguments \ + ':feature:__git_flow_feature_list'\ + ;; + + (diff) + _arguments \ + ':branch:__git_branch_names'\ + ;; + + (rebase) + _arguments \ + -i'[Do an interactive rebase]' \ + ':branch:__git_branch_names' + ;; + + (checkout) + _arguments \ + ':branch:__git_flow_feature_list'\ + ;; + + (pull) + _arguments \ + ':remote:__git_remotes'\ + ':branch:__git_branch_names' + ;; + + *) + _arguments \ + -v'[Verbose (more) output]' + ;; + esac + ;; + esac +} + +__git-flow-support () +{ + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments -C \ + ':command:->command' \ + '*::options:->options' + + case $state in + (command) + + local -a subcommands + subcommands=( + 'start:Start a new support branch.' + 'list:List all your support branches. (Alias to `git flow support`)' + ) + _describe -t commands 'git flow support' subcommands + _arguments \ + -v'[Verbose (more) output]' + ;; + + (options) + case $line[1] in + + (start) + _arguments \ + -F'[Fetch from origin before performing finish]'\ + ':feature:__git_flow_support_list'\ + ':branch-name:__git_branch_names' + ;; + + *) + _arguments \ + -v'[Verbose (more) output]' + ;; + esac + ;; + esac +} + +__git_flow_version_list () +{ + local expl + declare -a versions + + versions=(${${(f)"$(_call_program versions git flow release list 2> /dev/null | tr -d ' |*')"}}) + __git_command_successful || return + + _wanted versions expl 'version' compadd $versions +} + +__git_flow_feature_list () +{ + local expl + declare -a features + + features=(${${(f)"$(_call_program features git flow feature list 2> /dev/null | tr -d ' |*')"}}) + __git_command_successful || return + + _wanted features expl 'feature' compadd $features +} + +__git_remotes () { + local expl gitdir remotes + + gitdir=$(_call_program gitdir git rev-parse --git-dir 2>/dev/null) + __git_command_successful || return + + remotes=(${${(f)"$(_call_program remotes git config --get-regexp '"^remote\..*\.url$"')"}//#(#b)remote.(*).url */$match[1]}) + __git_command_successful || return + + # TODO: Should combine the two instead of either or. + if (( $#remotes > 0 )); then + _wanted remotes expl remote compadd $* - $remotes + else + _wanted remotes expl remote _files $* - -W "($gitdir/remotes)" -g "$gitdir/remotes/*" + fi +} + +__git_flow_hotfix_list () +{ + local expl + declare -a hotfixes + + hotfixes=(${${(f)"$(_call_program hotfixes git flow hotfix list 2> /dev/null | tr -d ' |*')"}}) + __git_command_successful || return + + _wanted hotfixes expl 'hotfix' compadd $hotfixes +} + +__git_flow_support_list () +{ + local expl + declare -a support + + support=(${${(f)"$(_call_program support git flow support list 2> /dev/null | tr -d ' |*')"}}) + __git_command_successful || return + + _wanted hotfixes expl 'support' compadd $support +} + + +__git_branch_names () { + local expl + declare -a branch_names + + branch_names=(${${(f)"$(_call_program branchrefs git for-each-ref --format='"%(refname)"' refs/heads 2>/dev/null)"}#refs/heads/}) + __git_command_successful || return + + _wanted branch-names expl branch-name compadd $* - $branch_names +} + +__git_command_successful () { + if (( ${#pipestatus:#0} > 0 )); then + _message 'not a git repository' + return 1 + fi + return 0 +} + +_git-flow "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_git-pulls b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_git-pulls new file mode 100644 index 00000000..8dfc117d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_git-pulls @@ -0,0 +1,83 @@ +#compdef git-pulls +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for git-pulls 0.3.1 (https://git-pulls.com/schacon/git-pulls). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud (https://github.com/nicoulaj) +# +# ------------------------------------------------------------------------------ + + +_git-pulls() { + typeset -A opt_args + local context state line curcontext="$curcontext" + + local ret=1 + + _arguments -C \ + '(- 1 *)--help[show usage]' \ + '1:cmd:->cmds' \ + '*::arg:->args' \ + && ret=0 + + case "$state" in + (cmds) + local commands; commands=( + 'update:update pull requests list' + 'list:list pull requests' + 'show:show pull request' + 'browse:open pull request in a web browser' + 'merge:merge pull request' + ) + _describe -t commands 'command' commands && ret=0 + ;; + (args) + curcontext="${curcontext%:*:*}:git-pulls-cmd-$words[1]:" + case $words[1] in + (update) + _message 'no more arguments' && ret=0 + ;; + (list) + _arguments \ + '--reverse[list in reverse order]' \ + && ret=0 + ;; + (show) + _arguments \ + '1: :_git-pulls_pull_requests_numbers' \ + '--full[use verbose output]' \ + && ret=0 + ;; + (browse|merge) + _arguments \ + '1: :_git-pulls_pull_requests_numbers' \ + && ret=0 + ;; + esac + ;; + esac + + return ret +} + +(( $+functions[_git-pulls_pull_requests_numbers] )) || +_git-pulls_pull_requests_numbers() { + local pull_requests; pull_requests=(${${${(M)${(f)"$(_call_program users $service list)"}:#[[:digit:]]##[[:space:]]*}//:/\\:}/[[:space:]]##/:}) + _describe -t pull-request-numbers 'pull request number' pull_requests "$@" +} + +_git-pulls "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_git-revise b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_git-revise new file mode 100644 index 00000000..10908266 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_git-revise @@ -0,0 +1,71 @@ +#compdef git-revise +#description update, split and rearrange commits +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for git-revise 0.7.0 +# (https://github.com/mystor/git-revise/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Hannu Hartikainen (https://github.com/dancek) +# +# ------------------------------------------------------------------------------ + +__git-revise_commits() { + local -a commits + if git rev-parse --is-inside-work-tree 1>/dev/null 2>/dev/null; then + commits=(${(f)"$(git log -20 --pretty=format:'%h:%d %s' | sed 's/: /:/')"}) + _describe -V 'commit' commits + else + _message 'not a git repository' + fi +} + +__git-revise_branches() { + local -a branches + if git rev-parse --is-inside-work-tree 1>/dev/null 2>/dev/null; then + branches=(${(f)"$(git for-each-ref --format='%(refname:short)' refs/heads/)"}) + _describe 'branch' branches + else + _message 'not a git repository' + fi +} + +_git-revise() { + local curcontext="$curcontext" ret=1 + + _arguments -s \ + '(- :)'{-h,--help}'[show help message and exit]' \ + '--root[revise starting at the root commit]' \ + '--ref=[reference to update]: :__git-revise_branches' \ + '--reauthor[reset the author of the targeted commit]' \ + '(- :)--version[show version number and exit]' \ + '(--edit -e)'{--edit,-e}'[edit commit message of targeted commit(s)]' \ + '(--no-autosquash)--autosquash[automatically apply fixup! and squash! commits to their targets]' \ + '(--autosquash)--no-autosquash[force disable revise.autoSquash behaviour]' \ + '(--all -a)--no-index[ignore the index while rewriting history]' \ + '(--no-index --all -a)'{--all,-a}'[stage all tracked files before running]' \ + '(--interactive -i --message -m --cut -c --patch -p)'{--patch,-p}'[interactively stage hunks before running]' \ + '(--interactive -i --message -m --cut -c --patch -p)'{--interactive,-i}'[interactively edit commit stack]' \ + '(--interactive -i --message -m --cut -c --patch -p)'{--message,-m}'[specify commit message on command line]:MESSAGE:()' \ + '(--interactive -i --message -m --cut -c --patch -p)'{--cut,-c}'[interactively cut a commit into two smaller commits]' \ + '(--gpg-sign -S --no-gpg-sign)'{--gpg-sign,-S}'[GPG sign commits]' \ + '(--gpg-sign -S --no-gpg-sign)--no-gpg-sign[do not GPG sign commits]' \ + '1: :__git-revise_commits' && ret=0 + + return $ret +} + +_git-revise "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_git-wtf b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_git-wtf new file mode 100644 index 00000000..e0366adf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_git-wtf @@ -0,0 +1,65 @@ +#compdef git-wtf +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for git-wtf, authored by +# William Morgan (http://git-wt-commit.rubyforge.org/git-wtf) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Mario Fernandez (https://github.com/sirech) +# * Shohei YOSHIDA (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +__git_wtf_branches() { + local -a branches + branches=(${(f)"$(git for-each-ref --format='%(refname:short)' refs/heads/)"}) + _describe 'branch' branches +} + +_arguments -w -C -s \ + '(--long --short)'{-l,--long}'[include author info and date for each commit]' \ + '(--long --short)'{-s,--short}'[do not show commits]' \ + '(--all)'{-a,--all}'[show all branches across all remote repos, not just those from origin]' \ + '(--all-commits)'{-A,--all-commits}'[show all commits, not just the first 5]' \ + '(--key)'{-k,--key}'[show key]' \ + '(--relations)'{-r,--relations}'[show relation to features / integration branches]' \ + '(--dump-config)--dump-config[print out current configuration and exit]' \ + '*: :__git_wtf_branches' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_glances b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_glances new file mode 100644 index 00000000..043bd69a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_glances @@ -0,0 +1,125 @@ +#compdef glances +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for glances (https://nicolargo.github.io/glances/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * loranger (https://github.com/loranger) +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_glances() { + _arguments \ + '(- *)'{-h,--help}'[show this help message and exit]' \ + '(- *)'{-V,--version}"[show program's version number and exit]" \ + '(-C,--config)'{-C,--config}'[path to the configuration file]: :_files' \ + '(--modules-list --module-list)'{--modules-list,--module-list}'[display modules list and exit]' \ + '(--disable-plugin --disable-plugins)'{--disable-plugin,--disable-plugins}'[disable plugin(comma separated list or all)]:plugin' \ + '(--enable-plugin --enable-plugins)'{--enable-plugin,--enable-plugins}'[enable plugin(comma separated list)]:plugin' \ + '--disable-process[disable process module]' \ + '--disable-webui[disable the Web Interface]' \ + '(--light --enable-light)'{--light,--enable-light}'[light mode for Curses UI]' \ + '(-0 --disable-irix)'{-0,--disable-irix}"[task's cpu usage will be divided by the total number of CPUs]" \ + '(-1 --percpu)'{-1,--percpu}'[start Clances in per CPU mode]' \ + '(-2 --disable-left-sidebar)'{-2,--disable-left-sidebar}'[disable network, disk I/O, FS and sensors modules]' \ + '(-3 --disable-quicklook)'{-3,--disable-quicklook}'[disable quick look module]' \ + '(-4 --full-quicklook)'{-4,--full-quicklook}'[disable all but quick look and load]' \ + '(-5 --disable-top)'{-5,--disable-top}'[disable top menu(QL, CPU, MEM, SWAP and LOAD)]' \ + '(-6 --menugpu)'{-6,--menugpu}'[start Glances in mean GPU mode]' \ + '--disable-history[disable stats history]' \ + '--disable-bold[disable bold mode in the terminal]' \ + '--disable-bg[disable background colors in the terminal]' \ + '--enable-irq[enable IRQ mode]' \ + '--enable-process-extended[enable extended stats on top process]' \ + '(--separator --enable-separator)'{--separator,--enable-separator}'[enable separator in the UI]' \ + '--sort-process[sort processes]: :(cpu_percent memory_percent username cpu_times io_counters name)' \ + '(--programs --program)'{--programs,--program}'[Accumulate processes by program]' \ + '--export[enable export module]:module' \ + '--export-csv-file[file path for CSV exporter]: :_files' \ + '--export-csv-overwrite[overwrite existing CSV file]' \ + '--export-json-file[file path for JSON exporter]: :_files' \ + '--export-graph-path[Folder for Graph exporter]: :_files -/' \ + '(-c --client)'{-c,--client}'[connect to a Glances server]:host:_hosts' \ + '(-s --server)'{-s,--server}'[run Glances in server mode]' \ + '--browser[start the client browser]' \ + '--disable-autodiscover[disable autodiscover feature]' \ + '(-p --port)'{-p,--port}'[define the client/server TCP port]' \ + '(-B --bind)'{-B,--bind}'[bind server to the given IPv4/IPv6 address or hostname]:host:_hosts' \ + '--username[define a client/server username]' \ + '--password[define a client/server password]' \ + '-u[use the given client/server username]:user_name' \ + '--snmp-community[SNMP community]:community' \ + '--snmp-port[SNMP community]:port' \ + '--snmp-version[SNMP version]:version:(1 2c 3)' \ + '--snmp-user[SNMP user]:user' \ + '--snmp-auth[SNMP auth]:auth' \ + '--snmp-force[force SNMP mode]' \ + '(-t --time)'{-t,--time}'[set minimum refresh rate in seconds(default: 2 sec)]:seconds' \ + '(-w --webserver)'{-w,--webserver}'[run Glances in web server mode]' \ + '--cached-time[set the server cache time(default: 1 sec)]:seconds' \ + '--stop-after[stop Glances after n fresh]:' \ + '--open-web-browser[try to open the Web UI in the default browser]' \ + '(-q --quiet)'{-q,--quiet}'[do not display the curses interface]' \ + '(-f --process-filter)'{-f,--process-filter}'[set the process filter pattern]:regexp' \ + '--process-short-name[force short name for processes name]' \ + '--process-long-name[force long name for processes name]' \ + '--stdout[display stats to stdout one stat per line]:stats' \ + '--stdout-json[display stats to stdout, JSON format]:stats' \ + '--stdout-csv[display stats to CSV, JSON format]:stats' \ + '--issue[test all plugins and exit]' \ + '--trace-malloc[trace memory allocation and display it at the end of the process]' \ + '--memory-leak[test memory leak]' \ + '--api-doc[display fields descriptions]'\ + '--hide-kernel-threads[hide kernel threads in process list]' \ + '(-b --byte)'{-b,--byte}'[display network rate in byte per second]' \ + '--diskio-show-ramfs[show RAM Fs in the DiskIO plugin]' \ + '--diskio-iops[show IO per second in the DiskIO plugin]' \ + '--fahrenheit[display temperature in Fahrenheit]' \ + '--fs-free-space[display FS free space instead of used]' \ + '--sparkline[display sparklines instead of bar in the curses interface]' \ + '--disable-unicode[disable unicode characters in the curses interface]' \ + '--theme-white[optimize display colors for white background ]' \ + '--disable-check-update[disable online Glances version check]' \ + '--strftime[strftime format string for displaying current date in standalone mode]' \ +} + +_glances "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_golang b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_golang new file mode 100644 index 00000000..b14bf366 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_golang @@ -0,0 +1,1143 @@ +#compdef go -P -value-,GO*,-default- -P -value-,CGO*,-default- +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# Copyright (c) 2013-2015 Robby Russell and contributors (see +# https://github.com/ohmyzsh/ohmyzsh/graphs/contributors) +# Copyright (c) 2010-2014 Go authors +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +# ARE DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY DIRECT, +# INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for go 1.21 (https://go.dev/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Mikkel Oscar Lyderik Larsen +# * Paul Seyfert +# * oh-my-zsh authors: +# https://github.com/ohmyzsh/ohmyzsh/blob/master/plugins/golang/golang.plugin.zsh +# * Go authors +# +# ------------------------------------------------------------------------------ + +__go_buildmodes() { + local -a buildmodes + buildmodes=( + 'archive[non-main packages into .a files]' + 'c-archive[main package, plus all packages it imports, into a C archive file]' + 'c-shared[main package, plus all packages it imports, into a C shared library]' + 'default[main packages are built into executables and listed non-main packages are built into .a files]' + 'shared[non-main packages into a single shared library that will be used when building with the -linkshared option]' + 'exe[main packages into executables]' + 'pie[main packages and everything they import into position independent executables (PIE)]' + 'plugin[main packages, plus all packages that they import, into a Go plugin]' + ) + + _values 'mode' $buildmodes +} + + +__go_runtimedebug() { + local -a vars + vars=( + 'allocfreetrace[profile allocations]:boolean:(1 0)' + 'clobberfree[clobber memory after free]:boolean:(1 0)' + 'cgocheck[check passing go pointers to non-go]: :((0\:"no checks" 1\:"check checks" 2\:"expensive checks"))' + 'efence[allocate on unique pages]:boolean:(1 0)' + "gccheckmark[verify garbage collector's concurrent mark phase]:boolean:(1 0)" + 'gcpacertrace[print state of the concurrent pacer from garbage collector]:boolean:(1 0)' + 'gcshrinkstackoff[disable moving goroutines to smaller stacks]:boolean:(1 0)' + 'gcstoptheworld[disable concurrent garbage collection]: :((0\:default 1\:"disable concurrent garbage collection" 2\:"disable concurrent gc and sweeping"))' + 'gctrace[emit memory collection and pause information from the garbage collector]:boolean:(1 0)' + 'madvdontneed[use MADV_DONTNEED instead of MADV_FREE]:boolean:(1 0)' + 'memprofilerate[every N-th allocation should be profiled]:int:' + 'invalidptr[crash on invalid integers in pointer-type variables]:boolean:(1 0)' + 'sbrk[replace memory allocator and garbage collector by trivial allocator]:boolean:(1 0)' + 'scavenge[enable debugging mode of heap scavenger]:boolean:(1 0)' + 'scavtrace[emit scavenger work information (memory returned and memory utilization)]:boolean:(1 0)' + 'scheddetail[emit detailed states of scheduler, processors, threads, goroutines]:boolean:(1 0)' + 'schedtrace[emit scheduler state every N ms to stderr]:int' + 'tracebackancestors[set ancestor goroutines to be printed in goroutine creation stacks]:int' + 'asyncpreemptoff[disable signal-based asynchronous goroutine preemption.]:boolean:(1 0)' + ) + _values -s ',' -S '=' "runtime debug behaviour" $vars[@] +} + +__go_gcdebugflags() { + _values -s , -S = 'debug flag' \ + 'append[print information about append compilation]' \ + 'checkptr[instrument unsafe pointer conversions]:pointer conversion checks:((0\:"instrumentation disabled" 1\:"conversions involving unsafe.Pointer are instrumented" 2\:"conversions to unsafe.Pointer force heap allocation"))' \ + 'closure[print information about closure compilation]' \ + 'compilelater[compile functions as late as possible]' \ + 'disablenil[disable nil checks]' \ + 'dclstack[run internal dclstack check]' \ + 'gcprog[print dump of GC programs]' \ + 'libfuzzer[coverage instrumentation for libfuzzer]' \ + 'nil[print information about nil checks]' \ + 'panic[do not hide any compiler panic]' \ + 'slice[print information about slice compilation]' \ + 'typeassert[print information about type assertion inlining]' \ + 'wb[print information about write barriers]' \ + 'export[print export data]' \ + 'pctab[print named pc-value table]:pc-value:(pctospadj pctofile pctoline pctoinline pctopcdata)' \ + 'locationlists[print information about DWARF location list creation]' \ + 'typecheckinl[eager typechecking of inline function bodies]' \ + 'dwarfinl[print information about DWARF inlined function creation]' \ + 'softfloat[force compiler to emit soft-float code]' \ + 'defer[print information about defer compilation]' \ + 'ssa/help[print help about SSA debugging]' +} + +__go_gcflags() { + _arguments \ + '-%[debug non-static initializers]' \ + '-c=[concurrency during compilation]:int' \ + '-+[compiling runtime]' \ + '-B[disable bounds checking]' \ + '-C[disable printing of columns in error messages]' \ + '-D=[set relative path for local imports]:path: _path_files -/' \ + '-E[debug symbol export]' \ + '-I=[add directory to import search path]:directory: _path_files -/' \ + '-K[debug missing line numbers]' \ + '-L[show full file names in error messages]' \ + '-N[disable optimizations]' \ + '-S[print assembly listing]' \ + '-V[print version and exit]' \ + '-W[debug parse tree after type checking]' \ + '-asmhdr=[write assembly header to file]:file' \ + '-bench=[append benchmark times to file]:file' \ + '-blockprofile=[write block profile to file]:file' \ + '-buildid=[record id as the build id in the export metadata]:id' \ + '-complete[compiling complete package (no C or assembly)]' \ + '-cpuprofile=[write cpu profile to file]:file' \ + '-d=[print debug information about items in list; try -d help]:list: __go_gcdebugflags' \ + '-dwarf[generate DWARF symbols (default true)]' \ + '-dwarfbasentries[use base address selection entries in DWARF (default true)]' \ + '-dwarflocationlists[add location lists to DWARF in optimized mode (default true)]' \ + '-dynlink[support references to Go symbols defined in other shared libraries]' \ + '-e[no limit on number of errors reported]' \ + '-gendwarfinl=[generate DWARF inline info records (default 2)]:int' \ + '-goversion=[required version of the runtime]:string' \ + '-h[halt on error]' \ + '-importcfg=[read import configuration from file]:file' \ + '-installsuffix=[set pkg directory suffix]:suffix' \ + '-j[debug runtime-initialized variables]' \ + '-json=[version,destination for JSON compiler/optimizer logging]:string' \ + '-l[disable inlining]' \ + '-lang=[release to compile for]:string' \ + '-linkobj=[write linker-specific object to file]:file' \ + '-linkshared[generate code that will be linked against Go shared libraries]' \ + '-live[debug liveness analysis]' \ + '-m[print optimization decisions]' \ + '-memprofile=[write memory profile to file]:file' \ + '-memprofilerate=[set runtime.MemProfileRate to rate]:rate' \ + '-msan[build code compatible with C/C++ memory sanitizer]' \ + '-mutexprofile=[write mutex profile to file]:file' \ + '-newobj[use new object file format]' \ + '-nolocalimports[reject local (relative) imports]' \ + '-o=[write output to file]:file' \ + '-p=[set expected package import path]:path: _path_files -/' \ + '-pack[write to file.a instead of file.o]' \ + '-r[debug generated wrappers]' \ + '-race[enable race detector]' \ + '-shared[generate code that can be linked into a shared library]' \ + '-smallframes[reduce the size limit for stack allocated objects]' \ + '-spectre=[enable spectre mitigations]:mitigations:(all index ret)' \ + '-std[compiling standard library]' \ + '-symabis=[read symbol ABIs from file]:file' \ + '-traceprofile=[write an execution trace to file]:file' \ + '-trimpath=[remove prefix from recorded source file paths]:prefix' \ + '-v[increase debug verbosity]' \ + '-w[debug type checking]' \ + '-wb[enable write barrier (default true)]' \ +} + +__go_pgo() { + _alternative \ + "name:name:(auto off)" \ + "file:file:_files" +} + +local -a commands build_flags +commands=( +'bug:start a bug report' +'build:compile packages and dependencies' +'clean:remove object files and cached files' +'doc:show documentation for package or symbol' +'env:print Go environment information' +'fix:update packages to use new APIs' +'fmt:gofmt (reformat) package sources' +'generate:generate Go files by processing source' +'get:download and install packages and dependencies' +'install:compile and install packages and dependencies' +'list:list packages or modules' +'mod:module maintenance' +'work:workspace maintenance' +'run:compile and run Go program' +'test:test packages' +'tool:run specified go tool' +'version:print Go version' +'vet:report likely mistakes in packages' +'help:get more information about a command' +) + +__go_envvarvals() { + # if __go_envvarvals is called for -value-, I use the function argument to + # decide which variable to go to. if $1 is not set, then __go_envvarvals is + # called from the `go env` completion and the current word (with all after + # the first '=' removed) is the current variable. + local variable + variable=${1-${words[$CURRENT]%%=*}} + case $variable in + # commands + AR) + ;& + CC) + ;& + CXX) + ;& + FC) + ;& + GCCGO) + _command_names -e + ;; + # directories (using fallthrough) + GOBIN) + ;& + GOCACHE) + ;& + GOTMPDIR) + ;& + GOTOOLDIR) + ;& + GOROOT) + ;& + GOROOT_FINAL) + ;& + GCCGOTOOLDIR) + ;& + GOPATH) + ;& + GOMODCACHE) + _files -/ + ;; + # regular files (using fallthrough) + GOMOD) + ;& + PKG_CONFIG) + ;& + GOENV) + _files + ;; + # special + GOHOSTOS) + ;& + GOOS) + # from https://golang.org/doc/install/source#environment + _values 'operating system' aix android darwin dragonfly freebsd illumos ios js linux netbsd openbsd plan9 solaris windows wasip1 + ;; + GOHOSTARCH) + ;& + GOARCH) + _values 'architecture' amd64 386 arm64 arm ppc64 ppc64le mips mipsle mips64 mips64le riscv64 s390x wasm + ;; + CGO_ENABLED) + _values 'enable/disable cgo' 0 1 + ;; + GO_EXTLINK_ENABLED) + _values 'enable/disable external linkage' 0 1 + ;; + GOARM) + _values 'target arm architecture' 5 6 7 + ;; + GO386) + _values 'x86 floating point instruction set' 387 sse2 + ;; + GOAMD64) + _values 'amd64 instruction set' v1 v2 v3 v4 + ;; + GOMIPS*) + _values 'mips floating point instructions' hardfloat softfloat + ;; + GOPPC64) + _values 'powerpc64 instruction set' power8 power9 power10 + ;; + GOWASM) + _values 'web assembly features' -s ',' satconv signext + ;; + GOPROXY) + _urls + ;; + GOEXE) + _message "suffix for executables" + ;; + CGO_*FLAGS_*ALLOW) + _message "regexp" + ;; + CGO_*FLAGS) + _dispatch $service -value-,${variable#CGO_},-default- + ;; + GODEBUG) + __go_runtimedebug + ;; + GOFLAGS) + # not implemented, sorry + ;; + GOINSECURE) + ;& + GOPRIVATE) + ;& + GONOPROXY) + ;& + GONOSUMDB) + # comma separated glob patterns (in the syntax of Go's path.Match) + _message "comma separated glob pattern" + ;; + GOSUMDB) + _message "e.g. sum.golang.org+ https://sum.golang.org" + ;; + esac +} + +if [[ "$service" = -value-* ]]; then + variable=${${service%,-default-}#-value-,} + # some special variables are not read from the environment + local -a blacklist + blacklist=('GOEXE' 'GOGCCFLAGS' 'GOHOSTARCH' 'GOHOSTOS' 'GOMOD' 'GOTOOLDIR') + if (($blacklist[(I)$variable])); then + return + fi + __go_envvarvals $variable + return +fi + +_arguments \ + "1: :{_describe 'command' commands}" \ + '*:: :->args' + +case $state in + args) + build_flags=( + '-C[change to directory before running the command]: :_files -/' + '-a[force rebuilding of packages that are already up-to-date]' + '-n[print the commands but do not run them]' + '-p[number of builds that can be run in parallel]:number' + '-race[enable data race detection]' + '-msan[enable interoperation with memory sanitizer]' + '-asan[enable interoperation with address sanitizer]' + '-v[print the names of packages as they are compiled]' + '-work[print temporary work directory and keep it]' + '-x[print the commands]' + '-asmflags[arguments for each go tool asm invocation]:flags' + '-buildmode[build mode to use]:mode:__go_buildmodes' + '-buildvcs[stamp binaries with version control information]:mode:(internal external auto)' + '-compiler[name of compiler to use]:name' + '-gccgoflags[arguments for gccgo]:args' + '*-gcflags=[arguments for each go tool compile invocation]:args:__go_gcflags' + '-installsuffix[suffix to add to package directory]:suffix' + '-ldflags[arguments to pass on each go tool link invocation.]:flags' + '-linkshared[link against shared libraries]' + '-overlay[read a JSON config file that provides an overlay for build operations]:file:_files -g "*.json"' + '-pgo[specify the file path of a profile for profile-guided optimization]:file_or_profile:__go_pgo' + '-pkgdir[install and load all packages from dir]:dir' + '-tags[list of build tags to consider satisfied]:tags' + '-trimpath[remove all file system paths from the resulting executable]' + '-toolexec[program to use to invoke toolchain programs]:args' + ) + mod_flags=( + '-mod=[module download mode to use]:download mode:(readonly vendor mod)' + '-modcacherw[leave newly-created directories in the module cache read-write]' + '-modfile=[read an alternate go.mod file]:modfile: _files -g "*.mod"' + ) + + edit_flags=( + '-fmt[reformats the go.mod/work file without making other changes]' \ + '*-require=[add a requirement on the given module path and version]:require' \ + '*-droprequire=[drop a requirement on the given module path and version]:droprequire' \ + '-go[sets the expected Go language version]:goversion' \ + '*-replace=[add a replacement of the given module path and version]:replace' \ + '*-dropreplace=[drop a replacement of the given module path and version]:dropreplace' \ + '-json[prints the final go.mod/work file in JSON format]' \ + '-print[prints the final go.mod/work in its text format]' \ + ) + + __go_packages() { + local gopaths + declare -a gopaths + gopaths=("${(s/:/)$(go env GOPATH)}") + gopaths+=("$(go env GOROOT)") + for p in $gopaths; do + _path_files $@ -W "$p/src" -/ + done + # no special treatment for + # - relative paths starting with .. + # - absolute path starting with / + # - variables, substitutions, subshells + if [[ $words[$CURRENT] = ..* || $words[$CURRENT] = \$* || $words[$CURRENT] = /* ]]; then + _path_files $@ -/ -g '*.go' + else + # go build accepts paths relative to the cwd but they must start with './', so prefix them + _path_files $@ -P './' -/ -g '*.go' + fi + } + + case $words[1] in + build) + _arguments \ + '-o[force build to write to named output file or directory]:file or directory:_files' \ + ${build_flags[@]} \ + ${mod_flags[@]} \ + '*:importpaths:__go_packages' + ;; + + clean) + _arguments \ + '-i[remove corresponding installed archive or binary]' \ + '-r[apply clean recursively on all dependencies]' \ + '-cache[remove the entire go build cache]' \ + '-testcache[expire all test results in the go build cache]' \ + '-modcache[clean to remove the entire module download cache]' \ + '-fuzzcache[remove files stored in the Go build cache for fuzz testing]' \ + ${build_flags[@]} \ + ${mod_flags[@]} \ + '*:importpaths:__go_packages' + ;; + + doc) + _arguments \ + '-all[show all the documentation for the package]' \ + '-c[respect case when matching symbols]' \ + '-cmd[treat a command (package main) like a regular package]' \ + '-short[one-line representation for each symbol]' \ + '-src[show the full source code for the symbol]' \ + '-u[show docs for unexported and exported symbols and methods]' + ;; + + env) + local -a goenvvars + goenvvars=( + "GOARCH[architecture, or processor, for which to compile code.]:architecture" + "GCCGO[gccgo command to run.]:gccgo command" + "GOBIN[directory where 'go install' installs to]:go install target dir" + "GOCACHE[directory to store cached information]:go build cache dir" + "GODEBUG[enable runtime debug facilities]:runtime debug settings" + "GOENV[location of the go environment configuration file]:configuration file" + "GOFLAGS[default go command line flags]:space separated default command line flags" + "GOINSECURE[module prefixes that are fetched insecurely]:comma separated module prefixes" + "GOOS[target operating system]:operating system" + "GOPATH[path to resolve import statements]:import path" + "GOPROXY[URL of go module proxy]:proxy url" + "GOROOT[root of the go tree]:go root directory" + "GOTMPDIR[directory for temporary sources, packages, and binaries]:tmp directory" + "GOPRIVATE[modules that should always be fetched directly]:comma separated glob patterns" + "GONOPROXY[modules that should always be fetched directly]:comma separated glob patterns" + "GONOSUMDB[modules that should not be compared against the checksum db]:comma separated glob patterns" + "GOMODCACHE[module cache directory]:path" + "GOSUMDB[checksum database]:name(+publickey( url))" + "AR[command for manipulating library archives (for gccgo)]:archive manipulation program" + "CC[command to compile C code]:C compiler" + "CGO_ENABLED[enable/disable cgo]:boolean" + "CGO_CFLAGS[flags passed to the compiler for C code]:C compilation flags" + "CGO_CFLAGS_ALLOW[additional flags to allow to appear in #cgo CFLAGS]:regular expression" + "CGO_CFLAGS_DISALLOW[flags that must be disallowed from appearing in #cgo CFLAGS]" + "CGO_CPPFLAGS[flags passed to the C preprocessor]:C preprocessor flags" + "CGO_CPPFLAGS_ALLOW[additional flags to allow to appear in #cgo CPPFLAGS]:regular expression" + "CGO_CPPFLAGS_DISALLOW[flags that must be disallowed from appearing in #cgo CPPFLAGS]" + "CGO_CXXFLAGS[flags passed to the compiler for C++ code]:C++ compilation flags" + "CGO_CXXFLAGS_ALLOW[additional flags to allow to appear in #cgo CXXFLAGS]:regular expression" + "CGO_CXXFLAGS_DISALLOW[flags that must be disallowed from appearing in #cgo CXXFLAGS]" + "CGO_FFLAGS[flags passed to the compiler for Fortran code]:Fortran compilation flags" + "CGO_FFLAGS_ALLOW[additional flags to allow to appear in #cgo FFLAGS]:regular expression" + "CGO_FFLAGS_DISALLOW[flags that must be disallowed from appearing in #cgo FFLAGS]" + "CGO_LDFLAGS[flags passed to the compiler for linker]:linker flags" + "CGO_LDFLAGS_ALLOW[additional flags to allow to appear in #cgo LDFLAGS]:regular expression" + "CGO_LDFLAGS_DISALLOW[flags that must be disallowed from appearing in #cgo LDFLAGS]" + "CXX[command to compile C++]:C++ compiler" + "FC[command to compile Fortran]:Fortran compiler" + "PKG_CONFIG[Path to pkg-config tool.]:path to pkg-config" + "GOARM[arm architecture]:arm architecture" + "GO386[x86 instruction set]:x86 instruction set" + "GOAMD64[amd64 instruction set]:amd64 instruction set" + "GOMIPS[mips instruction set]:mips instruction set" + "GOMIPS64[mips64 instruction set]:mips64 instruction set" + "GOPPC64[powerpc64 instruction set]:powerpc64 instruction set" + "GOWASM[web assembly features]:comma separated web assembly features" + "GCCGOTOOLDIR[directory of gccgo tools]:gccgo tool directory" + "GOROOT_FINAL[root of the go tree]:go root" + "GO_EXTLINK_ENABLED[enable external linking mode]:boolean" + "GIT_ALLOW_PROTOCOL[schemes allowed to fetch]:colon separated git schemes" + "GOEXE[suffix for executables]:executable suffix" + "GOGCCFLAGS[arguments supplied to CC]:space separated arguments to CC" + "GOHOSTARCH[architecture of the toolchain binaries]:host os architecture" + "GOHOSTOS[operating system of the toolchain binaries]:host os" + "GOMOD[absolute path the the main go.mod]:abs path to main go.mod" + "GOTOOLDIR[installation directory of go tools]:tool installation directory" + ) + local -a exclude_from_w + exclude_from_w=(GOENV) + + __list_env_vars() { + # the parameter expansion strops off everything after the first [ + _values -s ' ' -w 'environment variable' ${goenvvars[@]%%\[*} + } + + # the ^ parameter expansion appends ": __go_envvarvals" to every element of goenvvars + # the :# parameter expansion removes all elements matching GOENV* + [[ $words[2] != '-w' ]] && _arguments \ + '-C[change to directory before running the command]: :_files -/' \ + '-json[print the environment in JSON format]' \ + '-u[unset environment variables]' \ + '-w[change the default setting of environment variables]' \ + '*:[show environment variable]: __list_env_vars' || _values \ + -s ' ' -S "=" -w 'environment variable' ${^goenvvars:#GOENV*}": __go_envvarvals" + ;; + + fix) + _arguments \ + '-C[change to directory before running the command]: :_files -/' \ + '*:importpaths:__go_packages' + ;; + + fmt) + _arguments \ + '-C[change to directory before running the command]: :_files -/' \ + '-n[prints commands that would be executed]' \ + '-x[prints commands as they are executed]' \ + '*:importpaths:__go_packages' + ;; + + generate) + _arguments \ + '-C[change to directory before running the command]: :_files -/' \ + '-run=[specifies a regular expression to select directives]:regex' \ + '-x[print the commands]' \ + '-n[print the commands but do not run them]' \ + '-v[print the names of packages as they are compiled]' \ + "*:args:{ _alternative ':importpaths:__go_packages' _files }" + ;; + + get) + # no mod_flags for get + _arguments \ + '-d[instructs get to stop after downloading the packages]' \ + '-f[force get -u not to verify that each package has been checked from vcs]' \ + '-fix[run the fix tool on the downloaded packages]' \ + '-insecure[permit fetching/resolving custom domains]' \ + '-t[also download the packages required to build tests]' \ + '-u[use the network to update the named packages]' \ + ${build_flags[@]} \ + '*:importpaths:__go_packages' + ;; + + install) + _arguments ${build_flags[@]} \ + '*:importpaths:__go_packages' + ;; + + list) + local -a list_args + list_args=( + '-e[changes the handling of erroneous packages]' + '-f[specifies an alternate format for the list]:format' + '-json[causes package data to be printed in JSON format]' + '-compiled[set CompiledGoFiles to the Go source files presented to the compiler]' + '-deps[iterate over named packages and their dependencies]' + '-m[list modules instead of packages]' + ${build_flags[@]} + ${mod_flags[@]} + '*:importpaths:__go_packages' + ) + # -u and -versions are only available if -m is present on the commandline + if (($words[(I)-m])); then + list_args+=( + '-u[adds information about available upgrades]' + '-versions[list all known versions of modules]' + ) + fi + _arguments ${list_args[@]} + ;; + + mod) + local -a mod_commands + mod_commands=( + 'download:download modules to local cache' + 'edit:edit go.mod from tools or scripts' + 'graph:print module requirement graph' + 'init:initialize new module in current directory' + 'tidy:add missing and remove unused modules' + 'vendor:make vendored copy of dependencies' + 'verify:verify dependencies have expected content' + 'why:explain why packages or modules are needed' + 'help:get more information about a command' + ) + + _arguments \ + "1: :{_describe 'command' mod_commands}" \ + '*:: :->args' + + case $state in + args) + case $words[1] in + download) + _arguments \ + '-json[print a sequence of JSON objects to standard output]' \ + '-x[print the commands download executes]' + ;; + + edit) + _arguments \ + ${edit_flags[@]} \ + "-module[change the module's path]" \ + '*-exclude=[add an exclusion for the given module path and version]:exclude' \ + '*-dropexclude=[drop an exclusion for the given module path and version]:dropexclude' \ + ':go.mod:_path_files -g "go.mod"' + ;; + graph) + _arguments \ + '-go[report the module graph as loaded by the given Go version]:goversion' + ;; + init) + # Use go packages as module name suggestion + _arguments \ + '*:module:__go_packages' + ;; + tidy) + _arguments \ + '-v[print information about removed modules to standard error]' \ + '-e[attempt to proceed despite errors encountered while loading packages]' \ + '-go[update the go directive in the go.mod file to the given version]:goversion' \ + '-compat[preserves additional checksums needed for the indicated Go version]' + ;; + vendor) + _arguments \ + '-v[print the names of vendored modules and packages to standard error]' \ + '-e[attempt to proceed despite errors encountered while loading packages]' \ + '-o[create the vendor directory at the given path instead of "vendor"]:directory:_path_files -/' + ;; + verify) + ;; + why) + _arguments \ + '-m[treats the arguments as a list of modules]' \ + '-vendor[exclude tests of dependencies]' \ + '*:module:__go_packages' + ;; + esac + ;; + esac + ;; + + run) + _arguments \ + ${build_flags[@]} \ + '-exec[invoke the binary using xprog]:xporg' \ + '*:importpaths:__go_packages' + ;; + + test) + if [[ $words[$CURRENT] = -test.* ]]; then + _arguments \ + '-test.bench[run only benchmarks matching regexp]:regexp' \ + '-test.benchmem[print memory allocations for benchmarks]' \ + '-test.benchtime[run each benchmark for duration d (default 1s)]:d' \ + '-test.blockprofile[write a goroutine blocking profile to file]:file:_files' \ + '-test.blockprofilerate[set blocking profile rate (see runtime.SetBlockProfileRate) (default 1)]:rate' \ + '-test.count[run tests and benchmarks n times (default 1)]:n' \ + '-test.coverprofile[write a coverage profile to file]:file:_files' \ + '-test.cpu[comma-separated list of cpu counts to run each test with]:comma-separated list' \ + '-test.cpuprofile[write a cpu profile to file]:file:_files' \ + '-test.failfast[do not start new tests after the first test failure]' \ + '-test.list[list tests, examples, and benchmarks matching regexp then exit]:regexp' \ + '-test.fuzz[run the fuzz test matching regexp]:regexp' \ + '-test.fuzzcachedir[directory where interesting fuzzing inputs are stored]:dir:_path_files -/' \ + '-test.fuzzminimizetime[time to spend minimizing a value after finding a failing input (default 1m0s)]:t' \ + '-test.fuzztime[time to spend fuzzing; default is to run indefinitely]:t' \ + '-test.fuzzworker[coordinate with the parent process to fuzz random values (for use only by cmd/go)]' \ + '-test.list[list tests, examples, and benchmarks matching regexp then exit]:regexp' \ + '-test.memprofile[write an allocation profile to file]:file:_files' \ + '-test.memprofilerate[set memory allocation profiling rate (see runtime.MemProfileRate)]:rate' \ + '-test.mutexprofile[write a mutex contention profile to the named file after execution]:string' \ + '-test.mutexprofilefraction[if >= 0, calls runtime.SetMutexProfileFraction() (default 1)]:int' \ + '-test.outputdir[write profiles to dir]:dir:_path_files -/' \ + '-test.paniconexit0[panic on call to os.Exit(0)]' \ + '-test.parallel[run at most n tests in parallel (default 4)]:n' \ + '-test.run[run only tests and examples matching regexp]:regexp' \ + '-test.short[run smaller test suite to save time]' \ + '-test.shuffle[randomize the execution order of tests and benchmarks (default "off")]:string' \ + '-test.testlogfile[write test action log to file (for use only by cmd/go)]:file' \ + '-test.timeout[panic test binary after duration d (default 0, timeout disabled)]:d' \ + '-test.trace[write an execution trace to file]:file' \ + '-test.v[verbose: print additional output]' + else + _arguments \ + "-c[compile but don't run test]" \ + '-bench[run benchmarks matching the regular expression]:regexp' \ + '-benchmem[print memory allocation statistics for benchmarks]' \ + '-benchtime[run benchmarks for t rime]:t' \ + '-blockprofile[write a goroutine blocking profile to the specified file]:block' \ + '-blockprofilerate[control goroutine blocking profiles]:n' \ + '-count[run each test and benchmark n times]:n' \ + '-cover[enable coverage analysis]' \ + '-covermode[set the mode for coverage analysis]:mode:(set count atomic)' \ + '-coverpkg[apply coverage analysis in each test of listed packages]:list' \ + '-coverprofile[write a coverage profile to file]:cover' \ + '-cpu[specify a list of GOMAXPROCS values]:cpus' \ + '-cpuprofile[write a CPU profile to the specified file]:profile' \ + '-failfast[do not start new tests after the first test failure]' \ + '-fullpath[show full file names in the error messages]' \ + '-fuzz[run the fuzz test matching the regular expression]:regexp' \ + '-fuzztime[run enough iterations of the fuzz target during fuzzing]:t' \ + '-fuzzminimizetime[run enough iterations of the fuzz target during each minimization attempt]:t' \ + '-json[log verbose output and test results in JSON]' \ + '-list[list tests, benchmarks, fuzz tests, or examples matching the regular expression]:regexp' \ + '-memprofile[write a memory profile to file]:mem' \ + '-memprofilerate[enable more precise memory profiles]:n' \ + '-mutexprofile[write a mutex contention profile to the specified file]:file:_files' \ + '-outputdir[place output files from profiling in output dir]:dir' \ + '-parallel[allow parallel execution of test functions]:n' \ + '-run[run tests and examples matching the regular expression]:regexp' \ + '-short[tell long-running tests to shorten their run time]' \ + '-shuffle[randomize the execution order of tests and benchmarks]:type:(off on)' \ + '-test.-[specify options for test running]:test running options:' \ + '-timeout[timeout long running tests]:t' \ + '-trace[write an execution trace to the specified file]:trace' \ + '-v[verbose output]' \ + '-vet[configure the invocation of "go vet" during "go test" to use the comma-separated list of vet checks]:list' \ + ${build_flags[@]} \ + '-exec[run test binary using xprog]:xprog' \ + '-o[compile test binary to named file]:file:_files' \ + '*:importpaths:__go_packages' + fi + ;; + + tool) + local -a tools + tools=($(go tool)) + + _arguments \ + '-n[print command that would be executed]' \ + "1: :{_describe 'tool' tools}" \ + '*:: :->args' + + case $state in + args) + case $words[1] in + addr2line) + _files + ;; + + asm) + _arguments \ + '-D[predefined symbol with optional simple value]:value' \ + '-I[include directory]:value' \ + '-S[print assembly and machine code]' \ + '-debug[dump instructions as they are parsed]' \ + '-dynlink[support references to Go symbols]' \ + '-o[output file]:string' \ + '-shared[generate code that can be linked into a shared lib]' \ + '-trimpath[remove prefix from recorded source file paths]:string' + ;; + + callgraph) + local -a algos graphs + algos=( + 'static:static calls only' + 'cha:Class Hierarchy Analysis' + 'rta:Rapid Type Analysis' + 'pta:inclusion-based Points-To Analysis' + ) + graphs=( + 'digraph:output in digraph format' + 'graphviz:output in AT&T GraphViz (.dot) format' + ) + + _arguments \ + '-algo=[call-graph construction algorithm]:algos:{ _describe "algos" algos }' \ + "-test[include the package's tests in the analysis]" \ + '-format=[format in which each call graph edge is displayed]:graphs:{ _describe "graphs" graphs }' + ;; + + cgo) + _arguments \ + '-debug-define[print relevant #defines]' \ + '-debug-gcc[print gcc invocations]' \ + '-dynimport[if non-empty, print dynamic import data]:string' \ + '-dynlinker[record dynamic linker information]' \ + '-dynout[write -dynimport output to file]:file' \ + '-dynpackage[set Go package for -dynimport output]:string' \ + '-exportheader[where to write export header]:string' \ + '-gccgo[generate files for use with gccgo]' \ + '-gccgopkgpath[-fgo-pkgpath option used with gccgo]:string' \ + '-gccgoprefix[-fgo-prefix option used with gccgo]:string' \ + '-godefs[write Go definitions for C file to stdout]' \ + '-import_runtime_cgo[import runtime/cgo in generated code]' \ + '-import_syscall[import syscall in generated code]' \ + '-importpath[import path of package being built]:path' \ + '-objdir[object directory]:dir' + ;; + + compile) + _arguments \ + '-%[debug non-static initializers]' \ + '-+[compiling runtime]' \ + "-A[for bootstrapping, allow 'any' type]" \ + '-B[disable bounds checking]' \ + '-D[set relative path for local imports]:path' \ + '-E[debug symbol export]' \ + '-I[add directory to import search path]:directory' \ + '-K[debug missing line numbers]' \ + '-L[use full (long) path in error messages]' \ + '-M[debug move generation]' \ + '-N[disable optimizations]' \ + '-P[debug peephole optimizer]' \ + '-R[debug register optimizer]' \ + '-S[print assembly listing]' \ + '-V[print compiler version]' \ + '-W[debug parse tree after type checking]' \ + '-asmhdr[write assembly header to file]:file' \ + '-buildid[record id as the build id in the export metadata]:id' \ + '-complete[compiling complete package (no C or assembly)]' \ + '-cpuprofile[write cpu profile to file]:file' \ + '-d[print debug information about items in list]:list' \ + '-dynlink[support references to Go symbols]' \ + '-e[no limit on number of errors reported]' \ + '-f[debug stack frames]' \ + '-g[debug code generation]' \ + '-h[halt on error]' \ + '-i[debug line number stack]' \ + '-installsuffix[set pkg directory suffix]:suffix' \ + '-j[debug runtime-initialized variables]' \ + '-l[disable inlining]' \ + '-largemodel[generate code that assumes a large memory model]' \ + '-live[debug liveness analysis]' \ + '-m[print optimization decisions]' \ + '-memprofile[write memory profile to file]:file' \ + '-memprofilerate[set runtime.MemProfileRate to rate]:rate' \ + '-nolocalimports[reject local (relative) imports]' \ + '-o[write output to file]:file' \ + '-p[set expected package import path]:path' \ + '-pack[write package file instead of object file]' \ + '-r[debug generated wrappers]' \ + '-race[enable race detector]' \ + '-s[warn about composite literals that can be simplified]' \ + '-shared[generate code that can be linked into a shared library]' \ + '-trimpath[remove prefix from recorded source file paths]:prefix' \ + '-u[reject unsafe code]' \ + '-v[increase debug verbosity]' \ + '-w[debug type checking]' \ + '-wb[enable write barrier (default 1)]' \ + '-x[debug lexer]' \ + '-y[debug declarations in canned imports (with -d)]' \ + '*:file:_files -g "*.go(-.)"' + ;; + + cover) + if (( CURRENT == 2 )); then + _arguments \ + '-func=[output coverage profile information for each function]:string' \ + '-html=[generate HTML representation of coverage profile]:file:_files' \ + '-mode=[coverage mode]:mode:(set count atomic)' + return + fi + + _arguments \ + '-o[file for output]:file' \ + '-var=[name of coverage variable to generate]:var' \ + '*:file:_files -g "*.go(-.)"' + ;; + + doc) + _arguments \ + '-c[respect case when matching symbols]' \ + '-cmd[treat a command (package main) like a regular package]' \ + '-u[show docs for unexported and exported symbols and methods]' \ + ;; + + fix) + _arguments \ + '-diff[display diffs instead of rewriting files]' \ + '-force[force fixes to run even if the code looks updated]:string' \ + '-r[restrict the rewrites]:string' \ + '*:files:_files' + ;; + + link) + _arguments \ + '-B[add an ELF NT_GNU_BUILD_ID note when using ELF]:note' \ + '-C[check Go calls to C code]' \ + '-D[set data segment address (default -1)]:address' \ + '-E[set entry symbol name]:entry' \ + '-H[set header type]:type' \ + '-I[use linker as ELF dynamic linker]:linker' \ + '-L[add specified directory to library path]:directory' \ + '-R[set address rounding quantum (default -1)]:quantum' \ + '-T[set text segment address (default -1)]:address' \ + '-V[print version and exit]' \ + '-W[disassemble input]' \ + '-X[add string value definition]:definition' \ + '-a[disassemble output]' \ + '-buildid[record id as Go toolchain build id]:id' \ + '-buildmode[set build mode]:mode' \ + '-c[dump call graph]' \ + '-cpuprofile[write cpu profile to file]:file' \ + '-d[disable dynamic executable]' \ + '-extld[use linker when linking in external mode]:linker' \ + '-extldflags[pass flags to external linker]:flags' \ + '-f[ignore version mismatch]' \ + '-g[disable go package data checks]' \ + '-h[halt on error]' \ + '-installsuffix[set package directory suffix]:suffix' \ + '-k[set field tracking symbol]:symbol' \ + '-linkmode[set link mode]:mode:(internal external auto)' \ + '-linkshared[link against installed Go shared libraries]' \ + '-memprofile[write memory profile to file]:file' \ + '-memprofilerate[set runtime.MemProfileRate to rate]:rate' \ + '-n[dump symbol table]' \ + '-o[write output to file]:file' \ + '-r[set the ELF dynamic linker search path to dir1:dir2:...]:path' \ + '-race[enable race detector]' \ + '-s[disable symbol table]' \ + '-shared[generate shared object (implies -linkmode external)]' \ + '-tmpdir[use directory for temporary files]:directory' \ + '-u[reject unsafe packages]' \ + '-v[print link trace]' \ + '-w[disable DWARF generation]' \ + '*:files:_files' + ;; + + objdump) + _arguments \ + '-s[only dump symbols matching this regexp]:regexp' \ + '*:files:_files' + ;; + + pack) + _arguments '1:ops:(c p r t x)' '::verbose:(v)' ':files:_files' + ;; + + pprof) + _arguments \ + '-callgrind[outputs a graph in callgrind format]' \ + '-disasm=[output annotated assembly]:p' \ + '-dot[outputs a graph in DOT format]' \ + '-eog[visualize graph through eog]' \ + '-evince[visualize graph through evince]' \ + '-gif[outputs a graph image in GIF format]' \ + '-gv[visualize graph through gv]' \ + '-list=[output annotated source for functions matching regexp]:p' \ + '-pdf[outputs a graph in PDF format]' \ + '-peek=[output callers/callees of functions matching regexp]:p' \ + '-png[outputs a graph image in PNG format]' \ + '-proto[outputs the profile in compressed protobuf format]' \ + '-ps[outputs a graph in PS format]' \ + '-raw[outputs a text representation of the raw profile]' \ + '-svg[outputs a graph in SVG format]' \ + '-tags[outputs all tags in the profile]' \ + '-text[outputs top entries in text form]' \ + '-top[outputs top entries in text form]' \ + '-tree[outputs a text rendering of call graph]' \ + '-web[visualize graph through web browser]' \ + '-weblist=[output annotated source in HTML]:p' \ + '-output=[generate output on file f (stdout by default)]:f' \ + '-functions[report at function level (default)]' \ + '-files[report at source file level]' \ + '-lines[report at source line level]' \ + '-addresses[report at address level]' \ + '-base[show delta from this profile]:profile' \ + '-drop_negative[ignore negative differences]' \ + '-cum[sort by cumulative data]' \ + '-seconds=[length of time for dynamic profiles]:n' \ + '-nodecount=[max number of nodes to show]:n' \ + '-nodefraction=[hide nodes below *total]:f' \ + '-edgefraction=[hide edges below *total]:f' \ + '-sample_index[index of sample value to display]' \ + '-mean[average sample value over first value]' \ + '-inuse_space[display in-use memory size]' \ + '-inuse_objects[display in-use object counts]' \ + '-alloc_space[display allocated memory size]' \ + '-alloc_objects[display allocated object counts]' \ + '-total_delay[display total delay at each region]' \ + '-contentions[display number of delays at each region]' \ + '-mean_delay[display mean delay at each region]' \ + '-runtime[show runtime call frames in memory profiles]' \ + '-focus=[restricts to paths going through a node matching regexp]:r' \ + '-ignore=[skips paths going through any nodes matching regexp]:r' \ + '-tagfocus=[restrict to samples tagged with key:value matching regexp]:r' \ + '-tagignore=[discard samples tagged with key:value matching regexp]' \ + '-call_tree[generate a context-sensitive call tree]' \ + '-unit=[convert all samples to unit u for display]:u' \ + '-divide_by=[scale all samples by dividing them by f]:f' \ + '-buildid=[override build id for main binary in profile]:id' \ + '-tools=[search path for object-level tools]:path' \ + '-help[help message]' \ + '*:files:_files' + ;; + + trace) + _arguments \ + '-http=[HTTP service address]:addr' \ + '*:files:_files' + ;; + + vet) + _arguments \ + '-all[check everything]' \ + '-asmdecl[check assembly against Go declarations]' \ + '-assign[check for useless assignments]' \ + '-atomic[check for common mistaken usages of the sync/atomic]' \ + '-bool[check for mistakes involving boolean operators]' \ + '-buildtags[check that +build tags are valid]' \ + '-composites[check that composite literals used field-keyed elements]' \ + '-compositewhitelist[use composite white list]' \ + '-copylocks[check that locks are not passed by value]' \ + '-methods[check that canonically named methods are canonically defined]' \ + '-nilfunc[check for comparisons between functions and nil]' \ + '-printf[check printf-like invocations]' \ + '-printfuncs[print function names to check]:string' \ + '-rangeloops[check that range loop variables are used correctly]' \ + '-shadow[check for shadowed variables]' \ + '-shadowstrict[whether to be strict about shadowing]' \ + '-shift[check for useless shifts]' \ + '-structtags[check that struct field tags have canonical format]' \ + '-tags[list of build tags to apply when parsing]:list' \ + '-test[for testing only: sets -all and -shadow]' \ + '-unreachable[check for unreachable code]' \ + '-unsafeptr[check for misuse of unsafe.Pointer]' \ + '-unusedfuncs[list of functions whose results must be used]:string' \ + '-unusedresult[check for unused result of calls to functions in -unusedfuncs]' \ + '-unusedstringmethods[list of methods whose results must be used]:string' \ + '-v[verbose]' \ + '*:files:_files' + ;; + + yacc) + _arguments \ + '-o[output]:output' \ + '-v[parsetable]:parsetable' \ + '*:files:_files' + ;; + esac + ;; + esac + ;; + + version) + _arguments \ + '-m[print each executable embedded module version information]' \ + '-v[report unrecognized files]' \ + '*:files:_files' + ;; + + + vet) + _arguments \ + '-n[print commands that would be executed]' \ + '-x[prints commands as they are executed]' \ + ${build_flags[@]} \ + '*:importpaths:__go_packages' + ;; + + work) + local -a work_commands + work_commands=( + 'edit:edit go.work from tools or scripts' + 'init:initialize workspace file' + 'sync:sync workspace build list to modules' + 'use:add modules to workspace file' + ) + + _arguments \ + "1: :{_describe 'command' work_commands}" \ + '*:: :->args' + + case $state in + args) + case $words[1] in + edit) + _arguments \ + ${edit_flags[@]} \ + '*-use[add use directive from the go.work set of module directories]' \ + '*-dropuse[drop use directive from the go.work set of module directories]' \ + ':go.work:_path_files -g "go.work"' + ;; + + init) + _arguments \ + '*:directory: _path_files -/' + ;; + + sync) + ;; + + use) + _arguments \ + '-r[searches recursively for modules in the argumentdirectories]' \ + '*:directory: _path_files -/' + ;; + esac + ;; + esac + ;; + + + help) + local -a topics + topics=( + 'buildconstraint:build constraints' + 'buildmode:build modes' + 'c:calling between Go and C' + 'cache:build and test caching' + 'environment:environment variables' + 'filetype:file types' + 'go.mod:the go.mod file' + 'gopath:GOPATH environment variable' + 'gopath-get:legacy GOPATH go get' + 'goproxy:module proxy protocol' + 'importpath:import path syntax' + 'modules:modules, module versions, and more' + 'module-get:module-aware go get' + 'module-auth:module authentication using go.sum' + 'packages:package lists and patterns' + 'private:configuration for downloading non-public code' + 'testflag:testing flags' + 'testfunc:testing functions' + 'vcs:controlling version control with GOVCS' + ) + + _arguments "1: :{_describe 'command' commands -- topics}" + ;; + esac + ;; +esac + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_google b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_google new file mode 100644 index 00000000..4a5e567d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_google @@ -0,0 +1,94 @@ +#compdef google +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for googlecl (https://code.google.com/p/googlecl/) +# +# Source: https://raw.github.com/dadrc/zsh-cfg/master/completions/_google +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * dadrc (https://github.com/dadrc) +# * Ben O'Hara (https://github.com/benohara) +# +# ------------------------------------------------------------------------------ + +_google() { + # init variables + local curcontext="$curcontext" state line + typeset -A opt_args + + # init state + _arguments \ + '1: :->service'\ + '2: :->task' + + case $state in + service) + _arguments '1:service:(picasa blogger youtube docs contacts calendar finance)' + ;; + *) + case $words[2] in + picasa) + compadd "$@" get create list list-albums tag post delete + ;; + blogger) + compadd "$@" post tag list delete + ;; + youtube) + compadd "$@" post tag list delete + ;; + docs) + compadd "$@" edit delete list upload get + ;; + contacts) + compadd "$@" list list-groups add add-groups delete-groups delete + ;; + calendar) + compadd "$@" add list today delete + ;; + finance) + compadd "$@" list-txn delete-pos create-pos delete-txn create create-txn list list-pos delete + ;; + *) + esac + esac +} + +_google "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_gpgconf b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_gpgconf new file mode 100644 index 00000000..5b4b8892 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_gpgconf @@ -0,0 +1,77 @@ +#compdef gpgconf +# Copyright (c) 2021 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + +# Description: +# Completions for gpgconf (configuration utility provided with GnuPG +# ) +# +# Authors: +# * "score" https://keybase.io/score_under + +_gpgconf_component() { + local values=( + "${(@f)$(gpgconf --list-components | awk -F: '{printf "%s[%s]\n", $1, $2}')}" + ) + if [ "${action[2]}" = all ]; then + values+=('all[All daemon components]') + fi + + _values 'component' "${(o)values[@]}" +} + +_arguments \ + '--help[print help text]' \ + '--list-components[list all components]' \ + '--check-programs[check all programs]' \ + '--apply-defaults[apply global default values]' \ + '--list-dirs[get the configuration directories for gpgconf]' \ + '--list-config[list global configuration file]' \ + '--check-config[check global configuration file]' \ + '--query-swdb[query the software version database]' \ + '--reload[reload all or a given component]:component:_gpgconf_component all' \ + '--launch[launch a given component]:component:_gpgconf_component all' \ + '--kill[kill a given component]:component:_gpgconf_component all' \ + '--create-socketdir[create a directory for sockets below /run/user or /var/run/user]' \ + '--remove-socketdir[remove a directory created with command --create-socketdir]' \ + '--list-options[list options]:component:_gpgconf_component' \ + '--change-options[change options]:component:_gpgconf_component' \ + '--check-options[check options]:component:_gpgconf_component' \ + '--apply-profile[update configuration files using the specified file]:configuration file:_path_files' \ + '--status-fd[write status info to the specified file descriptor]:file descriptor' \ + '--homedir[specify an alternative gnupg configuration home directory]:directory:_directories' \ + '(-o --output)'{-o,--output}'[write output to the specified file]:output file:_path_files' \ + '(-v --verbose)'{-v,--verbose}'[verbose]' \ + '(-q --quiet)'{-q,--quiet}'[quiet]' \ + '(-n --dry-run)'{-n,--dry-run}'[do not make any changes]' \ + '(-r --runtime)'{-r,--runtime}'[activate changes at runtime, if possible]' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_grpcurl b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_grpcurl new file mode 100644 index 00000000..cd085458 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_grpcurl @@ -0,0 +1,78 @@ +#compdef grpcurl +# ------------------------------------------------------------------------------ +# Copyright (c) 2023 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for grpcurl v1.8.7. (https://github.com/fullstorydev/grpcurl) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_arguments \ + '*-H[Additional headers in "name:value" format]:header' \ + '-allow-unknown-fields[If "json" format is used, allows unknown fields to be present]' \ + '-authority[The authoritative name of the remote server]:authority' \ + '-cacert[File containing trusted root certificates for the server]: :_files' \ + '-cert[File containing client certificate(public key) to present to the server]: :_files' \ + '-connect-timeout[The maximum time, in seconds, to wait for connection to be established]:seconds' \ + '*-d[Data for request contents]:data' \ + '-emit-defaults[Emit default values for JSON-encoded responses]' \ + '-expand-headers[Headers may use "\${NAME}" syntax to reference environment variables]' \ + '-format[The format of request data]: :(json text)' \ + '-format-error[When a non-zero status is returned, format the response using the value set by the -format flag]' \ + '*-import-path[The path to a directory from which proto sources can be imported]: :_files -/' \ + '-insecure[Skip server certificate and domain verification]' \ + '-keepalive-time[The maximum idle time in seconds]:seconds' \ + '-key[File containing client private key, to present to the server]: :_files' \ + '-max-msg-sz[The maximum encoded size of a response message in bytes, that grpcurl will accept]:bytes' \ + '-max-time[The maximum total time the operation can take, in seconds]:seconds' \ + '-msg-template[When describing messages, show a template of input data]' \ + '-plaintext[Use plain-text HTTP/2 when connecting to server(no TLS)]' \ + '*-proto[The name of a proto source file]: :_files' \ + '*-protoset[The name of a file containing an encoded FileDescriptorSet]: :_files' \ + '-protoset-out[The name of a file to be written that will contain a FileDescriptorSet]: :_files' \ + '*-reflect-header[Additional reflection headers in "name:value" format]:header' \ + '*-rpc-header[Additional RPC headers in "name:value" format]' \ + '-servername[Override server name when validating TLS certificate]' \ + '-unix[Indicates that the server address is the path to a Unix domain socket]' \ + '-use-reflection[Server reflection will be used to determine the RPC schema]' \ + '-user-agent[The specified value will be added to the User-Agent header set by the grpc-go library]:user_agent' \ + '-v[Enable verbose output]' \ + '(- *)-version[Print version]' \ + '-vv[Enable very verbose output]' \ + '(- *)-h[Show help message]' \ + '*:: :_files' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_gtk-launch b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_gtk-launch new file mode 100644 index 00000000..82f71194 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_gtk-launch @@ -0,0 +1,84 @@ +#compdef gtk-launch gtk4-launch +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for gtk-launch on gtk+-3.24.37, gtk4-launch-4.10.4 +# (https://www.gtk.org/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * ncaq +# +# ------------------------------------------------------------------------------ + +_gtk-launch() { + local ret=1 + + if [[ $service == "gtk-launch" ]]; then + _arguments -S -A "-*" \ + '(- *)'{-h,--help}'[Show help options]' \ + '(- *)'{-v,--version}'[Show program version]' \ + '(- *)'--help-all'[Show all help options]' \ + '(- *)'--help-gtk'[Show GTK+ Options]' \ + '(- *)'--display='[X display to use]:display:_x_display' \ + '--class=[Program class as used by the window manager]:class' \ + '--name=[Program name as used by the window manager]:name' \ + '--gtk-module=[Load additional GTK+ modules]:module' \ + '--g-fatal-warnings[Make all warnings fatal]' \ + '1: :_gtk-launch-apps' \ + '*:: :_files' && ret=0 + else + # gtk4-launch + _arguments -S -A "-*" \ + '(- *)'{-h,--help}'[Show help options]' \ + '(- *)'{-v,--version}'[Show program version]' \ + '1: :_gtk-launch-apps' \ + '*:: :_files' && ret=0 + fi + + return ret +} + +(( $+functions[_gtk-launch-apps] )) || +_gtk-launch-apps() { + local -a apps=(/usr/share/applications/*.desktop(:r:t)) + _values 'applications' $apps +} + +_gtk-launch "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_hello b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_hello new file mode 100644 index 00000000..e8dafdf6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_hello @@ -0,0 +1,19 @@ +#compdef hello +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for GNU hello (https://www.gnu.org/software/hello/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Wu Zhenyu +# +# ------------------------------------------------------------------------------ + +_arguments -s '(- *)'{-h,--help}'[display this help and exit]' \ + '(- *)'{-v,--version}'[display version information and exit]' \ + {-t,--traditional}'[use traditional greeting]' \ + {-g,--greeting=}'[use TEXT as the greeting message]:TEXT' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_hledger b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_hledger new file mode 100644 index 00000000..c8d975e3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_hledger @@ -0,0 +1,286 @@ +#compdef hledger + +# ------------------------------------------------------------------------------ +# 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 +# +# https://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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for hledger 1.10 ( https://hledger.org/ ) +# Last updated: 07.08.2018 +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Valodim ( https://github.com/Valodim ) +# * fdw ( https://github.com/fdw ) +# +# ------------------------------------------------------------------------------ +# Notes +# ----- +# +# account completion depends on availability of a ~/.hledger.journal file +# +# ------------------------------------------------------------------------------ + + +local curcontext="$curcontext" curstate state line expl grp cmd ret=1 +typeset -a args +typeset -A opt_args + +args=( + '(- *)'{-h,--help}'[print help information]' + '(-f --file)'{-f,--file}'=[use a different input file]:input file:_files' + '--rules-file=[CSV conversion rules file]:rules file:_files' + '--alias=[display accounts named OLD as NEW]:alias specification' + '--anon=[anonymize accounts and payees]' + '(-b --begin)'{-b,--begin}'=[include postings/txns on or after this date]:date' + '(-e --end)'{-e,--end}'=[include postings/txns before this date]:date' + '(-D --daily)'{-D,--daily}'[multiperiod/multicolumn report by day]' + '(-W --weekly)'{-W,--weekly}'[multiperiod/multicolumn report by week]' + '(-M --monthly)'{-M,--monthly}'[multiperiod/multicolumn report by month]' + '(-Q --quarterly)'{-Q,--quarterly}'[multiperiod/multicolumn report by quarter]' + '(-Y --yearly)'{-Y,--yearly}'[multiperiod/multicolumn report by year]' + '(-p --period)'{-p,--period}'=[set start date, end date, and/or reporting interval all at once]' + '(-C --cleared)'{-C,--cleared}'[include only cleared postings/txns]' + '(-U --uncleared)'{-U,--uncleared}'[include only uncleared postings/txns]' + '(-R --real)'{-R,--real}'[include only non-virtual postings]' + '(--depth)--depth=[hide accounts/postings deeper than N]:depth' + '(-E --empty)'{-E,--empty}'[show empty/zero things which are normally omitted]' + '(-B --cost)'{-B,--cost}'[show amounts in their cost price'\''s commodity]' + '(-V --value)'{-V,--value}'[converts reported amounts to the current market value]' + '(-I --ignore-assertions)'{-I,--ignore-assertions}'[ignore any failing balance assertions]' + '--forecast=[apply periodic transaction rules to generate future transactions]' +) + +_arguments -C "$args[@]" -A "-*" \ + '(- *)--version[print version information]' \ + '--debug[show debug output]' \ + '1: :->cmds' \ + '*:: :->args' && ret=0 + +while (( $#state )); do + curstate=$state + shift state + case $curstate in + cmds) + typeset -a cmds + cmds=( + 'accounts:show account names (a)' + 'activity:show an ascii barchart of posting counts per interval' + 'add:prompt for transactions and add them to the journal' + 'balance:show accounts and balances (b, bal)' + 'balancesheet:show a balance sheet (bs)' + 'balancesheetequity:like balancesheet, but also reports equity' + 'cashflow:show a cashflow statement (cf)' + 'check-dates:check that transactions are sorted by increasing date' + 'check-dupes:report account names having the same leaf but different prefixes' + 'close:print closing/opening transactions that bring some or all account balances to zero and back' + 'help:show any of the hledger manuals' + 'import:read new transactions added to each file since last run, and add them to the main journal file' + 'incomestatement:show an income statement (is)' + 'prices:print market price directives from the journal' + 'print:show transaction entries (p, txns)' + 'print-unique:print transactions which do not reuse an already-seen description' + 'register:show postings and running total (r, reg)' + 'register-patch:print the one posting whose transaction description is closest to the description' + 'rewrite:print all transactions, adding custom postings to the matched ones' + 'stats:show some journal statistics' + 'tags:list all the tag names used in the journal' + 'test:run built-in unit tests' + ) + _describe 'subcommands' cmds && ret=0 + ;; + args) + : $words + local cmd=$words[1] + (( $+cmd )) || return 1 + # curcontext="${curcontext%:*:*}:$service-$cmd:" + case $cmd in + accounts) + args=( + '(--declared)--declared[show account names declared with account directives]' + '(--used)--used[show account names posted to by transactions]' + '(--tree)--tree[show accounts as a tree (default in simple reports)]' + '(--flat)--flat[show accounts as a list (default in multicolumn)]' + '(--drop)--drop=[flat mode, omit N leading account name parts]:drop n' + ) + ;; + activity) + ;; + add) + args=( + '(--no-new-accounts)--no-new-accounts=[do not allow creating new accounts]' + ) + ;; + bal|balance) + args+=( + '(--change)--change[show balance change in each period (default)]' + '(--cumulative)--cumulative[show balance change accumulated across periods]' + '(-H --historical)'{-H,--historical}'[show historical ending balance in each period]' + '(--tree)--tree[show accounts as a tree (default in simple reports)]' + '(--flat)--flat[show accounts as a list (default in multicolumn)]' + '(-A --average)'{-A,--average}'[show a row average column (in multicolumn mode)]' + '(-T --row-total)'{-T,--row-total}'[show a row total column]' + '(-N --no-total)'{-N,--no-total}'[do not show the final total row]' + '(--drop)--drop=[in flat mode, omit N leading account name parts]:drop n' + '(--no-elide)--no-elide[tree mode, do not squash boring parent accounts]' + '(--format)--format=[in tree mode, use this custom line format]:custom line format' + '(-O --output-format)'{-O,--output-format}='[select the output format from txt, csv, html]:format' + '(-o --output-file)'{-o,--output-file}'=[write output to file]:file' + '(--pretty-tables)--pretty-tables[use unicode to display prettier tables]' + '(--sort-amount)--sort-amount[sort by amount instead of account code/name]' + '(--invert)--invert[display all amounts with reversed sign]' + '(--budget)--budget[show performance compared to budget goals]' + '(--show-unbudgeted)--show-unbudgeted[with --budget, show unbudgeted accounts also]' + ) + ;; + bl|balancesheet|balancesheetequity) + args+=( + '(--change)--change[show balance change in each period (default)]' + '(--cumulative)--cumulative[show balance change accumulated across periods]' + '(-H --historical)'{-H,--historical}'[show historical ending balance in each period]' + '(--tree)--tree[show accounts as a tree (default in simple reports)]' + '(--flat)--flat[show accounts as a list (default in multicolumn)]' + '(-A --average)'{-A,--average}'[show a row average column (in multicolumn mode)]' + '(-T --row-total)'{-T,--row-total}'[show a row total column]' + '(-N --no-total)'{-N,--no-total}'[do not show the final total row]' + '(--drop)--drop=[in flat mode, omit N leading account name parts]:drop n' + '(--no-elide)--no-elide[tree mode, do not squash boring parent accounts]' + '(--format)--format=[in tree mode, use this custom line format]:custom line format' + '(--sort-amount)--sort-amount[sort by amount instead of account code/name]' + ) + ;; + cashflow|cf|balancesheet|bs|incomestatement|is) + args+=( + '(--change)--change[show balance change in each period (default)]' + '(--cumulative)--cumulative[show balance change accumulated across periods]' + '(-H --historical)'{-H,--historical}'[show historical ending balance in each period]' + '(--tree)--tree[show accounts as a tree (default in simple reports)]' + '(--flat)--flat[show accounts as a list (default in multicolumn)]' + '(-A --average)'{-A,--average}'[show a row average column (in multicolumn mode)]' + '(-T --row-total)'{-T,--row-total}'[show a row total column]' + '(-N --no-total)'{-N,--no-total}'[do not show the final total row]' + '(--drop)--drop=[in flat mode, omit N leading account name parts]:drop n' + '(--no-elide)--no-elide[tree mode, do not squash boring parent accounts]' + '(--format)--format=[in tree mode, use this custom line format]:custom line format' + '(--sort-amount)--sort-amount[sort by amount instead of account code/name]' + ) + ;; + import) + args=( + '(--dry-run)--dry-run[just show the transactions to be imported]' + ) + ;; + is|incomestatement) + args+=( + '(--change)--change[show balance change in each period (default)]' + '(--cumulative)--cumulative[show balance change accumulated across periods]' + '(-H --historical)'{-H,--historical}'[show historical ending balance in each period]' + '(--tree)--tree[show accounts as a tree (default in simple reports)]' + '(--flat)--flat[show accounts as a list (default in multicolumn)]' + '(-A --average)'{-A,--average}'[show a row average column (in multicolumn mode)]' + '(-T --row-total)'{-T,--row-total}'[show a row total column]' + '(-N --no-total)'{-N,--no-total}'[do not show the final total row]' + '(--drop)--drop=[in flat mode, omit N leading account name parts]:drop n' + '(--no-elide)--no-elide[tree mode, do not squash boring parent accounts]' + '(--format)--format=[in tree mode, use this custom line format]:custom line format' + '(--sort-amount)--sort-amount[sort by amount instead of account code/name]' + ) + ;; + print) + args=( + '(-m --match)'{-m,--match}'[show the transaction whose description is most similar]:string' + '(--new)--new[show only newer-dated transactions added in each file since last run]' + '(-x --explicit)'{-x,--explicit}'[show all amounts explicitly]' + '(-O --output-format)'{-O,--output-format}='[select the output format from txt, csv, html]:format' + '(-o --output-file)'{-o,--output-file}'=[write output to file]:file' + ) + ;; + register|reg) + args+=( + '(--cumulative)--cumulative[show balance change accumulated across periods]' + '(-H --historical)'{-H,--historical}'[show historical ending balance in each period]' + '(-A --average)'{-A,--average}'[show a row average column (in multicolumn mode)]' + '(-r --related)'{-r,--related}'[show postings'\'' siblings instead]' + '(-w --width)'{-w,--width}'=[set output width to 120, or N]:width (default 80)' + '(-O --output-format)'{-O,--output-format}='[select the output format from txt, csv, html]:format' + '(-o --output-file)'{-o,--output-file}'=[write output to file]:file' + ) + ;; + stats) + args=( + '(-o --output-file)'{-o,--output-file}'=[write output to file]:file' + ) + ;; + # fallback to _default + *) _arguments -C -A "-*" "$args[@]" \ + '*: :_default' && ret=0 + continue + esac + _arguments -C -A "-*" "$args[@]" \ + '*:query patterns:->query' && ret=0 + ;; + query) + + local -a accs keywords + keywords=( + 'acct\::match account names' + 'code\::match by transaction code' + 'desc\::match transaction descriptions' + 'tag\::match by tag name' + 'depth\::match at or above depth' + 'status\::match cleared/uncleared transactions' + 'real\::match real/virtual transactions' + 'empty\::match if amount is/is not zero' + 'amt\::match transaction amount' + 'cur\::match by currency' + ) + if compset -P 'amt:'; then + _message 'match amount (<, <=, >, >=, add sign for non-absolute match)' && ret=0 + continue + fi + if compset -P '(#b)(code|desc|tag|depth|status|real|empty):'; then + _message "'$match[1]' parameter" && ret=0 + continue + fi + + accs=( ${(f)"$(_call_program hledger hledger accounts $PREFIX 2>/dev/null)"} ) + if (( $? )); then + _message "error fetching accounts from hledger" + fi + + # decided against partial matching here. these lines can + # be uncommented to complete subaccounts hierarchically + # (add -S '' -q to the compadd below, too) + # if compset -P '(#b)(*):'; then + # accs=( ${(M)accs:#$match[1]:*} ) + # accs=( ${accs#$IPREFIX} ) + # fi + # accs=( ${accs%%:*} ) + + _wanted accounts expl "accounts" compadd -a accs && ret=0 + _describe "matcher keywords" keywords -S '' && ret=0 + + # not is special, it doesn't need the -S '' + keywords=( + 'not:negate expression' + ) + _describe "matcher keywords" keywords && ret=0 + + ;; + esac +done + +return ret diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_homestead b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_homestead new file mode 100644 index 00000000..22ab86b9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_homestead @@ -0,0 +1,53 @@ +#compdef homestead +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for homestead (http://laravel.com/docs/homestead). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * loranger (https://github.com/loranger) +# +# ------------------------------------------------------------------------------ + + +_homestead_get_command_list () { + homestead --no-ansi | sed "1,/Available commands/d" | awk '/ [a-z]+/ { print $1 }' +} + +_homestead () { + if [ -f homestead ]; then + compadd `_homestead_get_command_list` + fi +} + +compdef _homestead php homestead +compdef _homestead homestead diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_httpie b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_httpie new file mode 100644 index 00000000..2d4de8d9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_httpie @@ -0,0 +1,218 @@ +#compdef http https=http +# ------------------------------------------------------------------------------ +# Copyright (c) 2015 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for httpie 3.2.2 (https://httpie.io/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Akira Maeda +# * Valodim +# * Claus Klingberg +# * Shohei YOSHIDA +# +# ------------------------------------------------------------------------------ + +_httpie_params() { + local ret=1 expl + + # or a url + if (( CURRENT <= NORMARG+1 )) && [[ $words[NORMARG] != *:* ]] ; then + _httpie_urls && ret=0 + + # regular param, if we already have a url + elif (( CURRENT > NORMARG )); then + + # if the suffix is precisely : this is shorthand for a header + if [[ -prefix ':' ]]; then + PREFIX= + SUFFIX=: + fi + + # if we are in front of a : (possibly due to the PREFIX move before) + if [[ -suffix ':' ]]; then + # this is rather buggy with normal tab behavior : + compstate[insert]=menu + _wanted http_header expl 'HTTP Header' \ + compadd -s ':' -S '' -- Content-Type Cookie && return 0 + fi + + # ignore all prefix stuff + compset -P '(#b)([^:@=]#)' + local name=$match[1] + + if compset -P '='; then + _message "$name data field value" + elif compset -P '@'; then + _files + elif compset -P ':=@'; then + _files + elif compset -P ':='; then + _message "$name raw json data" + elif compset -P '=='; then + _message "$name url parameter value" + elif compset -P ':'; then + _message "$name header content" + else + typeset -a ops + ops=( + '=:data field' + '\::header' + '==:request parameter' + '@:data file field' + '\:=:raw json field' + '\:=@:raw json field file path' + ) + _describe -t httpparams "parameter types" ops -Q -S '' + fi + + ret=0 + + fi + + # first arg may be a request method + (( CURRENT == NORMARG )) && + _wanted http_method expl 'Request Method' \ + compadd GET POST PUT DELETE HEAD OPTIONS TRACE CONNECT PATCH LINK UNLINK && ret=0 + + return $ret +} + +_httpie_urls() { + local ret=1 + + if ! [[ -prefix [-+.a-z0-9]#:// ]]; then + local expl + compset -S '[^:/]*' && compstate[to_end]='' + _wanted url-schemas expl 'URL schema' compadd -S '' http:// https:// && ret=0 + else + _urls && ret=0 + fi + + return $ret + +} + +_httpie_printflags() { + local ret=1 + + # not sure why this is necessary, but it will complete "-pH" style without it + [[ $IPREFIX == "-p" ]] && IPREFIX+=" " + + compset -P '(#b)([a-zA-Z]#)' + + local -a flags + [[ $match[1] != *H* ]] && flags+=( "H:request headers" ) + [[ $match[1] != *B* ]] && flags+=( "B:request body" ) + [[ $match[1] != *h* ]] && flags+=( "h:response headers" ) + [[ $match[1] != *b* ]] && flags+=( "b:response body" ) + + _describe -t printflags "print flags" flags -S '' && ret=0 + + return $ret +} + +_httpie_styles() { + local -a styles=(abap algol algol_nu arduino auto autumn borland bw + colorful default dracula emacs friendly + friendly_grayscale fruity github-dark gruvbox-dark gruvbox-light + igor inkpot lilypond lovelace manni material monokai + murphy native nord nord-darker one-dark paraiso-dark paraiso-light + pastie perldoc pie pie-dark pie-light rainbow_dash + rrt sas solarized solarized-dark solarized-light stata + stata-dark stata-light tango trac vim vs xcode zenburn) + + _describe -t styles 'style' styles +} + +integer NORMARG + +_arguments -n -C -s \ + '(-j --json -f)'{-j,--json}'[Data items from the command line are serialized as a JSON object]' \ + '(-f --form -j)'{-f,--form}'[Data items from the command line are serialized as form fields]' \ + '--multipart[Similar to --form, but always sends a multipart/form-data request]' \ + '--boundary=[Specify a custom boundary string for multipart/form-data requests]' \ + '--raw=[This option allows you to pass raw request data without extra processing]' \ + '(-x --compress)'{-x,--compress}'[Content compressed with Deflate algorithm]' \ + '--pretty=[Controls output processing]:output format:(all colors format none)' \ + '(-s --style)'{-s,--style}'=[Output coloring style]:STYLE:_httpie_styles' \ + '--unsorted[Disables all sorting while formatting output]' \ + '--sorted[Re-enables all sorting options while formatting output]' \ + '--response-charset=[Override the response encoding for terminal display purposes]:encoding' \ + '--response-mime=[Override the response mime type for coloring and formatting for the terminal]:mine' \ + '--format-options=[Controls output formatting]:format' \ + '(-p --print)'{-p,--print}'=[String specifying what the output should contain]:print flags:_httpie_printflags' \ + '(-v --verbose)'{-v,--verbose}'[Print the whole request as well as the response]' \ + '(-p -h --headers)'{-h,--headers}'[Print only the response headers]' \ + '(-p -m --meta)'{-m,--meta}'[Print only the response metadata]' \ + '(-p -b --body)'{-b,--body}'[Print only the response body]' \ + '--all[By default, only the final request/response is shown]' \ + '(-S --stream)'{-S,--stream}'[Always stream the output by line, i.e., behave like `tail -f`]' \ + '(-o --output)'{-o,--output}'=[Save output to FILE]:output file:_files' \ + '(-d --download)'{-d,--download}'=[Do not print the response body to stdout]' \ + '(-c --continue)'{-c,--continue}'[Resume an interrupted download]' \ + '(-q --quiet)'{-q,--quiet}'[Do not print to stdout or stderr, except for errors and warnings when provided once]' \ + '(--session-read-only)--session=[Create, or reuse and update a session]:session name (or path)' \ + '(--session)--session-read-only=[Create or read a session without updating it form the request/response exchange]:session name (or path)' \ + '(-a --auth)'{-a,--auth}'=[If only the username is provided (-a username)]:USER\:PASS' \ + '--auth-type=[The authentication mechanism to be used. Defaults to "basic"]:AUTH-TYPE:(basic digest bearer)' \ + '--ignore-netrc[Ignore credentials from .netrc]' \ + '--offline[Build the request and print it but do not actually send it]' \ + '--proxy=[String mapping protocol to the URL of the proxy]:PROXY' \ + '(-F --follow)'{-F,--follow}'[Allow full redirects]' \ + '--max-redirects=[A limit of redirects]:number:' \ + '--max-headers=[The maximum number of response headers to be read]:number:' \ + "--verify=[Enable or disable verification of ssl certificates]:verify certificate:(yes no)" \ + '--ssl=[The desired protocol version to use]:ssl version:(ssl2.3 tls1 tls1.1 tls1.2)' \ + '--ciphers=[A string in the OpenSSL cipher list format]:ciphers' \ + '--cert=[Specify a local cert to use as client side SSL certificate]:cert:_files' \ + '--cert-key=[Specify the private to key to use with SSL]:cert key:_files' \ + '--cert-key-pass=[The passphrase to be used to with the given private key]' \ + '--timeout=[Float describes the timeout of the request (Use socket.setdefaulttimeout() as fallback)]:timeout (seconds)' \ + '--check-status[This flag instructs HTTPie to also check the HTTP status code and exit with an error if the status indicates one]' \ + '--path-as-is[Bypass dot segment URL squashing]' \ + '--chunked[Enable streaming via chunked transfer encoding]' \ + '(-I --ignore-stdin)'{-I,--ignore-stdin}'[Do not attempt to read stdin]' \ + '(- *)--help[show help message]' \ + '(- *)--manual[show the full manual]' \ + "(- *)--version[show program's version number and exit]" \ + '--traceback[Prints exception traceback should one occur]' \ + '--default-scheme=[The default scheme to use if not specified in the URL]:scheme:' \ + '--debug[Prints exception traceback should one occur and other information useful for debugging HTTPie itself]' \ + '*:args:_httpie_params' && return 0 + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ibus b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ibus new file mode 100644 index 00000000..28ae67ea --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ibus @@ -0,0 +1,109 @@ +#compdef ibus +# ------------------------------------------------------------------------------ +# Copyright (c) 2017 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for ibus 1.5.27 (https://github.com/ibus/ibus). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Tomo Kazahaya +# +# ------------------------------------------------------------------------------ + +# The completion of "ibus emoji --lang=" depends on _language_codes from +# https://github.com/zsh-users/zsh-completions. + +local context state state_descr line +typeset -A opt_args +local curcontext=$curcontext + +_arguments -C \ + ":command:(($(ibus help|sed -ne 's/^ \(\S\+\) \+\(.*\)/"\1\\:\2"/p')))" \ + '*:: :->args' \ + && return + +case $state in + args) + case $line[1] in + (engine) + _arguments \ + ":engine:(($(ibus list-engine|sed -ne 's/:/\\\\:/g' -e 's/^ \(\S\+\) - \(.*\)$/"\1:\2"/p')))" \ + && return + ;; + (start|restart) + _arguments \ + '--type=[start or restart daemon type with direct or systemd type]: :(direct systemd)' \ + '--file=[start or restart daemon with SYSTEMD_SERVICE file]: :_files' \ + '--verbose[Show debug message]' \ + '(- *)--help[Show help message]' \ + && return + ;; + (read-cache) + _arguments \ + '--system[show the content of the system registry cache]' \ + '--file=[custom registry cache to show]:registry cache:_files' \ + '(- *)--help[Show help message]' \ + && return + ;; + (write-cache) + _arguments \ + '--system[save the system registry cache]' \ + '--file=[custom registry cache to save]:registry cache:_files' \ + '(- *)--help[Show help message]' \ + && return + ;; + (emoji) + _arguments \ + '--font=[emoji font]:emoji font: ' \ + '--lang=[language of emoji annotations]:language:_language_codes ISO-639-1' \ + '--partial-match[match annotations with a partial string]' \ + '(- *)--help[Show help message]' \ + && return + ;; + (im-module) + _arguments \ + '--type=[Set im-module TYPE]: :(gtk2 gtk3 gtk4)' \ + '(- *)--help[Show help message]' \ + && return + ;; + esac + ;; +esac + +return 1 + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_include-what-you-use b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_include-what-you-use new file mode 100644 index 00000000..0962e922 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_include-what-you-use @@ -0,0 +1,87 @@ +#compdef include-what-you-use iwyu + +# Copyright 2018 CERN for the benefit of the LHCb Collaboration. +# All rights reserved. +# +# Developed by: +# +# CERN LBC group +# +# CERN +# +# https://home.web.cern.ch/ +# +# Permission is hereby granted, free of charge, to any person obtaining a copy +# of this software and associated documentation files (the "Software"), to deal +# with 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: +# +# * Redistributions of source code must retain the above copyright notice, +# this list of conditions and the following disclaimers. +# +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimers in the +# documentation and/or other materials provided with the distribution. +# +# * Neither the names of the LBC group, CERN, nor the names of its +# contributors may be used to endorse or promote products derived from +# this Software without specific prior written permission. +# +# 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 +# CONTRIBUTORS 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 WITH +# THE SOFTWARE. +# +# In applying this licence, CERN does not waive the privileges and immunities +# granted to it by virtue of its status as an Intergovernmental Organization or +# submit itself to any jurisdiction. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for include-what-you-use 0.19 (https://github.com/include-what-you-use/include-what-you-use). +# +# ------------------------------------------------------------------------------ + +# TODO: +# - prevent _iwyu_opts from running once the first clang option got passed + +_iwyu_opts() { + _arguments \ + '--check_also=[print iwyu-violation info for files matching the given glob pattern]:glob pattern:' \ + '--keep=[tells iwyu to always keep these includes]:glob pattern' \ + '*'"--mapping_file=[iwyu mapping file]:iwyu mapping file:_path_files -g '*(/) *.imp'" \ + "--no_default_mappings[do not add iwyu's default mappings]" \ + '--pch_in_code[mark the first include in a translation unit as a precompiled header]' \ + '--prefix_header_includes=[what to do with command line includes]:command line include treatment:(add keep remove)' \ + "--transitive_includes_only[do not suggest that a file add headers that aren't already visible]" \ + '--max_line_length=[maximum line length for includes]:a number:' \ + '--comment_style=[set verbosity of "why" comments to]:comment style:(none short long)' \ + '--no_comments[do not add "why" comments]' \ + '--no_fwd_decls[do not use forward declarations]' \ + '--verbose=[the higher the level, the more output]:a number:' \ + '--quoted_includes_first[when sorting includes, place quoted ones first]' \ + '--cxx17ns[suggests the more concise syntax introduced in C++17]' \ + '--error=-[exit with N(default: 1) for iwyu violations]::exit code' \ + '--error_always=-[always exit with N (default: 1)]::exit code' \ + '--debug=[debug flags]:flag' \ + '--regex=[use specified regex dialect in iwyu]:dialect:(llvm ecmascript)' \ + '*: :_files' +} + +_alternative \ + 'iwyu:iwyu_option:_iwyu_opts' \ + 'gcc:gcc_option:_gcc' \ + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_inxi b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_inxi new file mode 100644 index 00000000..89975044 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_inxi @@ -0,0 +1,199 @@ +#compdef inxi +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script of inxi 3.3.21-00 (https://smxi.org/docs/inxi.htm) +# +# a full featured CLI system information tool +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Oleksii Filonenko +# +# ------------------------------------------------------------------------------ + +_inxi() { + typeset -A opt_args + local context state line + local curcontext="$curcontext" + local ret=1 + + local colors=($(seq 0 42)) + + _arguments -C -s \ + '(-A --audio)'{-A,--audio}"[Show Audio/sound card(s) information]" \ + '(-b --basic)'{-b,--basic}"[Show basic output, short form]" \ + '(-B --battery)'{-B,--battery}"[Show system Battery information]" \ + '(-C --cpu)'{-C,--cpu}"[Show full CPU output]" \ + '(-d --disk-full --optical)'{-d,--disk-full,--optical}"[Show hard + optical drive info]" \ + '(-D --disk)'{-D,--disk}"[Show hard Disk info]" \ + '(-E --bluetooth)'{-E,--bluetooth}'[Show bluetooth device data report, if available]' \ + '--edid[Full graphics data, triggers -a -G]' \ + '(-f --flags)'{-f,--flags}"[Show all CPU flags used]" \ + '(-F --full)'{-F,--full}"[Show Full output]" \ + '(-G --graphics)'{-G,--graphics}"[Show Graphic card(s) information]" \ + '(- *)'{-h,--help}"[Show list of command-line options]" \ + '(-i --ip)'{-i,--ip}"[Show WAN IP address and local interfaces]" \ + '(-I --info)'{-I,--info}"[Show Information: processes, uptime, etc.]" \ + '(-j --swap)'{-j,--swap}'[Swap in use]' \ + '(-J --usb)'{-J,--usb}"[Show USB data for attached Hubs and Devices]" \ + '(-l --label)'{-l,--label}"[Show partition labels]" \ + '(-L --logical)'{-L,--logical}'[Logical devices]' \ + '(-m --memory)'{-m,--memory}"[Memory (RAM) data]" \ + '(--memory-modules --mm)'{--memory-modules,--mm}'[Memory (RAM) data. Exclude empty module slots]' \ + '(--memory-short --ms)'{--memory-short,--ms}'[Memory (RAM) data. Show only short Memory RAM report]' \ + '(-M --machine)'{-M,--machine}"[Show Machine data]" \ + '(-n --network-advanced)'{-n,--network-advanced}"[Show Advanced Network card information]" \ + '(-N --network)'{-N,--network}"[Show Network card(s) information]" \ + '(-o --unmounted)'{-o,--unmounted}"[Show unmounted partition information]" \ + '(-p --partitions-full)'{-p,--partitions-full}"[Show full Partition information]" \ + '(-P --partitions)'{-P,--partitions}"[Show basic Partition information]" \ + '(-r --repos)'{-r,--repos}"[Show distro repository data]" \ + '(-R --raid)'{-R,--raid}"[Show RAID data]" \ + "(- *)"--recommends"[Check inxi dependencies + recommends]" \ + '(-s --sensors)'{-s,--sensors}"[Show output from configured sensors]" \ + "--slots[Show PCI slots]" \ + '(-S --system)'{-S,--system}"[Show System information]" \ + '(-t --processes)'{-t+,--processes=}"[Show processes]:processes:((c\:'CPU only' m\:'Memory only' cm\:'CPU+memory'))" \ + '(-u --uuid)'{-u,--uuid}"[Show partition UUIDs]" \ + "(- *)"{-U,--update}"[Auto-update inxi]" \ + "(- *)"{-V,--version}"[Show version of inxi]" \ + '(-v --verbosity)'{-v+,--verbosity=}"[Script verbosity levels]:verbosity:_inxi_verbosity" \ + '(-w --weather)'{-w,--weather}"[Adds weather line]" \ + '(-W --weather-location)'{-W+,--weather-location=}"[Get weather/time for an alternate location]:weather location: " \ + "--weather-source=[Change weather data source]: :(1 2 3 4 5 6 7 8 9)" \ + "--weather-unit=[Set weather unit]:weather unit:((m\:metric i\:imperial mi\:'metric (imperial)' im\:'imperial (metric)'))" \ + "--host[Turns on hostname in System line]" \ + "--no-host[Turns off hostname in System line]" \ + {-z,--filter}"[Adds security filters]" \ + '(--za --filter-all)'{--za,--filter-all}'[Shortcut triggers, -z, --zl, --zu, --zv]' \ + '(--zl --filter-label)'{--zl,--filter-label}'[Filter out partition labels in -j, -o, -p, -P, -Sa]' \ + '(--zu --filter-uuid)'{--zu,--filter-uuid}'[Filter out partition UUIDs in -j, -o, -p, -P, -Sa]' \ + '(--zv --filter-vulnerabilities)'{--zv,--filter-vulnerabilities}'[Filters out Vulnerabilities report in -Ca]' \ + '(-Z --no-filter)'{-Z,--no-filter}"[Disable output filters]" \ + '(-c --color)'{-c+,--color=}"[Set color scheme]:color:(${colors[*]})" \ + "--indent=[Change default wide mode primary indentation width]:integer:(11 12 13 14 15 16 17 18 19 20)" \ + "--indents=[Change wrapped mode primary indentation width]:integer:(0 1 2 3 4 5 6 7 8 9 10)" \ + "--limit[Limit max IP addresses for -i]:limit (-1 removes the limit): " \ + '(--max-wrap --wrap-max)'{--max-wrap,--warp-max}='[Set maximum width where inxi autowraps line starters]' \ + "--output[Change data output type]:type:(json screen xml)" \ + "--output-file[Path to output file]:output file:->output_file" \ + "--partition-sort[Change default sort order of partition output]:order:_inxi_partition_sort" \ + '(-y --width)'{-y+,--width=}"[Set width override]:columns (80 minimum): " \ + '(-Y --height)'{-Y+,--height=}"[Output height control]:" \ + \*{-x,--extra}"[Extra data options]" \ + '(-a --admin)'{-a,--admin}"[Admin extra data options]:admin option:->admin" \ + "--alt[Bypass a downloader option]:downloader:_inxi_alt" \ + '--bt-tool[Force use of given tool for bluetooth report]' \ + '(--no-dig --dig)--dig[Overrides configuration item NO_DIG]' \ + "--display[Get display data out of X]:\:: " \ + "--dmidecode[Force use of dmidecode]" \ + "--downloader[Force inxi to use a specific downloader]:downloader:(curl fetch perl wget)" \ + '--force[Force use items]:' \ + '--hddtemp[Force use of hddtemp for disk temps]' \ + '(--no-html-wan --html-wan)--html-wan[Overrides configuration item NO_HTML_WAN]' \ + '(--dig --no-dig)--no-dig[Skip dig for WAN IP checks]' \ + '--no-doas[Skip internal program use of doas features]' \ + '(--no-html-wan --html-wan)--no-html-wan[Skip HTML IP sources for WAN IP checks]' \ + "--no-ssl[Skip SSL certificate checks]" \ + "--no-sudo[Skip internal program use of sudo features]" \ + '--rpm[Force use of disabled package manager counts for packages feature with -rx/-Ix ]' \ + '--sensors-default[Removes configuration item SENSORS_USE and SENSORS_EXCLUDE]' \ + '--sensors-exclude[Exclude supplied sensor array for -s output]' \ + '--sensors-use[Use only supplied sensor array for -s output]' \ + "--sleep[Change CPU sleep time]:sleep time (usually in decimals): " \ + "--tty[Forces internal IRC flag to off]" \ + "--usb-sys[Forces the USB data generator to use /sys as data source]" \ + "--usb-tool[Forces the USB data generator to use lsusb as data source]" \ + "--wan-ip-url[Force -i to use supplied URL as WAN ip source]:URL: " \ + "--wm[Force System item wm to use wmctrl as data source]" \ + "--dbg[Debug downloader failures]:level:(1)" \ + "--debug[On screen debugger output]:level:(1 2 3 10 11 20 21 22)" \ + "--debug-proc[Force debugger to parse /proc directory data when run as root]" \ + "--debug-proc-print[Use this to locate file that /proc debugger hangs on]" \ + "--debug-no-exit[Skip exit on error when running debugger]" \ + "--debug-no-proc[Skip /proc debugging in case of a hang]" \ + "--debug-no-sys[Skip /sys debugging in case of a hang]" \ + "--debug-sys[Force PowerPC debugger parsing of /sys as sudo/root]" \ + "--debug-proc[Force debugger to parse /proc directory data when run as root]" \ + "--debug-sys-print[Use this to locate file that /sys debugger hangs on]" \ + "--ftp[Set alternate ftp upload location]:FTP URL: " \ + && ret=0 + + case "$state" in + (admin) + _arguments -s \ + '-C[Adds CPU family, model-id, and stepping]' \ + '-d[Adds logical and physical block size in bytes]' \ + {-p,-P}'[Adds raw partition / filesystem block size]' \ + && ret=0 + ;; + + (output_file) + _alternative \ + "outputs:output file:((print\:'Print to stdout'))" \ + "outputs:output file:_files" + ;; + esac + + return ret +} + +(( $+functions[_inxi_partition_sort] )) || +_inxi_partition_sort() { + local -a orders=( + 'dev-base:/dev partition identifier' + 'fs:partition filesystem' + 'id:mount point of partition (default)' + 'label:label of partition' + 'percent-used:percentage of partition size used' + 'size:KiB size of partition' + 'uuid:UUID of the partition' + 'used:KiB used of partition' + ) + + _describe 'sort order' orders +} + +(( $+functions[_inxi_alt] )) || +_inxi_alt() { + local -a downloaders=( + '40:Perl' + '41:Curl' + '42:Fetch' + '43:Wget' + '44:Curl, Fetch, and Wget' + ) + + _describe 'downloader' downloaders +} + +(( $+functions[_inxi_verbosity] )) || +_inxi_verbosity() { + local -a levels=( + '0:Short output, same as: inxi' + '1:Basic verbose, -S + basic CPU' + '2:Adds -N, -M, -B, same as: inxi -b' + '3:Adds -C, -n, -x' + '4:Adds -P, -D' + '5:Adds -A, -m, -s, -l, -u' + '6:Adds -p, -o, -d, --usb, -xx' + '7:Adds -i, -xxx' + '8:Adds -r, --slots, -tcm, --admin' + ) + + _describe 'script verbosity level' levels +} + +_inxi "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_jmeter b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_jmeter new file mode 100644 index 00000000..4d7b01df --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_jmeter @@ -0,0 +1,58 @@ +#compdef jmeter +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for JMeter (https://jmeter.apache.org/). +# +# Status: incomplete +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# +# ------------------------------------------------------------------------------ + + +_arguments \ + '(- 1 *)--?[print command line options and exit]' \ + '(- 1 *)'{-h,--help}'[print usage information and exit]' \ + '(- 1 *)'{-v,--version}'[print the version information and exit]' \ + {-p,--propfile}'[the jmeter property file to use]:properties file:_files -g "*.properties"' \ + '*'{-q,--addprop}'[additional property file(s)]:properties file:_files -g "*.properties"' \ + {-t,--testfile}'[the jmeter test plan file to run]:JMeter test plan file:_files -g "*.jmx"' \ + {-j,--jmeterlogfile}'[the jmeter log file]: :_files -g "*.log"' \ + {-l,--logfile}'[the file to log samples to]: :_files -g "*.jtl"' \ + {-i,--jmeterlogconf}'[jmeter logging configuration file]: :_files -g "*.xml"' \ + {-j,--jmeterlogfile}'[jmeter run file]: :_files -g "*.log"' \ + {-n,--nongui}'[run JMeter in nongui mode]' \ + {-s,--server}'[run the JMeter server]' \ + {-E,--proxyScheme}'[set a proxy scheme to use for the proxy server]:scheme' \ + {-H,--proxyHost}'[set a proxy server for JMeter to use]: :_hosts' \ + {-P,--proxyPort}'[set proxy server port for JMeter to use]:number' \ + {-N,--nonProxyHosts}'[set non proxy host list]:host' \ + {-u,--username}'[set username for proxy server that JMeter is to use]:username:_users' \ + {-a,--password}'[set password for proxy server that JMeter is to use]:password' \ + {-J-,--jmeterproperty}'[define additional JMeter properties]:argument=value' \ + {-G-,--globalproperty}'[define Global properties (sent to servers)]:argument=value' \ + {-D-,--systemproperty}'[define additional System properties]:argument=value' \ + {-S,--systemPropertyFile}'[a property file to be added as System properties]:properties file:_files -g "*.properties"' \ + {-f,--forceDeleteResultFile}'[force delete existing results files and web report folder]' \ + {-L,--loglevel}'[define loglevel]:[category=]level' \ + {-r,--runremote}'[start remote servers (as defined by the jmeter property remote_hosts)]' \ + {-R,--remotestart}'[start these remote servers (overrides remote_hosts)]:remote servers list' \ + {-d,--homedir}'[the JMeter home directory to use]: :_files -/' \ + {-X,--remoteexit}'[exit the remote servers at end of test (non-GUI)]' \ + {-g,--removeonly}'[generate report dashboard only, from a test results file]: :_files' \ + {-e,--reportatendofloadtests}'[generate report dashboard after load test]' \ + {-o,--reportoutputfolder}'[output folder for report dashboard]: :_files -/' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_jmeter-plugins b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_jmeter-plugins new file mode 100644 index 00000000..37609b5a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_jmeter-plugins @@ -0,0 +1,42 @@ +#compdef jmeter-plugins +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for jmeter-plugins command line tool 0.4.2 +# (https://jmeter-plugins.org/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# +# ------------------------------------------------------------------------------ + + +_arguments \ + '(- 1 *)--help[show help options]' \ + '--generate-png[generate PNG file containing graph]:PNG file name:_files -g "*.png"' \ + '--generate-csv[generate CSV file containing graph data]:CSV file name:_files -g "*.csv"' \ + '--input-jtl[load data from specified JTL file]:JTL file:_files -g "*.jtl"' \ + '--plugin-type[type of graph to use for results generation]:class:((AggregateReport ThreadsStateOverTime BytesThroughputOverTime HitsPerSecond LatenciesOverTime PerfMon ResponseCodesPerSecond ResponseTimesDistribution ResponseTimesOverTime ResponseTimesPercentiles ThroughputOverTime ThroughputVsThreads TimesVsThreads TransactionsPerSecond))' \ + '--width[set graph width]:graph width (pixels)' \ + '--height[set graph height]::graph height (pixels)' \ + '--granulation[granulation time for samples]:time (ms)' \ + '--relative-times[use relative X axis times, no will set absolute times]: :((yes no))' \ + '--aggregate-rows[aggregate all rows into one]: :((yes no))' \ + '--paint-gradient[paint gradient background]: :((yes no))' \ + '--paint-zeroing[paint zeroing lines]: :((yes no))' \ + '--prevent-outliers[prevent outliers on distribution graph]: :((yes no))' \ + '--limit-rows[limit number of points in row]:number of points' \ + '--force-y[force Y axis limit]:limit' \ + '--hide-low-counts[hide points with sample count below limit]:limit' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_jonas b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_jonas new file mode 100644 index 00000000..1d93475f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_jonas @@ -0,0 +1,100 @@ +#compdef jonas +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for JOnAS 5.2 (https://jonas.ow2.org/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# +# ------------------------------------------------------------------------------ + + +typeset -A opt_args +local context state line curcontext="$curcontext" ret=1 + +_arguments -C \ + '1:cmd:->cmds' \ + '*::arg:->args' \ +&& ret=0 + +case "$state" in + (cmds) + local commands; commands=( + 'version:show version information' + 'check:check that the JOnAS environment is correctly set' + 'start:start a server instance' + 'stop:stop a server instance' + 'admin:administrate a server instance' + ) + _describe -t commands 'command' commands && ret=0 + ;; + (args) + curcontext="${curcontext%:*:*}:jonas-cmd-$words[1]:" + case $words[1] in + (version|check) + _message 'no more arguments' && ret=0 + ;; + (start) + _arguments \ + '-standby[start a minimal JOnAS server with only mandatory services]' \ + '(-bg)-fg[start the server in foreground mode]' \ + '(-fg)-bg[start the server in background mode]' \ + '-win[start the server in a new window]' \ + '(-bg)-tui[start the Apache Felix TUI (force foreground mode)]' \ + '-gui[start the Apache Felix GUI]' \ + '-dev[start a JOnAS server by using bundles present in the default maven repository instead of bundles under $JONAS_ROOT/lib/bundles]' \ + '-clean[clean the Apache Felix cache before starting a JOnAS server]' \ + '-n[set the server name, must be unique in the domain (default: jonas)]:name' \ + '-target[start another server or cluster (group of servers) in the domain]:server' \ + '-Ddomain.name=[set the name of the management domain to which the server belongs]:domain' \ + && ret=0 + ;; + (stop) + _arguments \ + '-standby[stop all services except the mandatory ones]' \ + '-n[set the name of the server to stop (default: jonas)]:name' \ + '-target[stop another server or cluster (group of servers) in the domain]:server' \ + '-Ddomain.name=[set the name of the management domain to which the server belongs]:domain' \ + && ret=0 + ;; + (admin) + _arguments \ + '(- : *)-?[print the help message]' \ + '-win[administer the server in a new window]' \ + '-n[set the name of the server to administer (default: jonas)]:name' \ + '-username[set the username when authentication is required]: :_users' \ + '-password[set the password when authentication is required]:password' \ + '-registry[set the registry URL]: :_urls' \ + '-protocol[set the protocol name]:protocol:((jrmp\:JRE\ implementation\ of\ RMI\ on\ the\ JRMP\ protocol\ \(default\) iiop\:JacORB\ implementation\ of\ RMI\ over\ the\ IIOP\ protocol irmi\:Oracle\ JRE\ independent\ implementation\ of\ RMI))' \ + '-a[deploy an application from a given filepath on the current server, or on another target in the domain if the current server is a master]:Java application archive:_files -g "*.(j|w|r|e)ar"' \ + '-r[undeploy a previously deployed application from the current server or from the specified target if the current server is a master]:Java application archive:_files -g "*.(j|w|r|e)ar"' \ + '-gc[run the garbage collector on the current JOnAS server]' \ + '-passivate[passivate all entity bean instances]' \ + '-e[list the properties of the current JOnAS server]' \ + '-j[list the registered JNDI names, as seen by the current JOnAS server]' \ + '-l[list the beans currently loaded by the current JOnAS server]' \ + '-synch[synchronize the entity bean instances on the current JOnAS server]' \ + '-debug[set the logging level for the given topic to DEBUG]:topic' \ + '-tt[change the default timeout for transactions]:timeout (seconds)' \ + '-ping[wait until the JOnAS server is available]' \ + '-timeout[maximum time to wait when -ping is used]:timeout (seconds)' \ + && ret=0 + ;; + esac + ;; +esac + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_jrnl b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_jrnl new file mode 100644 index 00000000..9979d375 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_jrnl @@ -0,0 +1,66 @@ +#compdef jrnl +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for jrnl a simple journal application for your command line. (https://maebert.github.io/jrnl/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Jindřich Pilař (https://github.com/JindrichPilar) +# +# ------------------------------------------------------------------------------ + + +_jrnl() { + + _arguments -C \ + '(- 1 *)'-h"[Show help and exit]" \ + '(- 1 *)'-v"[Prints version information and exits]" \ + '(- 1 *)'-ls"[Displays accessible journals]" \ + '(- 1 *)'-d"[Execute in debug mode]" \ + '(- 1 *)'--tags"[Returns a list of all tags and number of occurrences]" \ + "--short[Show only titles or line containing the search]" \ + "-from[View entries after this date]:date:" \ + "-until[View entries before this date]:date:" \ + "-to[View entries before this date]:date:" \ + "-on[View entries on this date]:date:" \ + "-and[Filter by tags using AND (default: OR)]" \ + "-starred[Show only starred entries]" \ + "-n[Shows the last n entries matching the filter. And '-3' have the same effect.]":number: \ + "--export[Export your journal. TYPE can be json, markdown text.]:format:(json markdown text)" \ + "-o[Optionally specifies output file when using --export If OUTPUT is a directory, exports each entry in individual file instead.]:output file:" \ + "--encrypt[Encrypts your existing journal with a new pass]" \ + "--decrypt[Decrypts your journal and stores it in plain text]" \ + "--edit[Opens your editor to edit the selected entries.]" \ +} + +_jrnl + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_kak b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_kak new file mode 100644 index 00000000..19faeee9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_kak @@ -0,0 +1,78 @@ +#compdef kak +# ------------------------------------------------------------------------------ +# Copyright (c) 2017 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for kak 2022.10.31 (https://github.com/mawww/kakoune) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Frank LENORMAND +# +# ------------------------------------------------------------------------------ + +_kak_sessions() { + local -a session_ids expl + session_ids=($(_call_program session_names kak -l)) + _description session-ids expl "session name" + compadd "$expl[@]" -a session_ids +} + +_kak() { + _arguments \ + '-c[connect to given session]:session_id:_kak_sessions' \ + '-e[execute argument on client initialization phase]:keys' \ + '-E[execute argument on server initialization]:keys' \ + "-n[do not load the system's kakrc]" \ + '-s[set the current session name]:session_id' \ + '-d[run as a headless session (requires -s)]' \ + '-p[just send stdin as commands to the given session]:session_id:_kak_sessions' \ + "-f[enter in 'filter mode':select the whole file, then execute keys]:keys" \ + '-i[backup the files on which a filter is applied using the given suffix]:suffix' \ + '-q[in filter mode, do not print any errors]' \ + '-ui[set the type of user interface to use (ncurses, dummy, or json)]:ui_type:(ncurses dummy json)' \ + '-l[list existing sessions]:session_id:_kak_sessions' \ + '-clear[clear dead sessions]' \ + '-debug[initial debug option value]:arg' \ + '(- *)-version[display Kakoune version and quit]' \ + '-ro[readonly mode]' \ + '(- *)-help[display a help message and quit]' \ + '*::files:_files' +} + +_kak "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_kitchen b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_kitchen new file mode 100644 index 00000000..0d939179 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_kitchen @@ -0,0 +1,86 @@ +#compdef kitchen +# ------------------------------------------------------------------------------ +# Copyright (c) 2014 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Test Kitchen (https://kitchen.ci/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Peter Eisentraut (https://github.com/petere) +# * Shohei YOSHIDA (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + + +_kitchen() { + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments '1: :->cmds'\ + '2: :->args' + + case $state in + cmds) + _kitchen_commands + ;; + args) + case $line[1] in + converge|create|destroy|diagnose|list|setup|test|verify) + compadd 'all' + _kitchen_instances + ;; + login) + _kitchen_instances + ;; + esac + ;; + esac +} + +_kitchen_commands() { + local commands + + commands=("${(@f)$(_call_program commands $service help | sed -n 's/^ kitchen \([[:alpha:]]*\) .*# \(.*\)$/\1:\2/p')}") + _describe -t commands 'kitchen commands' commands +} + +_kitchen_instances() { + if [[ $_kitchen_instances_cache_dir != $PWD ]]; then + unset _kitchen_instances_cache + fi + if [[ ${+_kitchen_instances_cache} -eq 0 ]]; then + _kitchen_instances_cache=(${(f)"$(_call_program instances $service list -b 2>/dev/null)"}) + _kitchen_instances_cache_dir=$PWD + fi + _wanted instances expl 'instance' compadd -a _kitchen_instances_cache +} + +_kitchen "$@" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_knife b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_knife new file mode 100644 index 00000000..959668ea --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_knife @@ -0,0 +1,324 @@ +#compdef knife +# ------------------------------------------------------------------------------ +# Copyright (c) 2009-2015 Robby Russell and contributors (see +# https://github.com/ohmyzsh/ohmyzsh/graphs/contributors) +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Chef's knife (https://www.chef.io/). +# +# Source: https://github.com/ohmyzsh/ohmyzsh/blob/22fed4f/plugins/knife/_knife +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Frank Louwers (https://github.com/franklouwers) +# * Mark Cornick (https://github.com/markcornick) +# +# ------------------------------------------------------------------------------ + + +# You can override the path to knife.rb and your cookbooks by setting +# KNIFE_CONF_PATH=/path/to/my/.chef/knife.rb +# KNIFE_COOKBOOK_PATH=/path/to/my/chef/cookbooks +# If you want your local cookbooks path to be calculated relative to where you are then +# set the below option +# KNIFE_RELATIVE_PATH=true +# Read around where these are used for more detail. + +# knife has a very special syntax, some example calls are: +# knife status +# knife cookbook list +# knife role show ROLENAME +# knife data bag show DATABAGNAME +# knife role show ROLENAME --attribute ATTRIBUTENAME +# knife cookbook show COOKBOOKNAME COOKBOOKVERSION recipes + +# The -Q switch in compadd allow for completions of things like "data bag" without having to go through two rounds of completion and avoids zsh inserting a \ for escaping spaces +_knife() { + # These flags should be available everywhere according to man knife + local -a knife_general_flags; knife_general_flags=(--help --server-url --key --config --editor --format --log_level --logfile --no-editor --user --print-after --version --yes) + + local curcontext="$curcontext" state line + typeset -A opt_args + local -a cloudproviders; cloudproviders=(bluebox ec2 rackspace slicehost terremark) + _arguments \ + '1: :->knifecmd' \ + '2: :->knifesubcmd' \ + '3: :->knifesubcmd2' \ + '4: :->knifesubcmd3' \ + '5: :->knifesubcmd4' \ + '6: :->knifesubcmd5' + + case $state in + knifecmd) + compadd -Q "$@" bootstrap client configure cookbook "cookbook site" "data bag" diff exec environment user index node recipe role search solo ssh status upload vault windows "$cloudproviders[@]" + ;; + knifesubcmd) + case $words[2] in + bluebox|ec2|rackspace|slicehost|terremark) + compadd "$@" server images + ;; + client) + compadd -Q "$@" "bulk delete" list create show delete edit reregister + ;; + configure) + compadd "$@" client + ;; + cookbook) + compadd -Q "$@" test list create download delete "metadata from" show "bulk delete" metadata upload + ;; + diff) + _arguments '*:file or directory:_files -g "*"' + ;; + environment) + compadd -Q "$@" list create delete edit show "from file" + ;; + user) + compadd -Q "$@" create delete edit list reregister show + ;; + node) + compadd -Q "$@" "from file" create show edit delete list run_list "bulk delete" + ;; + recipe) + compadd "$@" list + ;; + role) + compadd -Q "$@" "bulk delete" create delete edit "from file" list show + ;; + solo) + compadd "$@" bootstrap clean cook init prepare + ;; + upload) + _arguments '*:file or directory:_files -g "*"' + ;; + vault) + compadd -Q "$@" create decrypt delete edit remove "rotate all keys" "rotate keys" show update + ;; + windows) + compadd "$@" bootstrap + ;; + *) + _arguments '2:Subsubcommands:($(_knife_options1))' + ;; + esac + ;; + knifesubcmd2) + case $words[3] in + server) + compadd "$@" list create delete + ;; + images) + compadd "$@" list + ;; + site) + compadd "$@" vendor show share search download list unshare + ;; + show|delete|edit|update) + _arguments '3:Subsubcommands:($(_knife_list_remote "$words[2]"))' + ;; + upload|test) + _arguments '3:Subsubcommands:($(_call_function - "_knife_list_local_$words[2]s") --all)' + ;; + list) + compadd -a "$@" knife_general_flags + ;; + bag) + compadd -Q "$@" show edit list "from file" create delete + ;; + bootstrap|clean|cook|prepare) + compadd "$@" nodes/*.json(N:t:r) + ;; + init) + compadd "$@" ./*(/N:t) + ;; + *) + _arguments '3:Subsubcommands:($(_knife_options2))' + ;; + esac + ;; + knifesubcmd3) + case "$words[3]" in + show) + case "$words[2]" in + cookbook) + versioncomp=1 + _arguments '4:Cookbookversions:($(_knife_cookbook_versions) latest)' + ;; + node|client|role) + compadd "$@" --attribute + ;; + vault) + _arguments '4:Keys:($(_knife_list_remote "$words[2]" "$words[4]"))' + ;; + esac + ;; + update) + case "$words[2]" in + vault) + _arguments '4:Keys:($(_knife_list_remote "$words[2]" "$words[4]"))' + ;; + esac + ;; + esac + case "$words[4]" in + show|edit) + _arguments '4:Subsubsubcommands:($(_knife_list_remote "$words[2]" "$words[3]"))' + ;; + file) + case "$words[2]" in + environment) + _arguments '*:files:_path_files -g "*.(rb|json)" -W "$(_knife_root)/environments"' + ;; + node) + _arguments '*:files:_path_files -g "*.(rb|json)" -W "$(_knife_root)/nodes"' + ;; + role) + _arguments '*:files:_path_files -g "*.(rb|json)" -W "$(_knife_root)/roles"' + ;; + *) + _arguments '*:Subsubcommands:($(_knife_options3))' + ;; + esac + ;; + list) + compadd -a "$@" knife_general_flags + ;; + *) + _arguments '*:Subsubcommands:($(_knife_options3))' + ;; + esac + ;; + knifesubcmd4) + if ((versioncomp > 0)); then + compadd "$@" attributes definitions files libraries providers recipes resources templates + else + case "$words[5]" in + file) + _arguments '*:directory:_path_files -/ -W "$(_knife_root)/data_bags" -qS \ ' + ;; + *) _arguments '*:Subsubcommands:($(_knife_options2))' ;; + esac + fi + ;; + knifesubcmd5) + case "$words[5]" in + file) + _arguments '*:files:_path_files -g "*.json" -W "$(_knife_root)/data_bags/$words[6]"' + ;; + *) + _arguments '*:Subsubcommands:($(_knife_options3))' + ;; + esac + ;; + esac +} + +# Helper functions to provide the argument completion for several depths of commands +_knife_options1() { + local line + for line in $(_call_program commands knife "$words[2]" --help | grep -v "^knife"); do + echo $line | grep "\-\-" + done +} + +_knife_options2() { + local line + for line in $(_call_program commands knife "$words[2]" "$words[3]" --help | grep -v "^knife"); do + echo $line | grep "\-\-" + done +} + +_knife_options3() { + local line + for line in $(_call_program commands knife "$words[2]" "$words[3]" "$words[4]" --help | grep -v "^knife"); do + echo $line | grep "\-\-" + done +} + +# get a list of objects of type x on the server +_knife_list_remote() { + case "$*" in + role|client|node|cookbook|"cookbook site"|"data bag"|environment|user|vault) + _call_program commands knife "$@" list --format json \ + | grep \" \ + | awk '{print $1}' \ + | awk -F"," '{print $1}' \ + | awk -F"\"" '{print $2}' + ;; + "vault "*) + _call_program commands knife vault show "$2" --format json \ + | grep \" \ + | awk '{print $1}' \ + | awk -F"," '{print $1}' \ + | awk -F"\"" '{print $2}' + ;; + esac +} + +# The chef_x_local functions use the knife config to find the paths of relevant objects x to be uploaded to the server +_knife_list_local_cookbooks() { + if [ $KNIFE_RELATIVE_PATH ]; then + local cookbook_path="$(_knife_root)/cookbooks" + else + local knife_rb="${KNIFE_CONF_PATH:-${HOME}/.chef/knife.rb}" + if [ -f ./.chef/knife.rb ]; then + knife_rb="./.chef/knife.rb" + fi + local cookbook_path="${KNIFE_COOKBOOK_PATH:-$(grep -s cookbook_path "$knife_rb" | awk 'BEGIN {FS = "[" }; {print $2}' | sed 's/\,//g' | sed "s/'//g" | sed 's/\(.*\)]/\1/' | cut -d '"' -f2)}" + fi + + local i + for i in $cookbook_path; do + ls $i + done +} + +# This function extracts the available cookbook versions on the chef server +_knife_cookbook_versions() { + _call_program commands knife cookbook show "$words[4]" \ + | grep -v "$words[4]" \ + | grep -v -E '\]|\[|\{|\}' \ + | sed 's/ //g' \ + | sed 's/"//g' +} + +# Searches up from current directory to find the closest folder that has a .chef folder +# Useful for the knife upload/from file commands +_knife_root() { + local directory="$PWD" + while [ $directory != '/' ]; do + test -e "$directory/.chef" && echo "$directory" && return + directory="${directory:h}" + done +} + +_knife "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_language_codes b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_language_codes new file mode 100644 index 00000000..ef9d25a2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_language_codes @@ -0,0 +1,250 @@ +#autoload +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completer for language codes. +# +# Usage: _language_codes ISO-639-1 +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# +# ------------------------------------------------------------------------------ + + +(( $+functions[_language_codes_iso_639_1] )) || +_language_codes_iso_639_1() { + local codes; codes=( + 'aa:Afar' + 'ab:Abkhazian' + 'af:Afrikaans' + 'ak:Akan' + 'sq:Albanian' + 'am:Amharic' + 'ar:Arabic' + 'an:Aragonese' + 'hy:Armenian' + 'as:Assamese' + 'av:Avaric' + 'ae:Avestan' + 'ay:Aymara' + 'az:Azerbaijani' + 'ba:Bashkir' + 'bm:Bambara' + 'eu:Basque' + 'be:Belarusian' + 'bn:Bengali' + 'bh:Bihari languages' + 'bi:Bislama' + 'bo:Tibetan' + 'bs:Bosnian' + 'br:Breton' + 'bg:Bulgarian' + 'my:Burmese' + 'ca:Catalan' + 'cs:Czech' + 'ch:Chamorro' + 'ce:Chechen' + 'zh:Chinese' + 'cu:Church Slavic' + 'cv:Chuvash' + 'kw:Cornish' + 'co:Corsican' + 'cr:Cree' + 'cy:Welsh' + 'cs:Czech' + 'da:Danish' + 'de:German' + 'dv:Divehi' + 'nl:Dutch' + 'dz:Dzongkha' + 'el:Greek, Modern (1453-)' + 'en:English' + 'eo:Esperanto' + 'et:Estonian' + 'eu:Basque' + 'ee:Ewe' + 'fo:Faroese' + 'fa:Persian' + 'fj:Fijian' + 'fi:Finnish' + 'fr:French' + 'fy:Western Frisian' + 'ff:Fulah' + 'ka:Georgian' + 'de:German' + 'gd:Gaelic' + 'ga:Irish' + 'gl:Galician' + 'gv:Manx' + 'gn:Guarani' + 'gu:Gujarati' + 'ht:Haitian' + 'ha:Hausa' + 'he:Hebrew' + 'hz:Herero' + 'hi:Hindi' + 'ho:Hiri Motu' + 'hr:Croatian' + 'hu:Hungarian' + 'hy:Armenian' + 'ig:Igbo' + 'is:Icelandic' + 'io:Ido' + 'ii:Sichuan Yi' + 'iu:Inuktitut' + 'ie:Interlingue' + 'ia:Interlingua (International Auxiliary Language Association)' + 'id:Indonesian' + 'ik:Inupiaq' + 'is:Icelandic' + 'it:Italian' + 'jv:Javanese' + 'ja:Japanese' + 'kl:Kalaallisut' + 'kn:Kannada' + 'ks:Kashmiri' + 'ka:Georgian' + 'kr:Kanuri' + 'kk:Kazakh' + 'km:Central Khmer' + 'ki:Kikuyu' + 'rw:Kinyarwanda' + 'ky:Kirghiz' + 'kv:Komi' + 'kg:Kongo' + 'ko:Korean' + 'kj:Kuanyama' + 'ku:Kurdish' + 'lo:Lao' + 'la:Latin' + 'lv:Latvian' + 'li:Limburgan' + 'ln:Lingala' + 'lt:Lithuanian' + 'lb:Luxembourgish' + 'lu:Luba-Katanga' + 'lg:Ganda' + 'mk:Macedonian' + 'mh:Marshallese' + 'ml:Malayalam' + 'mi:Maori' + 'mr:Marathi' + 'ms:Malay' + 'mk:Macedonian' + 'mg:Malagasy' + 'mt:Maltese' + 'mn:Mongolian' + 'mi:Maori' + 'ms:Malay' + 'my:Burmese' + 'na:Nauru' + 'nv:Navajo' + 'nr:Ndebele, South' + 'nd:Ndebele, North' + 'ng:Ndonga' + 'ne:Nepali' + 'nl:Dutch' + 'nn:Norwegian Nynorsk' + 'nb:Bokmål, Norwegian' + 'no:Norwegian' + 'ny:Chichewa' + 'oc:Occitan (post 1500)' + 'oj:Ojibwa' + 'or:Oriya' + 'om:Oromo' + 'os:Ossetian' + 'pa:Panjabi' + 'fa:Persian' + 'pi:Pali' + 'pl:Polish' + 'pt:Portuguese' + 'ps:Pushto' + 'qu:Quechua' + 'rm:Romansh' + 'ro:Romanian' + 'ro:Romanian' + 'rn:Rundi' + 'ru:Russian' + 'sg:Sango' + 'sa:Sanskrit' + 'si:Sinhala' + 'sk:Slovak' + 'sk:Slovak' + 'sl:Slovenian' + 'se:Northern Sami' + 'sm:Samoan' + 'sn:Shona' + 'sd:Sindhi' + 'so:Somali' + 'st:Sotho, Southern' + 'es:Spanish' + 'sq:Albanian' + 'sc:Sardinian' + 'sr:Serbian' + 'ss:Swati' + 'su:Sundanese' + 'sw:Swahili' + 'sv:Swedish' + 'ty:Tahitian' + 'ta:Tamil' + 'tt:Tatar' + 'te:Telugu' + 'tg:Tajik' + 'tl:Tagalog' + 'th:Thai' + 'bo:Tibetan' + 'ti:Tigrinya' + 'to:Tonga (Tonga Islands)' + 'tn:Tswana' + 'ts:Tsonga' + 'tk:Turkmen' + 'tr:Turkish' + 'tw:Twi' + 'ug:Uighur' + 'uk:Ukrainian' + 'ur:Urdu' + 'uz:Uzbek' + 've:Venda' + 'vi:Vietnamese' + 'vietnamien' + 'vo:Volapük' + 'cy:Welsh' + 'wa:Walloon' + 'wo:Wolof' + 'xh:Xhosa' + 'yi:Yiddish' + 'yo:Yoruba' + 'za:Zhuang' + 'zh:Chinese' + 'zu:Zulu' + ) + _describe -t language-codes 'ISO 639-1 language code' codes "$@" +} + +_language_codes() { + local command="$argv[$#]" ret=1 + + case $command in + ISO-639-1) + _language_codes_${${command//-/_}:l} "${@[1,-2]}" && ret=0 + ;; + *) + _message "unknown command: $command" + ;; + esac + + return ret +} + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_lilypond b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_lilypond new file mode 100644 index 00000000..920f0758 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_lilypond @@ -0,0 +1,134 @@ +#compdef lilypond +# ------------------------------------------------------------------------------ +# Copyright (c) 2021 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for lilypond 2.22.2 (https://lilypond.org/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Andre Kugland (https://github.com/kugland) +# +# ------------------------------------------------------------------------------ + +_arguments -C -S -A "-*" \ + '(- 1 *)-dhelp[show help for scheme options]' \ + '(- 1 *)'{-h,--help}'[show usage information]' \ + '(- 1 *)'{-v,--version}'[show version number]' \ + '(- 1 *)'{-w,--warranty}'[show warranty and copyright]' \ + '(-f --formats)'{-f,--formats=}'[select format(s) to generate]:format(s) to generate:_sequence compadd - pdf svg png ps eps' \ + '--pdf[generate .pdf files]' \ + '--svg[generate .svg files]' \ + '--png[generate .png files]' \ + '--ps[generate .ps files]' \ + '(-E --eps)'{-E,--eps}'[generate .eps files]' \ + '(-O --pspdfopt)'{-O,--pspdfopt=}'[set .ps/.pdf optimization]:.ps/.pdf optimization:(size TeX TeX-GS)' \ + '*'{-d,--define-default=}'[set scheme option]:scheme option:->scheme_opt' \ + '(-e --evaluate)'{-e,--evaluate=}'[evaluate scheme code]:scheme code' \ + '(-H --header)'{-H,--header=}'[dump header field to file]:field' \ + '*'{-I,--include=}'[append directory to include search path]:directory:_files -/' \ + '(-i --init)'{-i,--init=}'[use file as init file]:file:_files -g "*.(#i)ly(-.)"' \ + '(-j --jail)'{-j,--jail=}'[chroot to jail, become user:group and cd into dir]:jail arg (user,group,jail,dir)' \ + '(-o --output)'{-o,--output=}'[set output base filename or folder]:output base filename or folder:_files' \ + '(-l --loglevel -s --silent -V --verbose)'{-l,--loglevel=}'[set level of the log]:log level [INFO]:(NONE ERROR WARNING BASIC PROGRESS INFO DEBUG)' \ + '(-l --loglevel -s --silent -V --verbose)'{-s,--silent}'[no progress, only error messages (same as --loglevel=ERROR)]' \ + '(-l --loglevel -s --silent -V --verbose)'{-V,--verbose}'[be verbose (same as --loglevel=DEBUG)]' \ + '*:input file:_files -g "*.(#i)ly(-.)"' + +case $state in + scheme_opt) + _values 'scheme option' \ + 'anti-alias-factor[set anti-alias factor]:anti-alias-factor (1-8)' \ + 'aux-files[create .tex, .texi, .count files in the EPS backend]:aux-files:(\#t \#f)' \ + 'backend[select backend]:backend:(eps null ps scm svg)' \ + 'check-internal-types[check every property assignment for types]:check-internal-types:(\#t \#f)' \ + 'clip-systems[generate cut-out snippets of a score]:clip-systems:(\#t \#f)' \ + 'crop[match the size of the normal output to the typeset image]:crop:(\#t \#f)' \ + 'datadir[LilyPond prefix for data files]: :_files -/' \ + 'debug-gc-assert-parsed-dead[ensure that all references to parsed objects are dead]:debug-gc-assert-parsed-dead:(\#t \#f)' \ + 'debug-gc[dump memory debugging statistics]:debug-gc:(\#t \#f)' \ + 'debug-lexer[debug the flex lexer]:debug-lexer:(\#t \#f)' \ + 'debug-page-breaking-scoring[dump scores for many different page breaking configurations]:debug-page-breaking-scoring:(\#t \#f)' \ + 'debug-parser[debug the bison parser]:debug-parser:(\#t \#f)' \ + 'debug-property-callbacks[debug cyclic callback chains]:debug-property-callbacks:(\#t \#f)' \ + 'debug-skylines[debug skylines]:debug-skylines:(\#t \#f)' \ + 'delete-intermediate-files[delete unusable, intermediate PostScript files]:delete-intermediate-files:(\#t \#f)' \ + 'dump-signatures[dump output signatures of each system]:dump-signatures:(\#t \#f)' \ + 'embed-source-code[embed the source files inside the generated PDF document]:embed-source-code:(\#t \#f)' \ + 'eps-box-padding[pad left edge of the output EPS bounding box by given amount]:eps-box-padding (mm)' \ + 'font-export-dir[directory for exporting fonts as PostScript files]:font-export-dir:_files -/' \ + 'font-ps-resdir[build a subset of PostScript resource directory for embedding fonts]:font-ps-resdir' \ + 'gs-api[whether to use the Ghostscript API (read-only if not available)]:gs-api:(\#t \#f)' \ + 'gs-load-fonts[load fonts via Ghostscript]:gs-load-fonts:(\#t \#f)' \ + 'gs-load-lily-fonts[load only LilyPond fonts via Ghostscript]:gs-load-lily-fonts:(\#t \#f)' \ + 'gs-never-embed-fonts[make Ghostscript embed only TrueType fonts and no other font format]:gs-never-embed-fonts:(\#t \#f)' \ + 'gui[run LilyPond from a GUI and redirect stderr to a log file]:gui:(\#t \#f)' \ + 'help[show this help]:help:(\#t \#f)' \ + 'include-book-title-preview[include book titles in preview images]:include-book-title-preview:(\#t \#f)' \ + 'include-eps-fonts[include fonts in separate-system EPS files]:include-eps-fonts:(\#t \#f)' \ + 'include-settings[included file before the score is processed]:include-settings:_files -g "*.(#i)ly(-.)"' \ + 'job-count[process in parallel, using the given number of jobs]:job-count' \ + 'log-file[output log to file (.log will be appended)]:log-file' \ + 'max-markup-depth[maximum depth for the markup tree]:max-markup-depth' \ + 'midi-extension[set the default file extension for MIDI output]:midi-extension:(mid midi)' \ + 'music-font-encodings[use font encodings and the PostScript "show" operator with music fonts]:music-font-encodings:(\#t \#f)' \ + 'music-strings-to-paths[convert text strings to paths when glyphs belong to a music font]:music-strings-to-paths:(\#t \#f)' \ + 'outline-bookmarks[use bookmarks in table of contents metadata]:outline-bookmarks:(\#t \#f)' \ + 'paper-size[set default paper size]:paper-size:(\"a1\" \"a2\" \"a3\" \"a4\" \"a5\" \"a6\" \"b1\" \"b2\" \"b3\" \"b4\" \"b5\" \"b6\" \"c1\" \"c2\" \"c3\" \"c4\" \"c5\" \"c6\" \"f4\" \"government-legal\" \"government-letter\" \"imperial\" \"junior-legal\" \"ledger\" \"legal\" \"letter\" \"folio\" \"octavo\" \"quarto\" \"tabloid\")' \ + 'pixmap-format[set GhostScript'\''s output format for pixel images]:pixmap-format:(fpng jpeg jpegcmyk jpeggray png16m pngalpha pnggray pngmonod)' \ + 'png-height[image height for PNG output]:png-height (pixels)' \ + 'png-width[image width for PNG output]:png-width (pixels)' \ + 'point-and-click[add point & click links to PDF and SVG output]:point-and-click:(\#t \#f)' \ + 'preview[create preview images also]:preview:(\#t \#f)' \ + 'print-pages[print pages in the normal way]:print-pages:(\#t \#f)' \ + 'profile-property-accesses[keep statistics of get_property() calls]:profile-property-accesses:(\#t \#f)' \ + 'protected-scheme-parsing[continue when errors in inline Scheme are caught in the parser]:protected-scheme-parsing:(\#t \#f)' \ + 'read-file-list[specify file which contains a list of input files]:read-file-list:(\#t \#f)' \ + 'relative-includes[look for the included file relative to the current file]:relative-includes:(\#t \#f)' \ + 'resolution[set resolution for generating PNG pixmaps to given value]:resolution (dpi)' \ + 'safe[run in safer mode]:safe:(\#t \#f)' \ + 'separate-log-files[use separate log files for each input]:separate-log-files:(\#t \#f)' \ + 'show-available-fonts[list available font names]:show-available-fonts:(\#t \#f)' \ + 'strict-infinity-checking[force a crash on encountering Inf and NaN floating point exceptions]:strict-infinity-checking:(\#t \#f)' \ + 'strip-output-dir[don'\''t use directories from input files while constructing output file names]:strip-output-dir:(\#t \#f)' \ + 'strokeadjust[set the PostScript '\''strokeadjust'\'' operator explicitly]:strokeadjust:(\#t \#f)' \ + 'svg-woff[use woff font files in SVG backend]:svg-woff:(\#t \#f)' \ + 'verbose[verbose output]:verbose:(\#t \#f)' \ + 'warning-as-error[change all warning and programming_error messages into errors]:warning-as-error:(\#t \#f)' + ;; +esac + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_lunchy b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_lunchy new file mode 100644 index 00000000..4c327b74 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_lunchy @@ -0,0 +1,138 @@ +#compdef lunchy +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for lunchy 0.10.4 (https://github.com/mperham/lunchy). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Blake Walters (https://github.com/markupboy) +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_lunchy() { + local state line cmds ret=1 + + _arguments -C \ + '1: :->cmds' \ + '*::arg:->args' && ret=0 + + case $state in + cmds) + local -a cmds + cmds=( + 'ls:Show the list of installed agents, with optional filter' + 'list:Show the list of installed agents, with optional filter' + 'start:Start the first agent matching pattern' + 'stop:Stop the first agent matching pattern' + 'restart:Stop and start the first agent matching pattern' + 'status:Show the PID and label for all agents, with optional filter' + 'install:Install an agents plist file to ~/Library/LaunchAgents or /Library/LaunchAgents' + 'uninstall:Uninstall name from ~/Library/LaunchAgents or /Library/LaunchAgents' + 'show:Show the contents of the launchctl daemon file' + 'edit:Open the launchctl daemon file in the default editor(EDITOR environment variable)' + ) + _describe -t commands 'lunchy command' cmds && ret=0 + ;; + args) + local -a cmd_args + case $line[1] in + (ls|list) + cmd_args=( + '-l[display absolute paths of the launchctl daemon files when showing list of installed agents]' + '1:: :_lunchy_installed_agents' + ) + ;; + (start) + cmd_args=( + '-w[persist the start command, the agent will load on startup]' + '-F[force start agents]' + '1: :_lunchy_installed_agents' + ) + ;; + (stop) + cmd_args=( + '-w[persist the stop command, the agent will never load]' + '1: :_lunchy_agents' + ) + ;; + (restart) + cmd_args=( + '1: :_lunchy_agents' + ) + ;; + (install) + cmd_args=( + '-s[use a symlink for installation]' + '1: :_files' + ) + ;; + (uninstall) + cmd_args=( + '1: :_lunchy_agents' + ) + ;; + (*) + cmd_args=( + '1: :_lunchy_installed_agents' + ) + ;; + esac + + _arguments -s -S "$cmd_args[@]" && ret=0 + ;; + esac + + return ret +} + +(( $+functions[_lunchy_agents] )) || +_lunchy_agents() { + local -a agents=(${(@f)"$(lunchy status | awk 'NR>=2{print $3}')"}) + _values 'agents' $agents +} + +(( $+functions[_lunchy_installed_agents] )) || +_lunchy_installed_agents() { + local -a agents=(${(@f)"$(lunchy ls)"}) + _values 'agents' $agents +} + +_lunchy "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mc b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mc new file mode 100644 index 00000000..64eaf00c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mc @@ -0,0 +1,82 @@ +#compdef mc +# ------------------------------------------------------------------------------ +# Copyright (c) 2019 Sebastian Gniazdowski +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Midnight Commander 4.8.28 (https://midnight-commander.org/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Sebastian Gniazdowski (https://github.com/psprint) +# ------------------------------------------------------------------------------ + +setopt localoptions warncreateglobal typesetsilent + +local -a opts +opts=( + {-h,--help}'[show help on options]' + --help-all'[show help on all options]' + --help-terminal'[terminal options help]' + --help-color'[color options help]' + {-a,--stickchars}'[use stickchars to draw]' + '(-c --color -b --nocolor)'{-b,--nocolor}'[requests to run in black and white]' + '(-b --nocolor -c --color)'{-c,--color}'[request to run in color mode]' + {-C,--colors=}'[specifies a color configuration]:arg:' + --configure-options'[print configure options]' + {-d,--nomouse}'[disable mouse support in text version]' + {-d,--debuglevel=}'[save the debug level for SMB VFS]:debug level:(0 1 2 3 4 5 6 7 8 9 10)' + {-e,--edit=}'[edit files]:file:_files' + {-f,--datadir}'[print data directory]' + {-F,--datadir-info}'[print extended info about used data directories]' + {-g,--oldmouse}'[tries to use an old highlight mouse tracking]' + {-k,--resetsoft}'[resets soft keys on HP terminals]' + {-K,--keymap=}'[load definitions of key bindings from specified file]:file:_files' + {-l,--ftplog=}'[log ftp dialog to specified file]:file:_files' + --nokeymap"[don't load key bindings from any file, use default hardcoded keys]" + {-P,--printwd=}'[print last working directory to specified file]:file:_files' + {-s,--slow}'[to run on slow terminals]' + {-S,--skin=}'[show mc with specified skin]:skin:' + {-t,--termcap}'[tries to use termcap instead of terminfo]' + '(-U --subshell -u --nosubshell)'{-u,--nosubshell}'[disables subshell support]' + '(-u --nosubshell -U --subshell)'{-U,--subshell}'[enables subshell support (default)]' + {-v,--view=}'[launches the file viewer on a file]:file:_files' + {-V,--version}'[displays the current version]' + {-x,--xterm}'[forces xterm features]' + {-X,--no-x11}'[disable X11 support]' + '*:pane directory:_directories' +) + +_arguments -s $opts + +# Return value passes through + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_middleman b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_middleman new file mode 100644 index 00000000..ba2e98a2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_middleman @@ -0,0 +1,156 @@ +#compdef middleman +# ------------------------------------------------------------------------------ +# Copyright (c) 2013 Jozef Izso, MIT License +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for middleman (https://middlemanapp.com/) +# Includes commands from middleman-blog and middleman-deploy extensions. +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Jozef Izso (https://github.com/jozefizso) +# +# ------------------------------------------------------------------------------ + +local ret=1 state + +local -a common_ops +common_ops=( + "--help[Display help]" +) + +typeset -A opt_args +_arguments \ + ':subcommand:->subcommand' \ + $common_ops \ + '*::options:->options' && ret=0 + +case $state in + subcommand) + local -a subcommands + subcommands=( + "article:Create a new blog article" + "build:Builds the static site for deployment" + "console:Start an interactive console in the context of your Middleman application" + "deploy:Deploy a middleman built site over rsync, ftp, sftp, or git (e.g. gh-pages on github)." + "extension:Create Middleman extension scaffold" + "init:Create new project" + "server:Start the preview server" + "upgrade:Upgrade installed bundle" + "version:Show version" + ) + + _describe -t subcommands 'middleman subcommand' subcommands && ret=0 + ;; + + options) + local -a args + args=( + $common_ops + ) + + local -a help + help=( + "--help[Display help information]" + ) + + case $words[1] in + article) + args=( + {-d,--date}"[The date to create the post with (defaults to now)]:date" + ) + ;; + + build) + args=( + "--clean[Remove orphaned files from build (Default: true)]" + "--no-clean[Disable removing orphaned files from build]" + {-g,--glob}"[Build a subset of the project]:glob" + "--verbose[Print debug messages]" + "--instrument[Print instrument messages]:instrument" + "--profile[Generate profiling report for the build]" + ) + ;; + + console) + args=( + {-e,--environment}"[The environment Middleman will run under (Default: development)]:environment" + "--verbose[Print debug messages]" + ) + ;; + + deploy) + args=( + {-b,--build-before}"[Run \`middleman build\` before the deploy step]" + ) + ;; + + extension) + args=( + "--git[Default: true]" + ) + ;; + + init) + args=( + {-T,--template}"[Use a project template: default, html5, mobile, smacss, empty. (Default: default)]:template" + "--css-dir [The path to the css files]:css_dir" + "--js-dir [The path to the javascript files]:js_dir" + "--images-dir [The path to the image files]:images_dir" + "--rack [Include a config.ru file]" + "--skip-gemfile [Don't create a Gemfile]" + "--skip-bundle [Don't run bundle install]" + "--skip-git [Skip Git ignores and keeps]" + ) + ;; + + server) + args=( + {-e,--environment}"[The environment Middleman will run under (Default: development)]:environment" + {-h,--host}"[Bind to HOST address (Default: 0.0.0.0)]:host" + {-p,--port}"[The port Middleman will listen on (Default: 4567)]:port" + "--verbose [Print debug messages]" + "--instrument [Print instrument messages]:instrument" + "--disable-watcher [Disable the file change and delete watcher process]" + "--profile [Generate profiling report for server startup]" + "--reload-paths [Additional paths to auto-reload when files change]:reload_paths" + "--force-polling [Force file watcher into polling mode]" + ) + ;; + + upgrade) + args=() + ;; + + version) + args=() + ;; + esac + + _arguments $args && ret=0 + ;; +esac + +return ret diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mina b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mina new file mode 100644 index 00000000..cfe920f2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mina @@ -0,0 +1,68 @@ +#compdef mina +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Mina (http://nadarei.co/mina/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Kazuya Takeshima (https://github.com/mitukiii) +# +# ------------------------------------------------------------------------------ + + +local curcontext="$curcontext" state line cmds ret=1 + +_arguments -C \ + {-h,--help}'[Show help]' \ + {-V,--version}'[Show program version]' \ + {-v,--verbose}'[Show commands as they happen]' \ + {-s,--simulate}'[Run in simulation mode]' \ + {-t,--trace}'[Show backtraces when errors occur]' \ + -f'[Use FILE as the deploy configuration]:file:_files' \ + '*: :->cmds' && ret=0 + +case $state in + cmds) + cmds=( ${(f)"$(_call_program commands mina -T 2> /dev/null | sed -e 's/:/\\:/g; s/\[/\\[/g; s/\]/\\]/g; s/mina \([^ ]*\) .*# /\1:/g')"} ) + _describe -t commands 'mina command' cmds && ret=0 + ;; +esac + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mix b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mix new file mode 100644 index 00000000..0cd8ecde --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mix @@ -0,0 +1,238 @@ +#compdef mix +#autoload + +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Elixir Mix +# +# Last updated: 18.04.2017 +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Han Ngo (https://github.com/tieubao) +# * Teja Sophista (https://github.com/tejanium) +# +# ------------------------------------------------------------------------------ + +local -a _1st_arguments +_1st_arguments=( + 'app.start:Starts all registered apps' + 'app.tree:Prints the application tree' + 'archive:Lists installed archives' + 'archive.build:Archives this project into a .ez file' + 'archive.install:Installs an archive locally' + 'archive.uninstall:Uninstalls archives' + 'clean:Deletes generated application files' + 'cmd:Executes the given command' + 'compile:Compiles source files' + 'deps:Lists dependencies and their status' + "deps.clean:Deletes the given dependencies' files" + 'deps.compile:Compiles dependencies' + 'deps.get:Gets all out of date dependencies' + 'deps.tree:Prints the dependency tree' + 'deps.unlock:Unlocks the given dependencies' + 'deps.update:Updates the given dependencies' + 'do:Executes the tasks separated by comma' + 'ecto:Prints Ecto help information' + 'ecto.create:Creates the repository storage' + 'ecto.drop:Drops the repository storage' + 'ecto.dump:Dumps the repository database structure' + 'ecto.gen.migration:Generates a new migration for the repo' + 'ecto.gen.repo:Generates a new repository' + 'ecto.load:Loads previously dumped database structure' + 'ecto.migrate:Runs the repository migrations' + 'ecto.migrations:Displays the repository migration status' + 'ecto.rollback:Rolls back the repository migrations' + 'escript:Lists installed escripts' + 'escript.build:Builds an escript for the project' + 'escript.install:Installs an escript locally' + 'escript.uninstall:Uninstalls escripts' + 'gettext.extract:Extracts translations from source code' + 'gettext.merge:Merge template files into translation files' + 'help:Prints help information for tasks' + 'hex:Prints Hex help information' + 'hex.build:Builds a new package version locally' + 'hex.config:Reads, updates or deletes Hex config' + 'hex.docs:Fetch or open documentation of a package' + 'hex.info:Prints Hex information' + 'hex.key:Manages Hex API key' + 'hex.outdated:Shows outdated Hex deps for the current project' + 'hex.owner:Manages Hex package ownership' + 'hex.public_keys:Manages Hex public keys' + 'hex.publish:Publishes a new package version' + 'hex.retire:Retires a package version' + 'hex.search:Searches for package names' + 'hex.user:Registers or manages Hex user' + 'loadconfig:Loads and persists the given configuration' + 'local:Lists local tasks' + 'local.hex:Installs Hex locally' + 'local.phoenix:Updates Phoenix locally' + 'local.phx:Updates the Phoenix project generator locally' + 'local.public_keys:Manages public keys' + 'local.rebar:Installs Rebar locally' + 'new:Creates a new Elixir project' + 'phoenix.gen.html:Generates controller, model and views for an HTML based resource' + 'phoenix.server:Starts applications and their servers' + 'phx.digest:Digests and compresses static files' + 'phx.digest.clean:Removes old versions of static assets.' + 'phx.gen.auth:Generates a flexible, pre-built authentication system' + 'phx.gen.channel:Generates a Phoenix channel' + 'phx.gen.context:Generates a context with functions around an Ecto schema' + 'phx.gen.html:Generates controller, views, and context for an HTML resource' + 'phx.gen.json:Generates controller, views, and context for a JSON resource' + 'phx.gen.presence:Generates a Presence tracker' + 'phx.gen.schema:Generates an Ecto schema and migration file' + 'phx.gen.secret:Generates a secret' + 'phx.new:Creates a new Phoenix application' + 'phx.new.ecto:Creates a new Ecto project within an umbrella project' + 'phx.new.web:Creates a new Phoenix web project within an umbrella project' + 'phx.routes:Prints all routes' + 'phx.server:Starts applications and their servers' + 'profile.fprof:Profiles the given file or expression with fprof' + 'run:Runs the given file or expression' + "test:Runs a project's tests" + 'xref:Performs cross reference checks' + '--help:Describe available tasks' + '--version:Prints the Elixir version information' +) + +__task_list () +{ + local expl + declare -a tasks + + tasks=( + 'app.start' + 'app.tree' + 'archive' + 'archive.build' + 'archive.install' + 'archive.uninstall' + 'clean' + 'cmd' + 'compile' + 'deps' + 'deps.clean' + 'deps.compile' + 'deps.get' + 'deps.tree' + 'deps.unlock' + 'deps.update' + 'do' + 'ecto' + 'ecto.create' + 'ecto.drop' + 'ecto.dump' + 'ecto.gen.migration' + 'ecto.gen.repo' + 'ecto.load' + 'ecto.migrate' + 'ecto.migrations' + 'ecto.rollback' + 'escript' + 'escript.build' + 'escript.install' + 'escript.uninstall' + 'gettext.extract' + 'gettext.merge' + 'format' + 'help' + 'hex' + 'hex.build' + 'hex.config' + 'hex.docs' + 'hex.info' + 'hex.key' + 'hex.outdated' + 'hex.owner' + 'hex.public_keys' + 'hex.publish' + 'hex.retire' + 'hex.search' + 'hex.user' + 'loadconfig' + 'local' + 'local.hex' + 'local.public_keys' + 'local.rebar' + 'new' + 'phoenix.gen.html' + 'phoenix.server' + 'phx.digest' + 'phx.digest.clean' + 'phx.gen.auth' + 'phx.gen.channel' + 'phx.gen.context' + 'phx.gen.html' + 'phx.gen.json' + 'phx.gen.presence' + 'phx.gen.schema' + 'phx.gen.secret' + 'phx.routes' + 'phx.server' + 'profile.fprof' + 'run' + 'test' + 'xref' + ) + + _wanted tasks expl 'help' compadd $tasks +} + +local expl + +local curcontext="$curcontext" state line +typeset -A opt_args + +_arguments -C \ + ':command:->command' \ + '*::options:->options' + +case $state in + (command) + _describe -t commands "mix subcommand" _1st_arguments + return + ;; + + (options) + case $line[1] in + (help) + _arguments ':feature:__task_list' + return + ;; + (test|format|run) + _arguments ':PATH:_files' + return + ;; + esac + ;; +esac diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mkcert b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mkcert new file mode 100644 index 00000000..6c639dea --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mkcert @@ -0,0 +1,58 @@ +#compdef mkcert +# ------------------------------------------------------------------------------ +# Copyright (c) 2023 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for mkcert v1.4.4 (https://github.com/FiloSottile/mkcert) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_arguments \ + '(- *)-help[Print help message]' \ + '(- *)-version[Print version information]' \ + '-install[Install the local CA in the system trust store]' \ + '-uninstall[Uninstall the local CA]' \ + '-cert-file[Specify cert file output path]:path:_files' \ + '-key-file[Specify key file output path]:path:_files' \ + '-p12-file[Specify p12 file output path]:path:_files' \ + '-client[Generate a certificate for client authentication]' \ + '-ecdsa[Generate a certificate with an ECDSA key]' \ + '-pkcs12[Generate a ".p12" PKCS #12 file]' \ + '-csr[Generate a certificate based on the supplied CSR]:csr' \ + '(- *)-CAROOT[Print the CA certificate and key storage location]' \ + && return 0 + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mssh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mssh new file mode 100644 index 00000000..49b26d64 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mssh @@ -0,0 +1,108 @@ +#compdef mssh +# ------------------------------------------------------------------------------ +# Copyright (c) 2020 Hyeon Kim +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# mssh is a Python client for accessing EC2 instances via AWS EC2 Instance +# Connect. +# +# References: +# https://docs.aws.amazon.com/AWSEC2/latest/UserGuide/ec2-instance-connect-methods.html#ec2-instance-connect-connecting-ec2-cli +# https://github.com/aws/aws-ec2-instance-connect-cli +# https://pypi.org/project/ec2instanceconnectcli/ +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Hyeon Kim (https://hyeon.me/) +# +# ------------------------------------------------------------------------------ + +# Do nothing if there's no AWS CLI +if (( ! $+commands[aws] )); then + return +fi + +# Define function only when it doesn't exist +(( $+functions[_mssh_cache_policy] )) || _mssh_cache_policy() { + # Cache invalidates after 30 seconds + # + # Reference: + # https://zsh.sourceforge.net/Doc/Release/Expansion.html#index-globbing_002c-qualifiers + local -a oldp + oldp=( "$1"(ms+30) ) + (( $#oldp )) +} + +# Unless user explicitly turned off caching, enable caching just for this context +local existing_setting +zstyle -s ":completion:${curcontext}:" use-cache existing_setting +if [[ -z "${existing_setting}" ]]; then + zstyle ":completion:${curcontext}:" use-cache on +fi + +# Update cache policy only when there was no existing policy +local existing_policy +zstyle -s ":completion:${curcontext}:" cache-policy existing_policy +if [[ -z "${existing_policy}" ]]; then + zstyle ":completion:${curcontext}:" cache-policy _mssh_cache_policy +fi + +local -a instances +if _cache_invalid mssh_instances || ! _retrieve_cache mssh_instances; then + # Cache is invalid or caching retrieval failed (usually due to disabled cache) + + # Store the output of the AWS CLI separately + # + # Reference: + # https://unix.stackexchange.com/a/430182 + local stderr + local -i exit_code + () { + aws ec2 describe-instances \ + --query 'Reservations[].Instances[] | [?State.Name == `running`].join(`:`, [InstanceId, Tags[?Key == `Name`].Value | [0]])' \ + --output text \ + >${1} 2>${2} + exit_code=${?} + IFS=$'\n\t' instances=($(<${1})) + stderr=$(<${2}) + } =(:) =(:) + + if (( $exit_code == 0 )); then + # AWS CLI successfully executed + _store_cache mssh_instances instances + else + # AWS CLI failed, abort autocompletion + _message -r "\ +Failed autocomplete due to following reason: +${stderr}" + return + fi +fi + +_describe 'command' instances + +# Reference: +# https://zsh.sourceforge.net/Doc/Release/Completion-System.html +# https://github.com/zsh-users/zsh-completions/blob/master/zsh-completions-howto.org diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mussh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mussh new file mode 100644 index 00000000..d52cb40e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mussh @@ -0,0 +1,86 @@ +#compdef mussh +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for MUltihost SSH Wrapper (https://sourceforge.net/projects/mussh/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Mario Fernandez (https://github.com/sirech) +# +# ------------------------------------------------------------------------------ + +local curcontext="$curcontext" state line ret=1 +typeset -A opt_args + +# TODO: +# -i: admit more than one use +# -d, -v, -t: control input +# -m: Accept number (but also empty) +# -h: Accept multiple hosts, also more than one use +# -H: Accept multiple files, also more than one use + +_arguments -C \ + '--help[display this help message]' \ + '-V[print version info and exit]' \ + '-d[Verbose debug]:level (from 0 to 2)' \ + '-v[SSH debug level]:level (from 0 to 3)' \ + '-m[Run concurrently]' \ + '(-b -B)-b[Print each hosts output in a block without mingling with other hosts output]' \ + '(-b -B)-B[Allow hosts output to mingle. (default)]' \ + '(-a -A)-a[Force loading ssh-agent]' \ + '(-a -A)-A[Do NOT load ssh-agent]' \ + '(-u -U)-u[Unique. Eliminate duplicate hosts. (default)]' \ + '(-u -U)-U[Do NOT make host list unique]' \ + '-P[Do NOT fall back to passwords on any host. This will skip hosts where keys fail]' \ + '-i[Load an identity file. May be used more than once]:identity' \ + '-o[Args to pass to ssh with -o option]:ssh-args' \ + '(-l -L)-l[Use _login_ when no other is specified with the hostname]:login' \ + '(-l -L)-L[Force use of _login_ on all hosts]:login' \ + '-s[Path to shell on remote host]:shell' \ + '-t[Timeout setting for each session]:timeout' \ + '-p[Host to use as proxy]:[user@]host' \ + '-po[Args to pass to ssh on proxy with -o option]:ssh-args' \ + '(-h -H)-h[Add a host to list of hosts]:[user@]host' \ + '(-h -H)-H[Add contents of file to list of hosts]:host file:_files' \ + '(-c -C)-c[Add a command or quoted list of commands to list of commands to be executed on each host]:command' \ + '(-c -C)-C[Add file contents to list of commands to be executed on each host]:commands file:_files' \ + '(-q)-q[No output unless necessary]' && ret=0 + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mvn b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mvn new file mode 100644 index 00000000..c7922f54 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_mvn @@ -0,0 +1,617 @@ +#compdef mvn mvnDebug +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Maven 3.8.6 (https://maven.apache.org/). +# +# Status: See FIXME and TODO tags. +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# +# ------------------------------------------------------------------------------ +# Notes +# ----- +# +# * By default advanced phases are displayed only if you start typing them. To have +# them always displayed: +# +# zstyle ':completion:*:mvn:*' show-all-phases true +# +# * By default full form plugins (groupId:artifactId[:version]) are only shown if you +# start typing them. To have them always displayed: +# +# zstyle ':completion:*:mvn:*' show-full-form-plugins true +# +# * By default only the plugins for which the completion has already been +# called ("mvn plugin:") are shown. To define your own list of plugins: +# +# maven_plugins=(jboss tomcat gwt android) +# zstyle ':completion:*:mvn:*' plugins $maven_plugins +# +# * To have a better presentation of completions: +# +# zstyle ':completion:*:*:mvn:*:matches' group 'yes' +# zstyle ':completion:*:*:mvn:*:options' description 'yes' +# zstyle ':completion:*:*:mvn:*:options' auto-description '%d' +# zstyle ':completion:*:*:mvn:*:descriptions' format $'\e[1m -- %d --\e[22m' +# zstyle ':completion:*:*:mvn:*:messages' format $'\e[1m -- %d --\e[22m' +# zstyle ':completion:*:*:mvn:*:warnings' format $'\e[1m -- No matches found --\e[22m' +# +# ------------------------------------------------------------------------------ + + +_mvn() { + typeset -A opt_args + local context state line + + local curcontext="$curcontext" maven_version excl_opts + + excl_opts=(-h --help -v --version -ep --encrypt-password -emp --encrypt-master-password) + + _pick_variant -r maven_version maven3='Maven 3' maven2='Maven 2' unknown --version + if [[ $maven_version == 'maven3' ]]; then + opts=( + "($excl_opts -T --threads)"{-T,--threads}'[thread count, for instance 2.0C where C is core multiplied]:thread count:_mvn_thread_counts' + "($excl_opts -t --toolchains)"{-t,--toolchains}'[alternate path for the user toolchains file]:toolchains file:_mvn_toolchains_files' + "($excl_opts -l --log-file)"{-l,--log-file}'[log file to where all build output will go]:log file:_mvn_log_files' + ) + elif [[ $maven_version == 'maven2' ]]; then + opts=( + "($excl_opts -cpu --check-plugin-updates -up --update-plugins -npu --no-plugin-updates -o --offline)"{-cpu,--check-plugin-updates,-up,--update-plugins}'[force upToDate check for any relevant registered plugins]' + "($excl_opts -npr --no-plugin-registry)"{-npr,--no-plugin-registry}'[don'\''t use plugin-registry.xml for plugin versions]' + "($excl_opts -npu --no-plugin-updates -cpu --check-plugin-updates -up --update-plugins)"{-npu,--no-plugin-updates}'[suppress upToDate check for any relevant registered plugins]' + "($excl_opts -r --reactor)"{-r,--reactor}'[dynamically build reactor from subdirectories]:reactor:_mvn_reactors' + ) + fi + + [[ -n ${(M)words:#"-pl"} || -n ${(M)words:#"--projects"} ]] && opts+=( + "($excl_opts -am --also-make)"{-am,--also-make}'[if project list is specified, also build projects required by the list]' + "($excl_opts -amd --also-make-dependents)"{-amd,--also-make-dependents}'[if project list is specified, also build projects that depend on projects on the list]' + ) + + _arguments -C \ + "(- : *)"{-h,--help}'[display help information]' \ + "(- : *)"{-v,--version}'[display version information]' \ + "(- : *)"{-emp,--encrypt-master-password}'[encrypt master security password]:master password:_mvn_passwords' \ + "(- : *)"{-ep,--encrypt-password}'[encrypt server password]:password:_mvn_passwords' \ + "($excl_opts -B --batch-mode)"{-B,--batch-mode}'[run in non-interactive (batch) mode]' \ + "($excl_opts -b --builder)"{-b,--builder}'[The id of the build strategy to use]' \ + "($excl_opts -V --show-version)"{-V,--show-version}'[display version information without stopping build]' \ + "($excl_opts -q --quiet -X --debug)"{-q,--quiet}'[quiet output, only show errors]' \ + "($excl_opts -X --debug -q --quiet)"{-X,--debug}'[produce execution debug output]' \ + "($excl_opts -llr --legacy-local-repository)"{-llr,--legacy-local-repository}'[Use Maven 2 Legacy Local Repository behaviour]' \ + "($excl_opts -N --non-recursive)"{-N,--non-recursive}'[do not recurse into sub-projects]' \ + "($excl_opts -C --strict-checksums -c --lax-checksums)"{-C,--strict-checksums}'[fail the build if checksums don'\''t match]' \ + "($excl_opts -c --lax-checksums -C --strict-checksums)"{-c,--lax-checksums}'[warn if checksums don'\''t match]' \ + "($excl_opts -e --errors)"{-e,--errors}'[produce execution error messages]' \ + "($excl_opts -f --file)"{-f,--file}'[force the use of an alternate POM file]:POM file:_mvn_pom_files' \ + "($excl_opts -s --settings)"{-s,--settings}'[alternate path for the user settings file]:settings file:_mvn_settings_files' \ + "($excl_opts -gs --global-settings)"{-gs,--global-settings}'[alternate path for the global settings file]:global settings file:_mvn_settings_files' \ + "($excl_opts -gt --global-toolchains)"{-gt,--global-toolchains}'[alternate path for the global toolchains file]:global toolchains file:_mvn_toolchains_files' \ + "($excl_opts -fae --fail-at-end -ff --fail-fast -fn --fail-never)"{-fae,--fail-at-end}'[only fail the build afterwards, allow all non-impacted builds to continue]' \ + "($excl_opts -ff --fail-fast -fae --fail-at-end -fn --fail-never)"{-ff,--fail-fast}'[stop at first failure in reactorized builds]' \ + "($excl_opts -fn --fail-never -fae --fail-at-end -ff --fail-fast)"{-fn,--fail-never}'[never fail the build, regardless of project result]' \ + "($excl_opts)*"{-P,--activate-profiles}'[comma-delimited list of profiles to activate]:profile:_mvn_profiles -s ,' \ + "($excl_opts -pl --projects)"{-pl,--projects}'[build specified reactor projects instead of all projects]:project list:_mvn_projects -s ,' \ + "($excl_opts -rf --resume-from)"{-rf,--resume-from}'[resume reactor from specified project]:project:_mvn_projects' \ + "($excl_opts -o --offline -U --update-snapshots -cpu --check-plugin-updates -up --update-plugins)"{-o,--offline}'[work offline]' \ + "($excl_opts -U --update-snapshots -nsu --no-snapshot-updates -o --offline)"{-U,--update-snapshots}'[force a check for updated releases and snapshots on remote repositories]' \ + "($excl_opts -nsu --no-snapshot-updates -U --update-snapshots -o --offline)"{-nsu,--no-snapshot-updates}'[Suppress SNAPSHOT updates]' \ + "($excl_opts -ntp --no-transfer-progress)"{-ntp,--no-transfer-progress}'[Do not display transfer progress when downloading or uploading ]' \ + "*"{-D-,--define}'[define a system property]:property:_mvn_properties' \ + "${opts[@]}" \ + "($excl_opts)*: :_mvn_args" +} + +(( $+functions[_mvn_args] )) || +_mvn_args() { + _alternative \ + 'phases:phase:_mvn_phases' \ + 'plugin-colon-goals:plugin colon goal:_mvn_plugin_colon_goals' +} + +(( $+functions[_mvn_phases] )) || +_mvn_phases() { + local phases + phases=( + 'clean:remove all files generated by the previous build' + 'compile:compile the source code of the project' + 'test:run tests using a suitable unit testing framework' + 'package:take the compiled code and package it in its distributable format, such as a JAR' + 'integration-test:process and deploy the package if necessary into an environment where integration tests can be run' + 'verify:run any checks to verify the package is valid and meets quality criteria' + 'install:install the package into the local repository, for use as a dependency in other projects locally' + 'deploy:done in an integration or release environment, copies the final package to the remote repository' + 'site:generates the projects site documentation' + 'site-deploy:deploys the generated site documentation to the specified web server' + ) + if [[ $#PREFIX -gt 0 ]] || zstyle -t ":completion:${curcontext}:" show-all-phases; then + phases+=( + 'pre-clean:executes processes needed prior to the actual project cleaning' + 'post-clean:executes processes needed to finalize the project cleaning' + 'validate:validate the project is correct and all necessary information is available' + 'initialize:initialize build state, e.g. set properties or create directories' + 'generate-sources:generate any source code for inclusion in compilation' + 'process-sources:process the source code, for example to filter any values' + 'generate-resources:generate resources for inclusion in the package' + 'process-resources:copy and process the resources into the destination directory, ready for packaging' + 'process-classes:post-process the generated files from compilation' + 'generate-test-sources:generate any test source code for inclusion in compilation' + 'process-test-sources:process the test source code, for example to filter any values' + 'generate-test-resources:create resources for testing' + 'process-test-resources:copy and process the resources into the test destination directory' + 'test-compile:compile the test source code into the test destination directory' + 'process-test-classes:post-process the generated files from test compilation' + 'prepare-package:perform any operations necessary to prepare a package before the actual packaging' + 'pre-integration-test:perform actions required before integration tests are executed' + 'post-integration-test:perform actions required after integration tests have been executed' + 'pre-site:executes processes needed prior to the actual project site generation.' + 'post-site:executes processes needed to finalize the site generation, and to prepare for site deployment' + ) + fi + _describe -t 'phases' "phase" phases +} + +(( $+functions[_mvn_plugins] )) || +_mvn_plugins() { + local ret=1 + if [[ $words[CURRENT] == *.* ]] || zstyle -t ":completion:${curcontext}:" show-full-form-plugins; then + _wanted full-form-plugins expl 'full form plugin' _mvn_full_form_plugins && ret=0 + else + _wanted plugin-prefixes expl 'plugin prefix' _mvn_plugin_prefixes && ret=0 + fi + return ret +} + +(( $+functions[_mvn_plugin_colon_goals] )) || +_mvn_plugin_colon_goals() { + local ret=1 + if [[ $words[CURRENT] == *.* ]] || zstyle -t ":completion:${curcontext}:" show-full-form-plugins; then + _wanted full-form-plugin-colon-goals expl 'full form plugin colon goal' _mvn_full_form_plugin_colon_goals && ret=0 + else + _wanted plugin-prefix-colon-goals expl 'plugin prefix colon goal' _mvn_plugin_prefix_colon_goals && ret=0 + fi + return ret +} + +(( $+functions[_mvn_plugin_prefix_colon_goals] )) || +_mvn_plugin_prefix_colon_goals() { + local ret=1 + if compset -P '*:'; then + local plugin="${IPREFIX%:}" + _wanted goals expl "${plugin} plugin goal" _mvn_plugin_goals $plugin && ret=0 + else + _wanted plugin-prefixes expl 'plugin prefix' _mvn_plugin_prefixes -qS: && ret=0 + fi + return ret +} + +(( $+functions[_mvn_plugin_prefixes] )) || +_mvn_plugin_prefixes() { + local plugins + zstyle -a ":completion:${curcontext}:" plugins plugins + [[ $#plugins -eq 0 ]] && plugins=($(__mvn_get_plugin_prefix $(__mvn_get_cache_dir)/mvn/plugins/*(:t))) + _describe -t plugin-prefixes 'plugin prefix' plugins $@ +} + +(( $+functions[_mvn_full_form_plugin_colon_goals] )) || +_mvn_full_form_plugin_colon_goals() { + local ret=1 + # FIXME Duplicates _mvn_full_form_plugins + if compset -P 1 '*:'; then + local groupId="${${IPREFIX%:}##*:}" + if compset -P 1 '*:'; then + local artifactId="${${IPREFIX%:}##*:}" + if compset -P 1 '*:'; then + local version="${${IPREFIX%:}##*:}" + _wanted goals expl "${artifactId}:${version} goal" _mvn_plugin_goals "${groupId}:${artifactId}:${version}" && ret=0 + else + _alternative \ + "versions:${artifactId} version:_mvn_artifact_versions -qS: ${groupId}:${artifactId}" \ + "goals:${artifactId} goal:_mvn_plugin_goals ${groupId}:${artifactId}" \ + && ret=0 + fi + else + _wanted artifactIds expl "${groupId} artifactId" _mvn_groupId_artifactIds -qS: $groupId && ret=0 + fi + else + _wanted groupIds expl "groupId" _mvn_groupIds -qS: && ret=0 + fi + return ret +} + +(( $+functions[_mvn_full_form_plugins] )) || +_mvn_full_form_plugins() { + local ret=1 chunk="${PREFIX%%:*}" + if compset -P 1 '*:'; then + local groupId="$chunk" + chunk="${PREFIX%%:*}" + if compset -P 1 '*:'; then + _wanted versions expl "${current} version" _mvn_artifact_versions $@ "${groupId}:${chunk}" && ret=0 + else + _wanted artifactIds expl "${groupId} artifactId" _mvn_groupId_artifactIds -qS: "${groupId}" && ret=0 + fi + else + _wanted groupIds expl "groupId" _mvn_groupIds -qS: && ret=0 + fi + return ret +} + +(( $+functions[_mvn_groupIds] )) || +_mvn_groupIds() { + local repository_location=$(__mvn_get_repository_location) update_policy ret=1 + + zstyle -s ":completion:${curcontext}:" cache-policy update_policy + [[ -z "$update_policy" ]] && zstyle ":completion:${curcontext}:" cache-policy _mvn_groupIds_caching_policy + + if [[ -d $repository_location ]]; then + unset _groupIds + if ( [[ ${+_groupIds} -eq 0 ]] || _cache_invalid "mvn/repositories/${repository_location}/groupIds" ) && ! _retrieve_cache "mvn/repositories/${repository_location}/groupIds"; then + _groupIds=($repository_location/**/) + _groupIds=(${${${(u)_groupIds:h:h}#"$repository_location/"}//\//.}) + [[ $#_groupIds -gt 0 ]] && _store_cache "mvn/repositories/${repository_location}/groupIds" _groupIds + fi + + [[ $#_groupIds -gt 0 ]] && _multi_parts $@ . _groupIds && ret=0 + fi + + return ret +} + +(( $+functions[_mvn_groupId_artifactIds] )) || +_mvn_groupId_artifactIds() { + local groupId_repository_location="${$(__mvn_get_repository_location)}/${${@[-1]}//\.//}" ret=1 + + if [[ -d $groupId_repository_location ]]; then + local artifactIds; artifactIds=($groupId_repository_location/*/*/*.pom(:h:h:t)) + _describe -t artifactIds "artifactId" artifactIds $@[0,-2] && ret=0 + fi + + return ret +} + +(( $+functions[_mvn_artifact_versions] )) || +_mvn_artifact_versions() { + local artifact_repository_location="${$(__mvn_get_repository_location)}/${${@[-1]}//[\.:]//}" ret=1 + + if [[ -d $artifact_repository_location ]]; then + local versions; versions=($artifact_repository_location/*/*.pom(:h:t)) + _describe -t versions "version" versions $@[0,-2] + fi + + return ret +} + +(( $+functions[_mvn_plugin_goals] )) || +_mvn_plugin_goals() { + local ret=1 plugin="$@[-1]" update_policy + + zstyle -s ":completion:${curcontext}:" cache-policy update_policy + [[ -z "$update_policy" ]] && zstyle ":completion:${curcontext}:" cache-policy _mvn_goals_caching_policy + + unset _goals + if ( [[ ${+_goals} -eq 0 ]] || _cache_invalid "mvn/plugins/${plugin}" ) && ! _retrieve_cache "mvn/plugins/${plugin}"; then + setopt localoptions extendedglob + _goals=(${(s:,,,:)${${${(f)${${${(f)${${${${(F)${(S)${(f)"$(_call_program goals $words[1] -N org.apache.maven.plugins:maven-help-plugin:2.1.1:describe -Dplugin=$plugin)"}//#$(__mvn_get_plugin_prefix $plugin):/,,,}}:#*BUILD FAILURE*}#*This plugin has*goals#:}%For more information, run \'mvn help:describe*}}//:/\\:}}}// ##/ }// Description\\: /:}}) + [[ $#_goals -gt 0 ]] && _store_cache "mvn/plugins/${plugin}" _goals + fi + + [[ $#_goals -gt 0 ]] && _describe -t "goals" "${plugin} goal" _goals $@[0,-2] && ret=0 + + return ret +} + +(( $+functions[_mvn_profiles] )) || +_mvn_profiles() { + + # FIXME Use "mvn help:all-profiles" output instead of parsing settings and pom files... + # Blocked on http://jira.codehaus.org/browse/MPH-82 and http://jira.codehaus.org/browse/MPH-83 + local profs update_policy settings_file=$(__mvn_get_settings_file) parent_pom_file=$(__mvn_get_parent_pom_file) cache_name profiles_section ret=1 + + # TODO Should be split into _mvn_profiles/mvn_profiles_lists + + zstyle -s ":completion:${curcontext}:" cache-policy update_policy + [[ -z "$update_policy" ]] && zstyle ":completion:${curcontext}:" cache-policy _mvn_profiles_caching_policy + + profs=() + + # Resolve profiles from settings.xml + if [[ -f $settings_file ]]; then + unset _profiles + cache_name="mvn/profiles${settings_file:A}" # FIXME Don't use A modifier, it is only available on Zsh >= 4.3.10 + if ( [[ ${+_profiles} -eq 0 ]] || _cache_invalid "$cache_name" ) && ! _retrieve_cache "$cache_name"; then + _profiles=() + profiles_section="${(M)${(f)$(<$settings_file)}:#**}" + if [[ -n "$profiles_section" ]]; then + for profile in ${(s:,,,:)${${${(S)${(S)${(S)${(S)${${profiles_section#*}%*}//*<\/repositories>}//*<\/pluginRepositories>}//*<\/build>}//<\/id>*/,,,}##*}%%*}}; do + [[ -z ${(M)profiles:#"$profile"*} ]] && _profiles+=("$profile"'['"in settings file"']') + done + fi + [[ $#_profiles -gt 0 ]] && _store_cache "$cache_name" _profiles + fi + profs+=($_profiles) + fi + + # Resolve project profiles + if [[ -f $parent_pom_file ]]; then + unset _profiles + cache_name="mvn/profiles${parent_pom_file:A}" # FIXME Don't use A modifier, it is only available on Zsh >= 4.3.10 + if ( [[ ${+_profiles} -eq 0 ]] || _cache_invalid "$cache_name" ) && ! _retrieve_cache "$cache_name"; then + _profiles=() + setopt localoptions extendedglob + for file in ${parent_pom_file:h}/**/pom.xml~*target\/*; do # FIXME project.build.directory is not always target/ + profiles_section="${(M)${(f)$(<$file)}:#**}" + if [[ -n "$profiles_section" ]]; then + for profile in ${(s:,,,:)${${${(S)${(S)${(S)${(S)${${profiles_section#*}%*}//*<\/repositories>}//*<\/pluginRepositories>}//*<\/build>}//<\/id>*/,,,}##*}%%*}}; do + [[ -z ${(M)profiles:#"$profile"*} ]] && _profiles+=("$profile"'['"in ${file#${parent_pom_file:h}\/}"']') + done + fi + done + [[ $#_profiles -gt 0 ]] && _store_cache "$cache_name" _profiles + fi + profs+=($_profiles) + fi + + compset -P '-'; compset -P '+'; compset -P '!' # FIXME Only works for the first profile + + [[ $#profs -gt 0 ]] && _values $@ 'profile' "${profs[@]}" && ret=0 + + return ret +} + +(( $+functions[_mvn_projects] )) || +_mvn_projects() { + # TODO Projects can also be given in the form [groupId:]artifactId. + # TODO Should be split into _mvn_projects/mvn_projects_lists + local pom_file=$(__mvn_get_parent_pom_file) ret=1 + + if [[ -f $pom_file ]]; then + setopt localoptions extendedglob + local projects; projects=(${pom_file:h}/*/**/pom.xml~*target\/*) # FIXME project.build.directory is not always target/ + projects=(${${projects#.\/}:h}) + [[ $#projects -gt 0 ]] && _values "$@" 'project' "${projects[@]}" && ret=0 + fi + + return ret +} + +(( $+functions[_mvn_properties] )) || +_mvn_properties() { + local ret=1 + if compset -P '*='; then + _wanted property-values expl 'property value' _mvn_property_values ${${IPREFIX%=}#-D} && ret=0 + else + _wanted property-names expl 'property name' _mvn_property_names -qS= && ret=0 + fi + return ret +} + +(( $+functions[_mvn_property_names] )) || +_mvn_property_names() { + # FIXME "-qS=" should be inherited from _mvn_properties + local alternatives; alternatives=( + "common-property-names:common property name:_mvn_common_property_names -qS=" + ) + for plugin_colon_goal in ${(M)words:#[^-]*:*}; do + alternatives+=("plugin-property-names:plugin property name:_mvn_plugin_goal_property_names -qS= ${plugin_colon_goal}") + done + _alternative "${alternatives[@]}" +} + +(( $+functions[_mvn_common_property_names] )) || +_mvn_common_property_names() { + local properties; properties=( + 'skipTests:skip tests execution' + 'maven.test.skip:skip tests compilation and execution' + 'gpg.passphrase:gpg passphrase' + 'tycho.mode:enable maven mode for Tycho projects to disable p2 resolution' + ) + _describe -t 'common-property-names' 'common property name' properties $@ +} + +(( $+functions[_mvn_plugin_goal_property_names] )) || +_mvn_plugin_goal_property_names() { + local plugin_colon_goal="$@[-1]" update_policy ret=1 + + zstyle -s ":completion:${curcontext}:" cache-policy update_policy + [[ -z "$update_policy" ]] && zstyle ":completion:${curcontext}:" cache-policy _mvn_properties_caching_policy + + unset _properties + if ( [[ ${+_properties} -eq 0 ]] || _cache_invalid "mvn/plugins/${plugin_colon_goal}" ) && ! _retrieve_cache "mvn/plugins/${plugin_colon_goal}"; then + # FIXME Does not work for: + # android:apk (new line before expression) + # ear:ear (unknown cause) + _properties=(${(M)${(ps:,,,:)${${${${(pj: :)${${${(f)${"$(_call_program properties $words[1] -N org.apache.maven.plugins:maven-help-plugin:2.1.1:describe -Dplugin=${plugin_colon_goal%:*} -Dgoal=${plugin_colon_goal##*:} -Ddetail)"#*Available parameters:}%%\[INFO\]*}//# [a-z]*/,,,}##*Expression: \$\{}}//\}[[:space:]]##/:}//[[:space:]]##/ }//[[:space:]]#,,,[[:space:]]#/,,,}}:#[a-zA-Z]##:*}) + [[ $#_properties -gt 0 ]] && _store_cache "mvn/plugins/${plugin_colon_goal}" _properties + fi + + [[ $#_properties -gt 0 ]] && _describe -t "${plugin_colon_goal//:/-}-property-names" "${plugin_colon_goal} property name" _properties $@[0,-2] && ret=0 + + return ret +} + +(( $+functions[_mvn_property_values] )) || +_mvn_property_values() { + local ret=1 + setopt localoptions extendedglob + case $@[-1] in + ((#i)*pomFile*) _wanted pom-files expl 'POM file' _mvn_pom_files && ret=0;; + ((#i)*file*) _wanted files expl 'file' _files && ret=0;; + ((#i)*groupId*) _wanted groupIds expl 'groupId' _mvn_groupIds && ret=0;; + ((#i)*artifactId*) _wanted artifactIds expl 'artifactId' _mvn_groupId_artifactIds ${${(M)${(ps.:.)opt_args[(K)-D]}:#groupId=*}#groupId=} && ret=0;; + ((#i)*version*) _wanted versions expl 'version' _mvn_artifact_versions ${${(M)${(ps.:.)opt_args[(K)-D]}:#groupId=*}#groupId=}:${${(M)${(ps.:.)opt_args[(K)-D]}:#artifactId=*}#artifactId=} && ret=0;; + ((#i)*repositoryId*) _message -e repositoryIds 'repositoryId' && ret=0;; # TODO Not implemented + ((#i)*classifier*) _message -e classifiers 'classifier' && ret=0;; + ((#i)*scope*) _wanted scopes expl 'scope' _mvn_scopes && ret=0;; + ((#i)*url*) _wanted urls expl 'url' _urls && ret=0;; # TODO Use _alternative and add repository urls from settings + projects + ((#i)*(password|passphrase)*) _wanted passwords expl password _mvn_passwords && ret=0;; + ((#i)*(createChecksum|generatePom|maven.test.skip)*) _wanted booleans expl 'boolean' _mvn_booleans && ret=0;; + ((#i)*user*) _wanted users expl 'user' _users && ret=0;; # TODO Use _alternative and add repository usernames from settings + projects + ((#i)*plugin*) _wanted plugin expl 'plugin' _mvn_plugins && ret=0;; + ((#i)*tycho.mode*) _wanted tychomodes expl 'tychomode' _mvn_tycho_modes && ret=0;; + (*) _default && ret=0;; + esac + return ret +} + +(( $+functions[_mvn_scopes] )) || +_mvn_scopes() { + local scopes; scopes=( + 'compile:default scope, used if none is specified. Compile dependencies are available in all classpaths of a project. Furthermore, those dependencies are propagated to dependent projects.' + 'provided:much like compile, but indicates you expect the JDK or a container to provide the dependency at runtime. For example, when building a web application for the Java Enterprise Edition, you would set the dependency on the Servlet API and related Java EE APIs to scope provided because the web container provides those classes. This scope is only available on the compilation and test classpath, and is not transitive.' + 'runtime:indicates that the dependency is not required for compilation, but is for execution. It is in the runtime and test classpaths, but not the compile classpath.' + 'test:indicates that the dependency is not required for normal use of the application, and is only available for the test compilation and execution phases.' + 'system:similar to provided except that you have to provide the JAR which contains it explicitly. The artifact is always available and is not looked up in a repository.' + 'import:only used on a dependency of type pom in the section. It indicates that the specified POM should be replaced with the dependencies in that POM'\''s section. Since they are replaced, dependencies with a scope of import do not actually participate in limiting the transitivity of a dependency.' + ) + _describe -t scopes 'scope' scopes +} + +(( $+functions[_mvn_thread_counts] )) || +_mvn_thread_counts() { + local thread_counts; thread_counts=( + '1:build with 1 thread' '1C:build with 1 thread per CPU core' + '2:build with 2 threads' '2C:build with 2 threads per CPU core' + '3:build with 3 threads' '3C:build with 3 threads per CPU core' + '4:build with 4 threads' '4C:build with 4 threads per CPU core' + '5:build with 5 threads' '5C:build with 5 threads per CPU core' + '6:build with 6 threads' '6C:build with 6 threads per CPU core' + '7:build with 7 threads' '7C:build with 7 threads per CPU core' + '8:build with 8 threads' '8C:build with 8 threads per CPU core' + ) + _describe -t thread-counts 'thread count' thread_counts +} + +(( $+functions[_mvn_reactors] )) || +_mvn_reactors() { + _message -e reactors 'reactor' # FIXME No idea what kind of value the "--reactor" option is supposed to take +} + +(( $+functions[_mvn_passwords] )) || +_mvn_passwords() { + _message -e passwords 'password' +} + +(( $+functions[_mvn_pom_files] )) || +_mvn_pom_files() { + _files -g '*pom*\.xml*' +} + +(( $+functions[_mvn_toolchains_files] )) || +_mvn_toolchains_files() { + _files -g '*toolchains*\.xml*' +} + +(( $+functions[_mvn_settings_files] )) || +_mvn_settings_files() { + _files -g '*settings*\.xml*' +} + +(( $+functions[_mvn_log_files] )) || +_mvn_log_files() { + _files +} + +(( $+functions[_mvn_booleans] )) || +_mvn_booleans() { + local booleans; booleans=( + 'true:"true" boolean value' + 'false:"false" boolean value' + ) + _describe -t booleans 'boolean' booleans +} + + +(( $+functions[_mvn_tycho_modes] )) || +_mvn_tycho_modes() { + local tychomodes; tychomodes=( + 'maven:maven mode, Tycho will not do any p2 dependency resolution' + ) + _describe -t tychomodes 'boolean' tychomodes +} + +# ------------------------------------------------------------------------------ +# Helper functions +# ------------------------------------------------------------------------------ + +__mvn_get_pom_file() { + print ${~opt_args[-f]:-${opt_args[--file]:-pom.xml}} +} + +__mvn_get_parent_pom_file() { + local pom_file=$(__mvn_get_pom_file) + while [[ -f ${pom_file:a:h:h}/pom.xml ]]; do + pom_file=${pom_file:a:h:h}/pom.xml; + done + print $pom_file +} + +__mvn_get_settings_file() { + print ${~opt_args[-s]:-${opt_args[--settings]:-$HOME/.m2/settings.xml}} +} + +__mvn_get_repository_location() { + print ${${${${(M)"$(<$(__mvn_get_settings_file))":#**}:-$HOME/.m2/repository}##*}%%<\/localRepository>*} +} + +__mvn_get_plugin_prefix() { + print ${${${${@#*.*:}%%:*}%-plugin}/-#maven-#} +} + +__mvn_get_cache_dir() { + local cache_dir + zstyle -s ":completion:${curcontext}:" cache-path cache_dir + print ${cache_dir:-${ZDOTDIR:-$HOME}/.zcompcache} +} + + +# ------------------------------------------------------------------------------ +# Caching policies +# ------------------------------------------------------------------------------ + +(( $+functions[_mvn_goals_caching_policy] )) || +_mvn_goals_caching_policy() { + # Rebuild if cache is older than one month. + local -a oldp + oldp=( "$1"(NmM+1) ) + (( $#oldp )) +} + +(( $+functions[_mvn_properties_caching_policy] )) || +_mvn_properties_caching_policy() { + _mvn_goals_caching_policy +} + +(( $+functions[_mvn_groupIds_caching_policy] )) || +_mvn_groupIds_caching_policy() { + _mvn_goals_caching_policy +} + +(( $+functions[_mvn_profiles_caching_policy] )) || +_mvn_profiles_caching_policy() { + # Rebuild if cached file more recent than cache. + local cached_file="${1#$(__mvn_get_cache_dir)}" + [[ -f $cached_file && $cached_file -nt "$1" ]] && return 0 + + # Rebuild if cache is older than one week. + local -a oldp + oldp=( "$1"(Nmw+1) ) + (( $#oldp )) && return 0 + + return 1 +} + +_mvn "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_nano b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_nano new file mode 100644 index 00000000..602443be --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_nano @@ -0,0 +1,74 @@ +#compdef nano + +local curcontext="$curcontext" state line +local -i ret=1 + +_arguments -s -S -C \ + '(-)'{-A,--smarthome}'[enable smart home key]' \ + '(-B --backup)'{-B,--backup}'[save backups of existing files]' \ + '(-C --backupdir)'{-C+,--backupdir=}'[specify directory for saving unique backup files]:directory:_directories' \ + '(-D --boldtext)'{-D,--boldtext}'[use bold instead of reverse video text]' \ + '(-E --tabstospaces)'{-E,--tabstospaces}'[convert typed tabs to spaces]' \ + '(-F --multibuffer)'{-F,--multibuffer}'[read a file into a new buffer by default]' \ + '(-G --locking)'{-G,--locking}'[use vim-style lock files]' \ + '(-H --historylog)'{-H,--historylog}'[log & read search replace string history]' \ + '(-I --ignorercfiles)'{-I,--ignorercfiles}"[don't look at nanorc files]" \ + '(-J --guidestripe)'{-J+,--guidestripe=}'[show a guide bar at specified column]:number' \ + '(-K --rawsequences)'{-K,--rawsequences}'[fix numeric keypad key confusion problem]' \ + '(-L --nonewlines)'{-L,--nonewlines}"[don't add an automatic newline]" \ + '(-M --trimblanks)'{-M,--trimblanks}'[trim trailing spaces when hard-wrapping]' \ + '(-N --noconvert -u --unix)'{-N,--noconvert}"[don't convert files from DOS/Mac format]" \ + '(-O --bookstyle)'{-O,--bookstyle}'[leading whitespace means new paragraph]' \ + '(-P --positionlog)'{-P,--positionlog}'[log & read location of cursor position]' \ + '(-Q --quotestr)'{-Q+,--quotestr=}'[specify regular expression to match quoted parts of lines]:regex [^([ \t]*([!#%\:;>|}]|//))+]' \ + '(-R --restricted)'{-R,--restricted}'[restricted mode]' \ + '(-S --softwrap)'{-S,--softwrap}'[display overly long lines on multiple rows]' \ + '(-T --tabsize)'{-T+,--tabsize=}'[set width of a tab]:columns [8]' \ + '(-U --quickblank -c --constantshow -_ --minibar)'{-U,--quickblank}'[do quick statusbar blanking]' \ + '(- *)'{-V,--version}'[print version information and exit]' \ + '(-W --wordbounds -X --wordchars)'{-W,--wordbounds}'[detect word boundaries more accurately]' \ + '(-X --wordchars -W --wordbounds)'{-X+,--wordchars=}'[specify which other characters are word parts]:string' \ + '(-Y --syntax=)'{-Y+,--syntax=}'[syntax definition to use for coloring]:value' \ + '(-Z --zap)'{-Z,--zap}'[let backspace and delete erase a marked region]' \ + '(-a --atblanks)'{-a,--atblanks}'[when soft-wrapping, do it at whitespace]' \ + '(-b --breaklonglines -w --nowrap)'{-b,--breaklonglines}'[automatically hard-wrap overlong lines]' \ + '(-c --constantshow -U --quickblank)'{-c,--constantshow}'[show cursor position constantly]' \ + '(-d --rebinddelete)'{-d,--rebinddelete}'[fix Backspace/Delete confusion problem]' \ + '(-e --emptyline)'{-e,--emptyline}'[keep the line below the title bar empty]' \ + '(-f --rcfile)'{-f,--rcfile=}'[Use only specified file for configuring nano]:file:_files' \ + '(-g --showcursor)'{-g,--showcursor}'[show cursor in file browser & help text]' \ + '(- *)'{-h,--help}'[show help text and exit]' \ + '(-i --autoindent)'{-i,--autoindent}'[automatically indent new lines]' \ + '(-j --jumpyscrolling)'{-j,--jumpyscrolling}'[scroll by half-screen, not by line]' \ + '(-k --cutfromcursor)'{-k,--cutfromcursor}'[cut from cursor to end of line]' \ + '(-l --linenumbers)'{-l,--linenumbers}'[show line numbers in front of the text]' \ + '(-m --mouse)'{-m,--mouse}'[enable the use of the mouse]' \ + '(-n --noread)'{-n,--noread}"[don't read the file (only write it)]" \ + '(-o --operatingdir)'{-o+,--operatingdir=}'[set operating directory]:directory:_directories' \ + '(-p --preserve)'{-p,--preserve}'[preserve XON (^Q) and XOFF (^S) keys]' \ + '(-q --indicator)'{-q,--indicator}'[show a position+portion indicator]' \ + '(-r --fill)'{-r+,--fill=}'[set width for hard-wrap and justification]:width [-8]' \ + '(-s --speller)'{-s+,--speller=}'[enable alternate speller]:program:_command_names -e' \ + '(-t --tempfile)'{-t,--tempfile}'[auto save on exit, do not prompt]' \ + '(-u --unix -N --noconvert)'{-u,--unix}'[save a file by default in Unix format]' \ + '(-v --view)'{-v,--view}'[view mode (read-only)]' \ + '(-w --nowrap -b --breaklonglines)'{-w,--nowrap}"[don't hard-wrap long lines default]" \ + '(-x --nohelp)'{-x,--nohelp}"[don't show the two help lines]" \ + '(-y --afterends)'{-y,--afterends}'[make Ctrl+Right stop at word ends]' \ + '(-z --suspend)'{-z,--suspend}'[enable suspension]' \ + '(-% --stateflags)'{-%,--stateflags}'[show some states in the title bar]' \ + '(-_ --minibar -U --quickblank)'{-_,--minibar}'[suppress the title bar and show information at the bottom of the screen]' \ + '(-! --magic)'{-\!,--magic}'[try libmagic to determine applicable syntax]' \ + '(-0 --zero)'{-0,--zero}'[Hide all bars, use whole terminal]' \ + '(-t -q)*: :->args' && ret=0 + +if [[ -n $state ]]; then + case $PREFIX in + +) _message -e lines "start at a given line" ;; + +[crCR]#[/?]) _message -e 'search string' ;; + +<->,) _message -e 'column number' ;; + *) _files && ret=0 ;; + esac +fi + +return ret diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_nanoc b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_nanoc new file mode 100644 index 00000000..0a87f1a3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_nanoc @@ -0,0 +1,150 @@ +#compdef nanoc +# ------------------------------------------------------------------------------ +# Copyright (c) 2020 OKURA Masafumi, MIT License +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for nanoc 4.12.16 (https://nanoc.app/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * OKURA Masafumi (https://okuramasafumi.com) +# +# This works is heavily inspired by the middleman completion by +# Jozef Izso (https://github.com/jozefizso) +# +# ------------------------------------------------------------------------------ + +local ret=1 +local context state line +local curcontext="$curcontext" + +local -a common_ops +common_ops=( + {-C,--no-color}"[disable color]" + {-V,--verbose}"[make output more detailed]" + {-d,--debug}"[enable debugging]" + \*{-e,--env=}"[set environment]:envvar:_parameters -g '*export*' -qS=" + '(- *)'{-h,--help}"[show the help message and quit]" + {-l,--color}"[enable color]" + '(- *)'{-v,--version}"[show version information and quit]" + {-w,--warn}"[enable warnings]" +) + +typeset -A opt_args +_arguments -C \ + $common_ops \ + '1:subcommand:->subcommand' \ + '*::options:->options' && ret=0 + +case $state in + subcommand) + local -a subcommands + subcommands=( + "check:run issue checks" + "compile:compile items of this site" + "create-site:create a site" + "deploy:deploy the compiled site" + "help:show help" + "prune:remove files not managed by Nanoc from the output directory" + "shell:open a shell on the Nanoc environment" + "show-data:show data in this site" + "show-plugins:show all available plugins" + "show-rules:describe the rules for each item" + "view:start the web server that serves static files" + ) + + _describe -t subcommands 'nanoc subcommand' subcommands && ret=0 + ;; + options) + local -a args + args=( + $common_ops + ) + + case $words[1] in + check) + args=( + {-L,--list}"[list all checks]" + {-a,--all}"[run all checks]" + ) + ;; + compile) + args=( + {-W,--watch}'[watch for changes and recompile when needed]' + "--diff[generate diff]" + ) + ;; + create-site) + args=( + "--force[force creation of new site]" + ) + ;; + deploy) + args=( + {-C,--no-check}"[do not run the issue checks marked for deployment]" + {-D,--list-deployers}"[list available deployers]" + {-L,--list}"[list available locations to deploy to]" + {-n,--dry-run}"[show what would be deployed]" + {-t,--target=}"[specify the location to deploy to (default:\`default\`)]:target" + ) + ;; + prune) + args=( + {-n,--dry-run}"[print files to be deleted instead of actually deleting them]" + {-y,--yes}"[confirm deletion]" + ) + ;; + shell) + args=( + {-p,--preprocess}"[run preprocessor]" + ) + ;; + show-data|show-plugins|show-rules) + args=( + ) + ;; + view) + args=( + {-H,--handler=}"[specify the handler to use(webrick/mongrel/...)]:handler" + {-L,--live-reload}"[reload on changes]" + {-o,--host=}"[specify the host to listen on(default: 127.0.0.1)]:host" + {-p,--port=}"[specify the port to listen on(default: 3000)]:port" + ) + ;; + esac + + _arguments $args && ret=0 + ;; +esac + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_neofetch b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_neofetch new file mode 100644 index 00000000..df02bc05 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_neofetch @@ -0,0 +1,146 @@ +#compdef neofetch +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for neofetch (https://github.com/dylanaraps/neofetch) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Wu Zhenyu +# +# ------------------------------------------------------------------------------ + +_neofetch_files_none() { + _alternative 'none:none:((none\:"Launch the script without a config file"))' 'files:file:_files' +} +_neofetch_sources() { + _alternative 'choices:choices:(auto ascii wallpaper "command output")' 'files: :_files' +} +local func_names=( + title underline os distro model kernel uptime packages shell resolution de wm + wm_theme icons term term_font cpu gpu memory gpu_driver cpu_usage disk battery + font song local_ip public_ip users locale cols +) +local colors=(black blue cyan default gray green magenta orange red white) +local distros=( + AIX Alpine AlterLinux Anarchy Android Antergos antiX + "AOSC OS" "AOSC OS/Retro" Apricity ArcoLinux ArchBox + ARCHlabs ArchStrike XFerience ArchMerge Arch Artix Arya + Bedrock Bitrig BlackArch BLAG BlankOn BlueLight bonsai BSD + BunsenLabs Calculate Carbs CentOS Chakra ChaletOS Chapeau + Chrom Cleanjaro ClearOS Clear_Linux Clover Condres + Container_Linux CRUX Cucumber Debian Deepin DesaOS Devuan + DracOS DarkOs DragonFly Drauger Elementary EndeavourOS Endless + EuroLinux Exherbo Fedora Feren FreeBSD FreeMiNT Frugalware + Funtoo GalliumOS Garuda Gentoo Pentoo gNewSense GNOME GNU + GoboLinux Grombyang Guix Haiku Huayra Hyperbola janus Kali + KaOS KDE_neon Kibojoe Kogaion Korora KSLinux Kubuntu LEDE + LFS Linux_Lite LMDE Lubuntu Lunar macos Mageia MagpieOS + Mandriva Manjaro Maui Mer Minix LinuxMint MX_Linux Namib + Neptune NetBSD Netrunner Nitrux NixOS Nurunner NuTyX + OBRevenge OpenBSD openEuler OpenIndiana openmamba OpenMandriva + OpenStage OpenWrt osmc Oracle OS Elbrus PacBSD Parabola + Pardus Parrot Parsix TrueOS PCLinuxOS Peppermint popos + Porteus PostMarketOS Proxmox Puppy PureOS Qubes Radix + Raspbian Reborn_OS Redstar Redcore Redhat Refracted_Devuan + Regata Rosa sabotage Sabayon Sailfish SalentOS Scientific + Septor SereneLinux SharkLinux Siduction Slackware SliTaz + SmartOS Solus Source_Mage Sparky Star SteamOS SunOS + openSUSE_Leap openSUSE_Tumbleweed openSUSE SwagArch Tails + Trisquel Ubuntu-Budgie Ubuntu-GNOME Ubuntu-MATE Ubuntu-Studio + Ubuntu Venom Void Obarun windows10 Windows7 Xubuntu Zorin IRIX +) +local options=( + --disable"[Allows you to disable an info line from appearing in the output]:func_name:($func_names)" + --title_fqdn"[Hide/Show Fully Qualified Domain Name in title]:on/off:(on off)" + --package_managers"[Hide/Show Package Manager names]:on/off:(on tiny off)" + --os_arch"[Hide/Show OS architecture]:on/off:(on off)" + --speed_type"[Change the type of cpu speed to display]:type:(current min max bios scaling_current scaling_min scaling_max cpufreq)" + --speed_shorthand"[Whether or not to show decimals in CPU speed]:on/off:(on off)" + --cpu_brand"[Enable/Disable CPU brand in output]:on/off:(on off)" + --cpu_cores"[Whether or not to display the number of CPU cores]:type:(logical physical off)" + --cpu_speed"[Hide/Show cpu speed]:on/off:(on off)" + --cpu_temp"[Hide/Show cpu temperature]:C/F/off:(C F off)" + --distro_shorthand"[Shorten the output of distro]:on/off:(on tiny off)" + --kernel_shorthand"[Shorten the output of kernel]:on/off:(on off)" + --uptime_shorthand"[Shorten the output of uptime]:on/off:(on tiny off)" + --refresh_rate"[Whether to display the refresh rate of each monitor]:on/off:(on off)" + --gpu_brand"[Enable/Disable GPU brand in output]:on/off:(on off)" + --gpu_type"[Which GPU to display]:type:(all dedicated integrated)" + --de_version"[Show/Hide Desktop Environment version]:on/off:(on off)" + --gtk_shorthand"[Shorten output of gtk theme/icons]:on/off:(on off)" + --gtk2"[Enable/Disable gtk2 theme/font/icons output]:on/off:(on off)" + --gtk3"[Enable/Disable gtk3 theme/font/icons output]:on/off:(on off)" + --shell_path"[Enable/Disable showing $SHELL path]:on/off:(on off)" + --shell_version"[Enable/Disable showing $SHELL version]:on/off:(on off)" + --disk_show"[Which disks to display]:value:('/' '/dev/sdXX' '/path/to/mount point')" + --disk_subtitle"[What information to append to the Disk subtitle]:type:(name mount dir none)" + --disk_percent"[Hide/Show disk percent]:on/off:(on off)" + --ip_host"[URL to query for public IP]:url:_urls" + --ip_timeout"[Public IP timeout (in seconds)]:int" + --song_format"[Print the song data in a specific format]:format:(%artist% %album% %title%)" + --song_shorthand"[Print the Artist/Album/Title on separate lines]:on/off:(on off)" + --memory_percent"[Display memory percentage]:on/off:(on off)" + --memory_unit"[Memory output unit]:kib/mib/gib:(kib mib gib)" + --music_player"[Manually specify a player to use]:player-name" + --colors"[Changes the text colors]:title color:($colors):@ color:($colors):underline color:($colors):subtitle color:($colors):colon color:($colors):info color:($colors)" + --underline"[Enable/Disable the underline]:on/off:(on off)" + --underline_char"[Character to use when underlining title]:char" + --bold"[Enable/Disable bold text]:on/off:(on off)" + --separator"[Changes the default ':' separator to the specified string]:string" + --color_blocks"[Enable/Disable the color blocks]:on/off:(on off)" + --col_offset"[Left-padding of color blocks]:auto/num" + --block_width"[Width of color blocks in spaces]:num" + --block_height"[Height of color blocks in lines]:num" + --block_range"[Range of colors to print as blocks]:num::num" + --bar_char"[Characters to use when drawing bars]:elapsed char::total char" + --bar_border"[Whether or not to surround the bar with '\\[\\]']:on/off:(on off)" + --bar_length"[Length in spaces to make the bars]:num" + --bar_colors"[Colors to make the bar in elapsed, total]:num::num" + --cpu_display"[Bar mode]:mode:(bar infobar barinfo off)" + --memory_display"[Bar mode]:mode:(bar infobar barinfo off)" + --battery_display"[Bar mode]:mode:(bar infobar barinfo off)" + --disk_display"[Bar mode]:mode:(bar infobar barinfo off)" + --backend"[Which image backend to use]:backend:(ascii caca chafa jp2a iterm2 off sixel tycat w3m kitty)" + --source"[Which image or ascii file to use]:source:_neofetch_sources" + --ascii"[Shortcut to use 'ascii' backend]:source:_neofetch_sources" + --caca"[Shortcut to use 'caca' backend]:source:_neofetch_sources" + --chafa"[Shortcut to use 'chafa' backend]:source:_neofetch_sources" + --iterm2"[Shortcut to use 'iterm2' backend]:source:_neofetch_sources" + --jp2a"[Shortcut to use 'jp2a' backend]:source:_neofetch_sources" + --kitty"[Shortcut to use 'kitty' backend]:source:_neofetch_sources" + --pot"[Shortcut to use 'pot' backend]:source:_neofetch_sources" + --pixterm"[Shortcut to use 'pixterm' backend]:source:_neofetch_sources" + --sixel"[Shortcut to use 'sixel' backend]:source:_neofetch_sources" + --termpix"[Shortcut to use 'termpix' backend]:source:_neofetch_sources" + --tycat"[Shortcut to use 'tycat' backend]:source:_neofetch_sources" + --w3m"[Shortcut to use 'w3m' backend]:source:_neofetch_sources" + --off"[Shortcut to use off backend (Disable ascii art)]" + --ascii_colors"[Colors to print the ascii art]:title color:($colors):@ color:($colors):underline color:($colors):subtitle color:($colors):colon color:($colors):info color:($colors)" + --ascii_distro"[Which Distro's ascii art to print]:distro:($distros)" + --ascii_bold"[Whether or not to bold the ascii logo]:on/off:(on off)" + {-L,--logo}"[Hide the info text and only show the ascii logo]" + --loop"[Redraw the image constantly until Ctrl+C is used]" + --size"[How to size the image]:00px or 00%:(auto none)" + --crop_mode"[Which crop mode to use]:mode:(normal fit fill)" + --crop_offset"[Change the crop offset for normal mode]:value:(northwest north northeast west center east southwest south southeast)" + --xoffset"[How close the image will be to the left edge of the]:px" + --yoffset"[How close the image will be to the top edge of the]:px" + --bg_color"[Background color to display behind transparent image]:color:($colors)" + --gap"[Gap between image and text]:num" + --clean"[Delete cached files and thumbnails]" + --config"[Specify a path to a custom config file]:files or none:_neofetch_files_none" + --no_config"[Don't create the user config file]" + '(- : *)'--print_config"[Print the default config file to stdout]" + --stdout"[Turn off all colors and disables any ASCII/image backend]" + '(- : *)'--help"[Print this text and exit]" + '(- : *)'--version"[Show neofetch version]" + -v"[Display error messages]" + -vv"[Display a verbose log for error reporting]" + '(- : *)'--gen-man"[Generate a manpage for Neofetch in your PWD]" +) + +_arguments $options "*::func_name:($func_names)" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_networkQuality b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_networkQuality new file mode 100644 index 00000000..a9a92767 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_networkQuality @@ -0,0 +1,53 @@ +#compdef networkQuality +# ------------------------------------------------------------------------------ +# Copyright (c) 2023 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for networkQuality on macOS +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_arguments \ + '-C[Use custom configuration URL or path]:url_or_path' \ + '-I[Bind test to interface]:interface:_net_interfaces' \ + '-r[Connect to host or IP]:host' \ + '-c[Produce computer-readable output]' \ + '-h[Show help]' \ + '-k[Disable verification of the server identity via TLS]' \ + '-s[Run tests sequentially instead of parallel upload/download]' \ + '-v[Verbose output]' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_nftables b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_nftables new file mode 100644 index 00000000..c891ead8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_nftables @@ -0,0 +1,500 @@ +#compdef nft +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for nft 0.9.0 (https://www.netfilter.org/projects/nftables/index.html). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Markus Richter ( https://github.com/mqus , ) +# +# ------------------------------------------------------------------------------ +_nft(){ +local -a rules states prev args families options descriptors +local state="start" line nextstate cmd_obj cmd_subcmd cmd_fam cmd_tab cmd_chain #curcontext="$curcontext" + +options=( + '(-)'{-h,--help}'[show help]' \ + '(-)'{-v,--version}'[print version information]' \ + "(-i --interactive)"{-i,--interactive}'[read input from interactive CLI]: :->end' \ + "(-f --file)"{-f,--file}'[read input from ]:nftables rule file:_files' \ + '(-c --check -n --numeric -N)'{-c,--check}"[check command's validity without actually applying the changes]" \ + '(-j --json)'{-j,--json}'[format output in json]' \ + '(-c --check -N)*'{-n,--numeric}'[can be specified up to 3 times, Shows 1:network addresses(default behaviour), 2:internet services (port numbers) and 3:protocols, user IDs, and group IDs numerically]' \ + '(-s --stateless)'{-s,--stateless}'[omit stateful information of ruleset]' \ + '(-N -n --numeric -c --check)'-N'[translate IP addresses to names]' \ + '(-a --handle)'{-a,--handle}'[output rule handle]' \ + '(-e --echo)'{-e,--echo}'[echo what has been added, inserted or replaced]' \ + {-I,--includepath}'[add specified directory to the paths searched for include files]:include directory [/usr/share]:include directory:_directories' +) + +# start a state machine. The state is modified by _arguments if the +# current argument (descriptors) cannot be completed. Each state has to define is successive state and the +# 'descriptors' for _arguments, which essentially tells _arguments how to complete +local _i=0 +while true;do + (( _i+=1 )) + #Guard for endless loops + [[ $_i -gt 100 ]] && return 1 + + descriptors=() + nextstate="end" + case $state in + (start) + ##if line is empty (at the start) or ends with semicolon, autocomplete subcommands, + # else if we are after a space,complete a semicolon (end the current nft command) and start anew + if [[ $line[1] = "" || $line[1] =~ ';$' ]] ; then + descriptors=( ":: :_nft_subcommands" ) + nextstate="category" + else + if [[ $words =~ ' $' ]]; then + descriptors=(':: :(\;)') + else + descriptors=(':argument: ') + fi + nextstate="start" + fi + ;; + (category) + case $line[1] in + (add | list | flush | delete | create | rename | insert | replace | reset) + descriptors=( ":: :_nft_${line[1]}" ) + nextstate=$line[1] + ;; + (monitor) + descriptors=( ":: : _nft_mon_filter" ) + nextstate="mon1" + ;; + (export) + descriptors=( ":: :(ruleset)" ":: :_nft_out_format" ) + nextstate="preend" + ;; + (describe) + descriptors=( ":expression: ") + nextstate="start" #x restart + ;; + (*) + return 1; + ;; + esac + + #descriptors=( "(ruleset)" ) + #nextstate="end" + ;; + (mon1) + case $line[1] in + (new | destroy) +# descriptors=( ":: :_nft_mon_keywords" ":: :_nft_out_format") + descriptors=( ":: : _nft_mon_keywords") + nextstate="mon1" + ;; + (tables | chains | sets | rules | elements | ruleset) + descriptors=( ":: : _nft_out_format") + nextstate="preend" + ;; + esac + ;; + #all completions for create and insert match with the completions of add + (create | insert) + state="add" + ;| + #all completions for reset and flush match with the completions of list + (reset | flush) + state="list" + ;| + #(add(^table)/create(^table)/delete/flush(^ruleset)/insert/list(^ruleset)/rename/replace)[family]table + (reset | delete | insert | rename | replace | add | create | flush | list) + if [[ $state = "add" && $line[1] = "table" ]]; then + descriptors=( ":: :_nft_families" ":table name:") + nextstate="start" #x restart + elif [[ $state = "list" && ( $line[1] = "ruleset" || $line[1] = "tables" ) ]]; then + descriptors=( ":: :_nft_families") + nextstate="start" #x restart + elif [[ $state = "delete" && $line[1] = "table" ]]; then + descriptors=(": : _nft_table all-handle") + nextstate="tcomplete-delete-table" + else + cmd_obj=$line[1] + cmd_subcmd=$state + descriptors=(": : _nft_table all") + nextstate="tcomplete" + fi + ;; + (tcomplete-delete-table) + # if only a family was completed, complete the table name. + case $line[1] in + (arp | bridge | inet | ip | ip6 | netdev) + descriptors=(": : _nft_table ${line[1]}-handle") + cmd_fam=$line[1] + ;; + # if 'handle' was completed, complete the handle number. + (handle) + descriptors=(": : _nft_table_handle_all " ) + ;; + # else, complete nothing and go to the next state. default family is 'ip' + (*) + descriptors=() + cmd_fam="ip" + ;; + esac + nextstate="delete-table" + ;; + (tcomplete) + # if only a family was completed, complete the table name. + case $line[1] in + (arp | bridge | inet | ip | ip6 | netdev) + descriptors=(": : _nft_table ${line[1]}") + cmd_fam=$line[1] + ;; + # else, complete nothing and go to the next state. default family is 'ip' + (*) + descriptors=() + cmd_fam="ip" + ;; + esac + nextstate="$cmd_subcmd-$cmd_obj" + ;; + (list-table) + descriptors=(":: :(\;)") + nextstate="start" + ;; + (delete-table) + #if family AND handle were input, complete handle number for given family. + if [[ $line[1] == "handle" ]]; then + descriptors=(":table handle: _nft_table_handle $cmd_fam" ) + else + descriptors=() + fi + nextstate="start" + ;; + (delete-chain | delete-set | delete-quota | delete-counter | delete-ct\\ helper) + cmd_tab=$line[1] + descriptors=(": : _nft_object $cmd_fam $cmd_tab $cmd_obj true") + nextstate="delete-obj-handle" + ;; + (delete-obj-handle) + if [[ $line[1] == "handle" ]]; then + descriptors=(": : _nft_object_handle $cmd_fam $cmd_tab $cmd_obj") + else + descriptors=(": :(\;)") + fi + nextstate="start" + ;; + (add-chain) + descriptors=(":chain name:") + nextstate="start" + ;; + (rename-chain) + cmd_tab=$line[1] + descriptors=(": : _nft_object $cmd_fam $cmd_tab chain false") + nextstate="add-chain" + ;; + (replace-rule | delete-rule) + cmd_tab=$line[1] + descriptors=(": : _nft_object $cmd_fam $cmd_tab chain false") + nextstate="repdel-rule" + ;; + (repdel-rule) + cmd_chain=$line[1] + descriptors=(": :(handle)" ": : _nft_rule_handle $cmd_fam $cmd_tab ${line[1]}") + if [[ $cmd_subcmd = "replace" ]];then + nextstate="rule-stmt" + else + nextstate="start" + fi + ;; + (add-rule) + cmd_tab=$line[1] + descriptors=(": : _nft_object $cmd_fam $cmd_tab chain false") + nextstate="add-rule-2" + ;; + (add-rule-2) + cmd_chain=$line[1] + descriptors=(": :(handle index position)") + nextstate="add-rule-3" + ;; + (add-rule-3) + case $line[1] in + (index | position) + descriptors=(":${line[1]}:") + ;; + (handle) + descriptors=(": : _nft_rule_handle $cmd_fam $cmd_tab $cmd_chain") + ;; + (*) + descriptors=() + ;; + esac + nextstate="rule-stmt" + ;; + (rule-stmt) + #TODO + # _nft_rule $cmd_fam $cmd_tab $cmd_chain\ + # && return 0; + descriptors=":expression: " + nextstate="start" + ;; + (list-set | list-map | delete-map | list-chain | list-flowtable | delete-flowtable | list-ct\\ helper | list-counter | list-quota | list-meter) + cmd_tab=$line[1] + descriptors=(": : _nft_object $cmd_fam $cmd_tab $cmd_obj false") + nextstate="start" + ;; + #TODO: + #(add-element | delete-element) + #(add-set | add-map) + #(add-flowtable) + #("add-ct\ helper") + #(add-counter) + #(add-quota) + + (*) + return 1; + ;; + esac + _arguments -C -s \ + "${options[@]}" \ + "${descriptors[@]}" \ + "*:: :->$nextstate" \ + && return 0; + +done +} # end _nft + +_nft_subcommands(){ + local commands=( + 'add:add a table, chain, rule, set, map, or object' + 'list:list a ruleset, table, chain, set, map, or object' + 'flush:flush (delete everything from) a ruleset, table, chain, set, or map' + 'export:print the ruleset in a machine readable format (json or xml)' + 'delete:delete a table, chain, rule, set, element, map, or object' + 'create:similar to add but returns an error for existing chain' + 'rename:rename the specified chain' + 'insert:similar to the add command, but the rule is prepended to the beginning of the chain or before the rule at the given position' + 'replace:similar to the add command, but replaces the specified rule' + 'reset:list-and-reset stateful object' + 'monitor:listen to Netlink events' + 'describe:show information about the type of an expression and its data type' + ) + _describe -t commands 'nft subcommand' commands "$@" +} +_nft_mon_filter(){ + local monitor_filters=( + 'new:show only events of created objects' + 'destroy:show only events of deleted objects' + ) + _describe -t monitor_filters 'nft monitor' monitor_filters -J monitor_filters "$@" + _nft_mon_keywords +} + +_nft_mon_keywords(){ + local monitor_keywords=( + 'tables:show table events' + 'chains:show chain events' + 'sets:show set events' + 'rules:show rule events' + 'elements:show only events of element objects' + 'ruleset:show ruleset events, such as table, chain, rule, set, counters and quotas' + ) + _describe -t monitor_keywords 'nft monitor' monitor_keywords -J monitor_keywords "$@" + _nft_out_format +} + +_nft_out_format(){ + local monitor_format=( + 'json:format output to JSON' + 'xml:format output to XML' + ) + _describe -t monitor_format "output format" monitor_format -J monitor_format "$@" +} + +_nft_add(){ + local commands=( + 'table:add a new table' + 'flowtable:add a new flowtable' + 'chain:add a chain to a table' + 'rule:add a rule to an existing chain' + 'set:add a set to a table' + 'map:add a map to a table' + 'element:add one or multiple element(s) to a set or map' + 'ct\ helper:add a ct helper to a table' + 'counter:add a named counter to a table' + 'quota:add a named quota helper to a table' + ) + _describe -t commands 'nft add' commands "$@" +} + +_nft_create(){ + local commands=( + "table:add a table, but return an error if it already exists" + "chain:add a chain to a table, but return an error if it already exists" + "flowtable:add a flowtable, but return an error if it already exists" + ) + _describe -t commands 'nft create' commands "$@" +} + +_nft_delete(){ + local commands=( + "table:delete the specified table" + "chain:delete the specified chain, chain must be empty and mustn't be used as jump target" + "rule:delete the specified rule, rule must be referable to by a handle" + "set:delete the specified set" + "map:delete the specified map" + "element:delete element(s) from the specified set/map" + "flowtable:delete the specified flowtable" + "ct\ helper:delete the specified ct helper" + "counter:delete the specified counter" + "quota:delete the specified quota" + ) + _describe -t commands 'nft delete' commands "$@" +} + +_nft_flush(){ + local commands=( + "ruleset:clear the whole ruleset, including removing all tables and containing objects" + "table:flush all chains and rules of the specified table" + "chain:flush all rules of the specified chain" + "set:remove all elements from the specified set" + "map:remove all elements from the specified map" + ) + _describe -t commands 'nft flush' commands "$@" +} + +_nft_insert(){ + local commands=( + "rule:prepend a rule to the beginning of the chain or before the rule with the given handle" + ) + _describe -t commands 'nft insert' commands "$@" +} + +_nft_list(){ + local commands=( + "ruleset:print the ruleset in human-readable format" + "tables:list all tables (undocumented)" + "table:list all chains and rules of the specified table" + "chain:list all rules of the specified chain" + "set:display the elements in the specified set" + "map:display the elements in the specified map" + "flowtable:list all flowtables" + "ct\ helper:display stateful information the ct helper holds" + "counter:display stateful information the counter holds" + "quota:display stateful information the quota holds" + ) + _describe -t commands 'nft list' commands "$@" +} + +_nft_rename(){ + local commands=( + "chain:replace a chain" + ) + _describe -t commands 'nft rename' commands "$@" +} + +_nft_replace(){ + local commands=( + "rule:replace a rule" + ) + _describe -t commands 'nft replace' commands "$@" +} + +_nft_reset(){ + local commands=( + 'ct\ helper:reset and list a ct helper to a table' + 'counter:reset and list a counter from a table' + 'quota:reset and list a quota object a table' + ) + _describe -t commands 'nft reset' commands "$@" +} +_nft_families(){ + local families=( + "ip:IPv4 address family" + "ip6:IPv6 address family" + "inet:internet (IPv4+IPv6) address family" + "arp:ARP address family, handling IPv4 ARP packets" + "bridge:Bridge address family, handling packets which traverse a bridge device" + "netdev:Netdev address family, handling packets from ingress" + ) + _describe -t families 'nft families' families "$@" +} + +_nft_table(){ + # complete the names of tables and the families of existing tables + #$1 can be: all all-handle -handle + local tables=() + if [[ "$1" =~ "^all" ]]; then + local families=( ${(f)"$(_call_program -p tables nft list tables 2>/dev/null \ + | cut -d\ -f2 )"} ) + # ip is the default family, search also for table names there + 1="${1/all/ip}" + _describe -t families "family" families -J "family" + fi + if [[ "$1" =~ "-handle$" ]]; then + tables=("handle:address the table by handle") + #remove -handle from $1 to be able to complete table names + 1="${1/-handle/}" + _describe -t tables "table" tables -V "handle" + fi + case $1 in + (arp | bridge | inet | ip | ip6 | netdev) + tables=( ${(f)"$(_call_program -p tables nft -a list ruleset 2>/dev/null \ + | grep '^table '"$1" | sed 's/table // ;s/{ # handle // ;s/\(\S*\) \(\S*\) \(\S*\)/\2:type \1, handle \3/' )"} ) + _describe -t tables "table" tables -V "table-name" + ;; + esac +} + +_nft_table_handle(){ + # complete the handles of tables with the specified family (with the table name in the description) + #$1:protocol family + local tables=( ${(f)"$(_call_program -p tables nft -a list ruleset 2>/dev/null \ + | grep '^table '"$1" | sed 's/table // ;s/{ # handle // ;s/\(\S*\) \(\S*\) \(\S*\)/\3:\2(type \1)/' )"} ) + echo $1 > /tmp/znfttab + _describe -t tables "table handle" tables +} + +_nft_table_handle_all(){ + # complete the handles of tables of all families (with the table name in the description) + local tables=( ${(f)"$(_call_program -p tables nft -a list ruleset 2>/dev/null \ + | grep '^table' | sed 's/table // ;s/{ # handle // ;s/\(\S*\) \(\S*\) \(\S*\)/\3:\2(type \1)/' )"} ) + _describe -t tables "table handle" tables +} + +_nft_object(){ + # complete the names of objects contained directly in a table (with the handle number in the description) + #$1:protocol family + #$2:table + #$3:object type (chain/set/map/flowtable/ct helper/counter/quota/meter) + #$4:include 'handle'? + local objects=( ${(f)"$(_call_program -p objects nft -a list table $1 $2 2>/dev/null\ + | grep ""\\s\*$3"" | sed 's/\s*'"$3"' // ;s/ { # \(.*\)/:(\1)/' )"} ) + if $4 ;then + objects+=( "handle:address $3 by handle") + fi + _describe -t objects "$3" objects +} + +_nft_object_handle(){ + # complete handles of objects contained directly in a table (with the name in the description) + #$1:protocol family + #$2:table + #$3:object type (chain/set/ct helper/counter/quota) + local handles=( ${(f)"$(_call_program -p handles nft -a list table $1 $2 2>/dev/null\ + | grep ""\\s\*$3"" | sed 's/\s*'"$3"' // ;s/ { # handle// ;s/\(\S*\) \(\S*\)/\2:\1/' )"} ) + _describe -t handles "$3-handle" handles +} + +_nft_rule_handle(){ + # complete the handles of rules (and put the rule into the description) + #$1:protocol family + #$2:table + #$3:chain name + local rules=( ${(f)"$(_call_program -p nft-rule-handle nft -a list chain $1 $2 $3 2>/dev/null \ + |grep -v '^\s*\(table\|chain\|type\|\}\)'|sed 's/^\s*\(.*\) # handle \(\S*\)$/\2:\1/' )"} ) + # don't sort those entries alphabetically, so they get shown in the order they are executed in nftables + _describe -t rules "rule" rules -V "rules" +} + +#currently, only the `nft` command is covered by this script. +_nft "$@" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_node b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_node new file mode 100644 index 00000000..02a5f847 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_node @@ -0,0 +1,206 @@ +#compdef node +# ------------------------------------------------------------------------------ +# Copyright (c) 2018 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Node.js v20.7.0 (https://nodejs.org) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Mario Fernandez (https://github.com/sirech) +# * Nicholas Penree (https://github.com/drudge) +# * Masafumi Koba (https://github.com/ybiquitous) +# * Shohei YOSHIDA (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_node_files() { + for (( i = 2; i < CURRENT; i++)); do + if [[ ${words[i]} == "--prof-process" ]]; then + _files -g "*.log" + return + fi + done + + _files -g "*.(js|mjs)" +} + +_node_args() { + if (( CURRENT == 2 )); then + _alternative "_node_files" "_values 'command' 'inspect[enable inspector for debugging]'" + return + fi + + _node_files +} + +local curcontext="$curcontext" state line ret=1 +typeset -A opt_args + +_arguments -C \ + '-[script read from stdin (default; interactive mode if a tty)]' \ + '--[indicate the end of node options]' \ + '--abort-on-uncaught-exception[aborting instead of exiting causes a core file to be generated for analysis]' \ + '--allow-child-process[allow use of child process when any permissions are set]' \ + '--allow-fs-read=[allow permissions to read the filesystem]: :_files' \ + '--allow-fs-write=[allow permissions to write in the filesystem]:_files' \ + '--build-snapshot[generate a snapshot blob when the process exits]' \ + '--completion-bash[print source-able bash completion script]' \ + '--cpu-prof[Start the V8 CPU profiler on start up]' \ + '--cpu-prof-dir=[directory where the V8 profiles generated by --cpu-prof]: :_files -/' \ + '--cpu-prof-name=[file name of the V8 profile generated with --cpu-prof]: :_files' \ + '--cpu-prof-interval=[sampling interval in microseconds for the V8 CPU profiler]:number' \ + '--diagnostic-dir=[set dir for all output files(default: current working directory)]:dir:_files -/' \ + '--disable-proto=[disable Object.prototype.__proto__]:mode:(delete throw)' \ + '--disallow-code-generation-from-strings[disallow eval and friends]' \ + '--dns-result-order=[set default value of verbatim in dns.lookup]: :(ipv4first verbatim)' \ + '--enable-etw-stack-walking[provides heap data to ETW Windows native tracing]' \ + '--enable-fips[enable FIPS crypto at startup]' \ + '--enable-network-family-autoselection[enable network address family autosetection algorithm]' \ + '--enable-source-maps[source map support]' \ + '*--env-file=[set environment variables from supplied file]:envfile:_files' \ + '--es-module-specifier-resolution=[extension resolution algorithm for es modules]:resolution algorithm:(explicit none)' \ + '--experimental-import-meta-resolve[experimental ES Module import.meta.resolve() support]' \ + '(--loader --experimental-loader)'{--loader,--experimental-loader}'=[Specify the module of a custom ECMAScript Module loader]: :_files' \ + '--experimental-network-imports[experimental https support for the ES Module loader]' \ + '--experimental-permission[enable the permission system]' \ + '--experimental-policy=[security policy file]: :_files' \ + '--experimental-sea-config=[generate a blob that can be embedded into the single executable application]: :_files' \ + '--experimental-test-coverage[enable code coverage in the test runner]' \ + '--experimental-vm-modules[experimental ES Module support in vm module]' \ + '--experimental-wasm-modules[experimental ES module support for webassembly modules]' \ + '--force-context-aware[disable loading non-context-aware addons]' \ + '--force-fips[force FIPS crypto]' \ + '--frozen-intrinsics[experimental frozen intrinsics support]' \ + '--heap-prof[Start the V8 heap profiler on start up]' \ + '--heap-prof-dir=[Directory where the V8 profiles generated by --heap-prof]: :_files -/' \ + '--heap-prof-interval=[sampling interval in bytes for the V8 heap profile]: :number' \ + '--heap-prof-name=[file name of the V8 heap profile generated]: :_files' \ + '--heapsnapshot-near-heap-limit=[Generate heapsnapshots whenever V8 is approaching the heap limit]:limit' \ + '--heapsnapshot-signal=[Generate heap snapshot on specified signal]:signals:_signals -s' \ + '--huge-max-old-generation-size[increase default maximum heap size with 16GB or more]' \ + '--icu-data-dir=[set ICU data load path to dir (overrides NODE_ICU_DATA) note: linked-in ICU data is present]: :_directories' \ + '--input-type=[set module type for string input]:module type :(commonjs module)' \ + '--insecure-http-parser[Use an insecure HTTP parser that accepts invalid HTTP headers]' \ + '--inspect-brk=-[activate inspector on host:port and break at start of user script]:[host\:]port' \ + '(--debug-port --inspect-port)'{--debug-port,--inspect-port}'=[set host:port for inspector]:[host\:]port' \ + '--inspect=-[activate inspector on host:port (default: 127.0.0.1:9229)]:[host\:]port' \ + '--inspect-publish-uid=[comma separated list of destinations for inspector uid]' \ + '--interpreted-frames-native-stack[help system profilers to translate JavaScript interpreted frames]' \ + '--jitless[Disable runtime allocation of executable memory]' \ + '--max-http-header-size=[set the maximum size of HTTP headers]: :number' \ + '--napi-modules[load N-API modules (no-op - option kept for compatibility)]' \ + '--no-addons[disable loading native addons]' \ + '--no-deprecation[silence deprecation warnings]' \ + '--no-experimental-fetch[disable experimental Fetch API]' \ + '--no-experimental-global-customevent[expose experimental CustomEvent on the global scope]' \ + '--no-experimental-global-webcrypto[expose experimental Web Crypto API on the global scope]' \ + '--no-experimental-repl-await[disable experimental await keyword support in REPL]' \ + '--no-extra-info-on-fatal-exception[hide extra information on fatal exception that causes exit]' \ + '--no-force-async-hooks-checks[disable checks for async_hooks]' \ + '--no-global-search-paths[disable global module search paths]' \ + '--no-warnings[silence all process warnings]' \ + '--node-memory-debug[run with extra debug checks for memory leaks in Node.js itself]' \ + '--openssl-config=[load OpenSSL configuration from the specified file (overrides OPENSSL_CONF)]:file:_files' \ + '--openssl-legacy-provider[enable OpenSSL 3.0 legacy provider]' \ + '--openssl-shared-config[enable OpenSSL shared configuration]' \ + '--pending-deprecation[emit pending deprecation warnings]' \ + '--policy-integrity=[ensure the security policy contents match the specified integrity]' \ + '--preserve-symlinks[preserve symbolic links when resolving]' \ + '--preserve-symlinks-main[preserve symbolic links when resolving the main module]' \ + '--prof[generate V8 profiler output]' \ + '--prof-process[process V8 profiler output generated using --prof]' \ + '--redirect-warnings=[write warnings to file instead of stderr]: :_files' \ + '--report-compact[output compact single-line JSON]' \ + '--report-directory=[custom report path]: :_files -/' \ + '--report-filename=[custom report file name]: :_files' \ + '--report-on-fatalerror[generate diagnostic report on fatal (internal) errors]' \ + '--report-on-signal=[generate diagnostic report upon receiving signals]' \ + '--report-signal=[causes diagnostic report to be produced on provided signal]:signals:_signals -s' \ + '--report-uncaught-exception[generate diagnostic report on uncaught exceptions]' \ + '--secure-heap=[total size of the OpenSSL secure heap]: :number' \ + '--secure-heap-min=[minimum allocation size from the OpenSSL secure heap]' \ + '--snapshot-blob=[path to the snapshot blob that is used to restore the application state]:snapshot:_files' \ + '--test[launch test runner on startup]' \ + '--test-name-pattern=[run tests whose name matches this regular expression]:pattern' \ + '--test-only[run tests with "only" option set]' \ + '*--test-reporter=[report test output using the given reporter]:reporter:(tap spec dot)' \ + '*--test-reporter-destination=[report given reporter to the given destination]:destination:_files' \ + '--test-shard=[run test at specific shard]:shard' \ + '--throw-deprecation[throw an exception on deprecations]' \ + '--title=[the process title to use on startup]:process title' \ + '--tls-cipher-list=[use an alternative default TLS cipher list]:cipher list string' \ + '--tls-keylog=[log TLS decryption keys to named file for traffic analysis]: :_files' \ + '(--tls-max-v1.3)--tls-max-v1.2[set default TLS maximum to TLSv1.2]' \ + '(--tls-max-v1.2)--tls-max-v1.3[set default TLS maximum to TLSv1.3]' \ + '(--tls-min-v1.1 --tls-min-v1.2 --tls-min-v1.3)--tls-min-v1.0[set default TLS minimum to TLSv1.0]' \ + '(--tls-min-v1.0 --tls-min-v1.2 --tls-min-v1.3)--tls-min-v1.1[set default TLS minimum to TLSv1.1]' \ + '(--tls-min-v1.0 --tls-min-v1.1 --tls-min-v1.3)--tls-min-v1.2[set default TLS minimum to TLSv1.2]' \ + '(--tls-max-v1.2 --tls-min-v1.0 --tls-min-v1.1 --tls-min-v1.2)--tls-min-v1.3[set default TLS minimum to TLSv1.3]' \ + '--trace-atomics-wait[trace Atomics.wait operations]' \ + '--trace-deprecation[show stack traces on deprecations]' \ + '--trace-event-categories[comma separated list of trace event categories to record]: :{_values -s , categories node node.async_hooks node.bootstrap node.perf node.perf.usertiming node.perf.timerify node.fs.sync node.vm.script v8}' \ + '--trace-event-file-pattern[Template string specifying the filepath for the trace-events data, it supports ${rotation} and ${pid} log-rotation id. %2$u is the pid.]:template string' \ + '--trace-exit[show stack trace when an environment exits]' \ + '--trace-sigint[prints a stack trace on SIGINT]' \ + '--trace-sync-io[show stack trace when use of sync IO is detected after the first tick]' \ + '--trace-tls[prints TLS packet trace information to stderr]' \ + '--trace-uncaught[show stack traces for the throw behind uncaught exceptions]' \ + '--trace-warnings[show stack traces on process warnings]' \ + '--track-heap-objects[track heap object allocations for heap snapshots]' \ + '--unhandled-rejections=[define unhandled rejections behavior]:rejection behavior:(strict warn none)' \ + '--update-assert-snapshot[update assert snapshot files]' \ + '--use-bundled-ca[use bundled CA store (default)]' \ + '--use-largepages=[re-map the Node.js static code to large memory pages at startup]:mode:(off on silent)' \ + "--use-openssl-ca[use OpenSSL's default CA store]" \ + '(- 1 *)--v8-options[print v8 command line options]' \ + "--v8-pool-size=[set v8's thread pool size]:number" \ + "--watch[run in watch mode]" \ + "--watch-path=[path to watch]: :_node_files" \ + '--watch-preserve-output[preserve outputs on watch mode restart]' \ + '--zero-fill-buffers[automatically zero-fill all newly allocated Buffer and SlowBuffer instances]' \ + {-c,--check}'[syntax check script without executing]' \ + '(- 1 *)'{-e,--eval}'[evaluate script]:inline JavaScript' \ + '(- 1 *)'{-h,--help}'[print node command line options]' \ + {-i,--interactive}'[always enter the REPL even if stdin does not appear to be a terminal]' \ + '(- 1 *)'{-p,--print}'[evaluate script and print result]:inline JavaScript' \ + '*'{-r,--require}'[module to preload (option can be repeated)]: :_node_files' \ + '(- 1 *)'{-v,--version}'[print Node.js version]' \ + '*: :_node_args' && ret=0 + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_nvm b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_nvm new file mode 100644 index 00000000..4c820d2f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_nvm @@ -0,0 +1,235 @@ +#compdef nvm +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for nvm v0.39.2 (https://github.com/nvm-sh/nvm). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Changwoo Park (https://github.com/pismute) +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +__nvm() { + typeset -A opt_args + local context state line + + local curcontext="$curcontext" + local ret=1 + + _arguments -C \ + '--help[show help message]' \ + '--no-color[suppress colored output]' \ + '--version[print out the installed version of nvm]' \ + '1: :__nvm_subcommands' \ + '*::arg:->args' && ret=0 + + case "$state" in + args) + case $words[1] in + (install) + _arguments -C \ + '-s[Skip binary download, install from source only]' \ + '-b[Skip source download, install from binary only]' \ + '--reinstall-packages-from=[When installing, reinstall packages installed in node]:version' \ + '--lts=[When installing, only select from LTS versions]::lts_name' \ + '--skip-default-packages[When installing, skip the default-packages file if it exists]' \ + '--latest-npm[After installing, attempt to upgrade to the latest working npm on the given node version]' \ + '--no-progress[Disable the progress bar on any downloads]' \ + '--alias=[After installing, set the alias specified to the version specified]' \ + '--default[After installing, set default alias to the version specified]' \ + '1::version:__nvm_versions' \ + && ret=0 + ;; + (uninstall) + _arguments -C \ + '--lts=[When installing, only select from LTS versions]::lts_name' \ + '1: :__nvm_installed_versions' \ + && ret=0 + ;; + (use) + _arguments -C \ + '--silent[Silences stdout/stderr output]' \ + '--lts=[When installing, only select from LTS versions]::lts_name' \ + '1: :__nvm_installed_versions' \ + '*: :_normal' \ + && ret=0 + ;; + (exec) + _arguments -C \ + '--silent[Silences stdout/stderr output]' \ + '--lts=[When installing, only select from LTS versions]::lts_name' \ + '1: :__nvm_installed_versions' \ + '*: :_normal' \ + && ret=0 + ;; + (run) + _arguments -C \ + '--silent[Silences stdout/stderr output]' \ + '--lts=[When installing, only select from LTS versions]::lts_name' \ + '1: :__nvm_installed_versions' \ + '*: :_normal' \ + && ret=0 + ;; + (ls) + _arguments -C \ + '--no-colors[Suppress colored output]' \ + '--no-alias[Suppress `nvm alias` output]' \ + && ret=0 + ;; + (ls-remote) + _arguments -C \ + '--silent[Silences stdout/stderr output]' \ + '--lts=[When installing, only select from LTS versions]::lts_name' \ + '--no-colors[Suppress colored output]' \ + && ret=0 + ;; + (version-remote) + _arguments -C \ + '--lts=[When installing, only select from LTS versions]::lts_name' \ + '1: :__nvm_versions' \ + && ret=0 + ;; + (deactivate) + _arguments -C \ + '--silent=[Silences stdout/stderr output]' \ + && ret=0 + ;; + (alias) + _arguments -C \ + '1:name' \ + '2:version:__nvm_installed_versions' \ + && ret=0 + ;; + (unalias) + _arguments -C \ + '1:version:__nvm_installed_versions' \ + && ret=0 + ;; + (reinstall-package) + _arguments -C \ + '--silent=[Silences stdout/stderr output]' \ + '1: :__nvm_installed_versions' \ + && ret=0 + ;; + (which) + _arguments -C \ + '1: : _alternative "version:version:__nvm_installed_versions" "current: :(current)"' \ + && ret=0 + ;; + (cache) + _arguments -C \ + '1: :__nvm_cache_subcommands' \ + && ret=0 + ;; + *) + (( ret )) && _message 'no more arguments' + ;; + esac + ;; + esac + + return ret +} + +__nvm_subcommands() { + local -a commands=( + 'help:Show this message' + 'install:Download and install a ' + 'uninstall:Uninstall a ' + 'use:Modify PATH to use ' + 'exec:Run on ' + 'run:Run with as arguments' + 'current:Display currently activated version of Node' + 'ls:List installed [versions]' + 'ls-remote:List remote versions available for install' + 'version:Show current node version' + 'version-remote:Resolve the given description to a single remote version' + 'deactivate:Undo effects of NVM on current shell' + 'alias:Set an alias named pointing to . Show all aliases beginning with [].' + 'unalias:Deletes the alias named ' + 'install-latest-npm:Attempt to upgrade to the latest working npm on the current node version' + 'reinstall-packages:Reinstall global npm packages contained in to current version' + 'unload:Unload `nvm` from shell' + 'which:Display path to installed node version' + 'cache:Show cache directory/Clear cache' + 'set-colors:Set five text colors using format "yMeBg"' + ) + + _describe -t commands 'command' commands "$@" +} + +__nvm_aliases() { + local aliases + if [[ -d $NVM_DIR/alias ]]; then + aliases=$(echo $NVM_DIR/alias/*(:t)) + fi + echo "$aliases" +} + +__nvm_versions() { + # nvm ls-remote is slow + if [[ ${#__nvm_node_version_cache[@]} == 0 ]]; then + __nvm_node_version_cache=(${(@f)"$(nvm ls-remote --no-colors | awk '{print $1}')"}) + fi + + _describe -t versions 'version' __nvm_node_version_cache "$@" +} + +__nvm_installed_versions() { + local -a versions + + if (( $+functions[nvm_ls] )); then + versions=(${(f)"$(nvm_ls)"}) + fi + + versions=($versions $(__nvm_aliases)) + _describe -t versions 'version' versions "$@" +} + +__nvm_cache_subcommands() { + local -a commands=( + 'dir:Display path to the cache directory for nvm' + 'clear:Empty cache directory for nvm' + ) + _describe -t commands 'command' commands "$@" +} + +__nvm "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_openssl b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_openssl new file mode 100644 index 00000000..9e93be0e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_openssl @@ -0,0 +1,1687 @@ +#compdef openssl +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ + +# openssl command [ command_opts ] [ command_args ] + +_openssl() { + local openssl_commands cmd cmds + if [[ "$CURRENT" -lt 2 ]]; then + # I do not think this can happen... + return + elif [[ "$CURRENT" -eq 2 ]]; then + # first parameter, the command + openssl_commands=(${(z)${${(f)"$(openssl help 2>&1)"}:#([A-Z]|openssl:Error:)*}}) + _describe 'openssl commands' openssl_commands + else + # $CURRENT -gt 2 + cmd="${words[2]}" + # Note: we could use ${(k)functions} to get a list of all functions and + # filter those that start with _openssl_ + # but that would mean defining a new function *somewhere* might mess with + # the completion... + cmds=(asn1parse ca ciphers cms crl crl2pkcs7 dgst dh dhparam dsa dsaparam \ + ec ecparam enc engine errstr gendh gendsa genpkey genrsa nseq ocsp \ + passwd pkcs12 pkcs7 pkcs8 pkey pkeyparam pkeyutl prime rand req rsa \ + rsautl s_client s_server s_time sess_id smime speed spkac srp ts \ + verify version x509) + # check if $cmd is in $cmds, the list of supported commands + if [[ "${cmds[(r)$cmd]}" == "${cmd}" ]]; then + # we should be able to complete $cmd + # run _openssl_$cmd with the remaining words from the command line + shift words + (( CURRENT-- )) + _openssl_${cmd} + elif [[ ${${=${"$(openssl help 2>&1)"/*Cipher commands[^)]#)/}}[(re)$cmd]} == "$cmd" ]]; then + # $cmd is a cipher command, which is practically an alias to enc + shift words + (( CURRENT-- )) + _openssl_enc + elif [[ ${${=${${"$(openssl help 2>&1)"%%Cipher commands*}/*Message Digest commands[^)]#)/}}[(re)$cmd]} == "$cmd" ]]; then + # $cmd is a message digest command, which is practically an alias to dgst + shift words + (( CURRENT-- )) + _openssl_dgst + fi + fi +} + + +_openssl_asn1parse() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format - one of DER PEM]:format:(DER PEM)' \ + '-in[input file]:file:_files' \ + '-out[output file (output format is always DER]:file:_files' \ + "-noout[don't produce any output]" \ + '-offset[offset into file]:number: ' \ + '-length[length of section in file]:number: ' \ + '-i[indent entries]' \ + '-dump[dump unknown data in hex form]' \ + '-dlimit[dump the first arg bytes of unknown data in hex form]:number: ' \ + '-oid[file of extra oid definitions]:file:_files' \ + "-strparse[a series of these can be used to 'dig' into multiple ASN1 blob wrappings]:offset:" \ + '-genstr[string to generate ASN1 structure from]:str:' \ + '-genconf[file to generate ASN1 structure from]:file:_files' +} + + +_openssl_ca() { + # written for openssl 1.0.1k + _arguments -C \ + '-verbose[talk a lot while doing things]' \ + '-config[a config file]:file:_files' \ + '-name[the particular CA definition to use]:section: ' \ + '-gencrl[generate a new CRL]' \ + '-crldays[days is when the next CRL is due]:days: ' \ + '-crlhours[hours is when the next CRL is due]:hours: ' \ + '-startdate[certificate validity notBefore]:date: ' \ + '-enddate[certificate validity notAfter (overrides -days)]:date: ' \ + '-days[number of days to certify the certificate for]:days: ' \ + '-md[md to use, one of md2, md5, sha or sha1]:alg:(md2 md5 sha sha1)' \ + "-policy[the CA 'policy' to support]:policy: " \ + '-keyfile[private key file]:file:_files' \ + '-keyform[private key file format (PEM or ENGINE)]:format:(PEM ENGINE)' \ + '-key[key to decode the private key if it is encrypted]:password: ' \ + '-cert[the CA certificate]:file:_files' \ + '-selfsign[sign a certificate with the key associated with it]' \ + '-in[the input PEM encoded certificate request(s)]:file:_files' \ + '-out[where to put the output file(s)]:file:_files' \ + '-outdir[where to put output certificates]:dir:_files -/' \ + '-infiles[the last argument, requests to process]:*:files:_files' \ + '-spkac[file contains DN and signed public key and challenge]:file:_files' \ + '-ss_cert[file contains a self signed cert to sign]:file:_files' \ + "-preserveDN[don't re-order the DN]" \ + "-noemailDN[don't add the EMAIL field into certificate' subject]" \ + "-batch[don't ask questions]" \ + '-msie_hack[msie modifications to handle all those universal strings]' \ + '-revoke[revoke a certificate (given in file)]:file:_files' \ + "-subj[use arg instead of request's subject]:subject: " \ + '-utf8[input characters are UTF8 (default ASCII)]' \ + '-multivalue-rdn[enable support for multivalued RDNs]' \ + '-extensions[extension section (override value in config file)]:section: ' \ + '-extfile[configuration file with X509v3 extensions to add]:file:_files' \ + '-crlexts[CRL extension section (override value in config file)]:section: ' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-status[shows certificate status given the serial number]:serial: ' \ + '-updatedb[updates db for expired certificates]' +} + + +_openssl_ciphers() { + # written for openssl 1.0.1k + _arguments -C \ + '-v[verbose mode, a textual listing of the SSL/TLS ciphers in OpenSSL]' \ + '-V[even more verbose]' \ + '-ssl2[SSL2 mode]' \ + '-ssl3[SSL3 mode]' \ + '-tls1[TLS1 mode]' \ + ':cipher suite:_list_ciphers' +} + + +_openssl_cms() { + # written for openssl 1.0.1k + _arguments -C \ + '-encrypt[encrypt message]' \ + '-decrypt[decrypt encrypted message]' \ + '-sign[sign message]' \ + '-verify[verify signed message]' \ + '-cmsout[output CMS structure]' \ + '-des3[encrypt with triple DES]' \ + '-des[encrypt with DES]' \ + '-seed[encrypt with SEED]' \ + '-rc2-40[encrypt with RC2-40 (default)]' \ + '-rc2-64[encrypt with RC2-64]' \ + '-rc2-128[encrypt with RC2-128]' \ + '-aes128[encrypt PEM output with cbc aes]' \ + '-aes192[encrypt PEM output with cbc aes]' \ + '-aes256[encrypt PEM output with cbc aes]' \ + '-camellia128[encrypt PEM output with cbc camellia]' \ + '-camellia192[encrypt PEM output with cbc camellia]' \ + '-camellia256[encrypt PEM output with cbc camellia]' \ + "-nointern[don't search certificates in message for signer]" \ + "-nosigs[don't verify message signature]" \ + "-noverify[don't verify signers certificate]" \ + "-nocerts[don't include signers certificate when signing]" \ + '-nodetach[use opaque signing]' \ + "-noattr[don't include any signed attributes]" \ + "-binary[don't translate message to text]" \ + '-certfile[other certificates file]:file:_files' \ + '-certsout[certificate output file]:file:_files' \ + '-signer[signer certificate file]:file:_files' \ + '-recip[recipient certificate file for decryption]:file:_files' \ + '-keyid[use subject key identifier]' \ + '-in[input file]:file:_files' \ + '-inform[input format SMIME (default), PEM or DER]:format:(SMIME PEM DER)' \ + '-inkey[input private key (if not signer or recipient)]:file:_files' \ + '-keyform[input private key format (PEM or ENGINE)]:format:(PEM ENGINE)' \ + '-out[output file]:file:_files' \ + '-outform[output format SMIME (default), PEM or DER]:format:(SMIME PEM DER)' \ + '-content[supply or override content for detached signature]:file:_files' \ + '-to[to address mail head]:address: ' \ + '-from[from address mail head]:address: ' \ + '-subject[subject mail head]:subject: ' \ + '-text[include or delete text MIME headers]' \ + '-CApath[trusted certificates directory]:dir:_files -/' \ + '-CAfile[trusted certificates file]:file:_files' \ + "-crl_check[check revocation status of signer's certificate using CRLs]" \ + "-crl_check_all[check revocation status of signer's certificate chain using CRLs]" \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-passin[input file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-rand[files to use for random number input]:file:_rand_files' \ + '*:certificate:_files' +} + + +_openssl_crl() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format - default PEM (DER or PEM)]:format:(PEM DER)' \ + '-outform[output format - default PEM]:format:(PEM DER)' \ + '-text[print out a text format version]' \ + '-in[input file - default stdin]:file:_files' \ + '-out[output file - default stdout]:file:_files' \ + '-hash[print hash value]' \ + '-hash_old[print old-style (MD5) hash value]' \ + '-fingerprint[print the crl fingerprint]' \ + '-issuer[print issuer DN]' \ + '-lastupdate[print lastUpdate field]' \ + '-nextupdate[print nextUpdate field]' \ + '-crlnumber[print CRL number]' \ + '-noout[no CRL output]' \ + '-CAfile[verify CRL using certificates in the specified file]:file:_files' \ + '-CApath[verify CRL using certificates in the specified directory]:dir:_files -/' \ + '*-nameopt[various certificate name options]:options:_nameopts' +} + + +_openssl_crl2pkcs7() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format - DER or PEM]:format:(PEM DER)' \ + '-outform[output format - DER or PEM]:format:(PEM DER)' \ + '-in[input file]:file:_files' \ + '-out[output file]:file:_files' \ + '-certfile[certificates file of chain to a trusted CA (can be used more than once)]:file:_files' \ + "-nocrl[no crl to load, just certs from '-certfile']" +} + + +_openssl_dgst() { + # written for openssl 1.0.1k + local digests + digests=(-dss1 -md4 -md5 -mdc2 -ripemd160 -sha -sha1 -sha224 -sha256 -sha384 -sha512 -whirlpool) + # -hmac is listed twice because it's documented twice by openssl + _arguments -C -A '-*' \ + '(-r -hex -binary)-c[to output the digest with separating colons]' \ + '(-c -hex -binary)-r[to output the digest in coreutils format]' \ + '-d[to output debug info]' \ + '(-c -r -binary)-hex[output as hex dump]' \ + '(-c -r -hex)-binary[output in binary form]' \ + '-hmac[set the HMAC key to arg]:key: ' \ + '-non-fips-allow[allow use of non FIPS digest]' \ + '-sign[sign digest using private key in the specified file]:file:_files' \ + '-verify[verify a signature using public key in the specified file]:file:_files' \ + '-prverify[verify a signature using private key in the specified file]:file:_files' \ + '-keyform[key file format (PEM or ENGINE)]:format:(PEM ENGINE)' \ + '-out[output to filename rather than stdout]:file:_files' \ + '-signature[signature to verify]:file:_files' \ + '-sigopt[signature parameter]:nm\:v: ' \ + '-hmac[create hashed MAC with key]:key: ' \ + '-mac[create MAC (not necessarily HMAC)]:algorithm: ' \ + '-macopt[MAC algorithm parameters or key]:nm\:v: ' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + "($digests)-dss1[use the dss1 message digest algorithm]" \ + "($digests)-md4[to use the md4 message digest algorithm]" \ + "($digests)-md5[to use the md5 message digest algorithm]" \ + "($digests)-mdc2[to use the mdc2 message digest algorithm]" \ + "($digests)-ripemd160[to use the ripemd160 message digest algorithm]" \ + "($digests)-sha[to use the sha message digest algorithm]" \ + "($digests)-sha1[to use the sha1 message digest algorithm]" \ + "($digests)-sha224[to use the sha224 message digest algorithm]" \ + "($digests)-sha256[to use the sha256 message digest algorithm]" \ + "($digests)-sha384[to use the sha384 message digest algorithm]" \ + "($digests)-sha512[to use the sha512 message digest algorithm]" \ + "($digests)-whirlpool[to use the whirlpool message digest algorithm]" \ + '*:file:_files' +} + + +_openssl_dh() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format]:format:(PEM DER)' \ + '-outform[output format]:format:(PEM DER)' \ + '-in[input file]:file:_files' \ + '-out[output file]:file:_files' \ + '-check[check the DH parameters]' \ + '-text[print a text form of the DH parameters]' \ + '-C[output C code]' \ + '-noout[no output]' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' +} + + +_openssl_dhparam() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format]:format:(PEM DER)' \ + '-outform[output format]:format:(PEM DER)' \ + '-in[input file]:file:_files' \ + '-out[output file]:file:_files' \ + '-dsaparam[read or generate DSA parameters, convert to DH]' \ + '-check[check the DH parameters]' \ + '-text[print a text form of the DH parameters]' \ + '-C[output C code]' \ + '-2[generate parameters using 2 as the generator value]' \ + '-5[generate parameters using 5 as the generator value]' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-rand[files to use for random number input]:file:_rand_files' \ + '-noout[no output]' \ + ':numbits: ' +} + + +_openssl_dsa() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format]:format:(PEM DER)' \ + '-outform[output format]:format:(PEM DER)' \ + '-in[input file]:file:_files' \ + '-passin[input file pass phrase source]:file:_files' \ + '-out[output file]:file:_files' \ + '-passout[output file pass phrase source]:file:_files' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-des[encrypt PEM output with cbc des]' \ + '-des3[encrypt PEM output with ede cbc des using 168 bit key]' \ + '-idea[encrypt PEM output with cbc idea]' \ + '-aes128[encrypt PEM output with cbc aes]' \ + '-aes192[encrypt PEM output with cbc aes]' \ + '-aes256[encrypt PEM output with cbc aes]' \ + '-camellia128[encrypt PEM output with cbc camellia]' \ + '-camellia192[encrypt PEM output with cbc camellia]' \ + '-camellia256[encrypt PEM output with cbc camellia]' \ + '-seed[encrypt PEM output with cbc seed]' \ + '-text[print the key in text]' \ + "-noout[don't print key out]" \ + '-modulus[print the DSA public value]' +} + + +_openssl_dsaparam() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format]:format:(PEM DER)' \ + '-outform[output format]:format:(PEM DER)' \ + '-in[input file]:file:_files' \ + '-out[output file]:file:_files' \ + '-text[print as text]' \ + '-C[output C code]' \ + '-noout[no output]' \ + '-genkey[generate a DSA key]' \ + '-rand[files to use for random number input]:file:_rand_files' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + ':numbits: ' +} + + +_openssl_ec() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format]:format:(PEM DER)' \ + '-outform[output format]:format:(PEM DER)' \ + '-in[input file]:file:_files' \ + '-passin[input file pass phrase source]:file:_files' \ + '-out[output file]:file:_files' \ + '-passout[output file pass phrase source]:file:_files' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + "-des[encrypt PEM output, instead of 'des' every other cipher supported by OpenSSL can be used]" \ + '-text[print the key]' \ + "-noout[don't print key out]" \ + '-param_out[print the elliptic curve parameters]' \ + '-conv_form[specifies the point conversion form]:form:(compressed uncompressed hybrid)' \ + '-param_enc[specifies the way the ec parameters are encoded in the asn1 der encoding]:encoding:(named_curve explicit)' +} + + +_openssl_ecparam() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format]:format:(PEM DER)' \ + '-outform[output format]:format:(PEM DER)' \ + '-in[input file - default stdin]:file:_files' \ + '-out[output file - default stdout]:file:_files' \ + '-noout[do not print the ec parameter]' \ + '-text[print the ec parameters in text form]' \ + '-check[validate the ec parameters]' \ + "-C[print a 'C' function creating the parameters]" \ + "-name[use the ec parameters with 'short name' name]:name: " \ + "-list_curves[prints a list of all currently available curve 'short names']" \ + '-conv_form[specifies the point conversion form]:form:(compressed uncompressed hybrid)' \ + '-param_enc[specifies the way the ec parameters are encoded in the asn1 der encoding]:encoding:(named_curve explicit)' \ + "-no_seed[if 'explicit' parameters are chosen do not use the seed]" \ + '-genkey[generate ec key]' \ + '-rand[files to use for random number input]:file:_rand_files' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' +} + + +_openssl_enc() { + # written for openssl 1.0.1k + local ciphers + ciphers=(-aes-128-cbc -aes-128-cbc-hmac-sha1 -aes-128-cfb -aes-128-cfb1 \ + -aes-128-cfb8 -aes-128-ctr -aes-128-ecb -aes-128-gcm -aes-128-ofb \ + -aes-128-xts -aes-192-cbc -aes-192-cfb -aes-192-cfb1 -aes-192-cfb8 \ + -aes-192-ctr -aes-192-ecb -aes-192-gcm -aes-192-ofb -aes-256-cbc \ + -aes-256-cbc-hmac-sha1 -aes-256-cfb -aes-256-cfb1 -aes-256-cfb8 \ + -aes-256-ctr -aes-256-ecb -aes-256-gcm -aes-256-ofb -aes-256-xts \ + -aes128 -aes192 -aes256 -bf -bf-cbc -bf-cfb -bf-ecb -bf-ofb \ + -blowfish -camellia-128-cbc -camellia-128-cfb -camellia-128-cfb1 \ + -camellia-128-cfb8 -camellia-128-ecb -camellia-128-ofb \ + -camellia-192-cbc -camellia-192-cfb -camellia-192-cfb1 \ + -camellia-192-cfb8 -camellia-192-ecb -camellia-192-ofb \ + -camellia-256-cbc -camellia-256-cfb -camellia-256-cfb1 \ + -camellia-256-cfb8 -camellia-256-ecb -camellia-256-ofb \ + -camellia128 -camellia192 -camellia256 -cast -cast-cbc -cast5-cbc \ + -cast5-cfb -cast5-ecb -cast5-ofb -des -des-cbc -des-cfb -des-cfb1 \ + -des-cfb8 -des-ecb -des-ede -des-ede-cbc -des-ede-cfb -des-ede-ofb \ + -des-ede3 -des-ede3-cbc -des-ede3-cfb -des-ede3-cfb1 \ + -des-ede3-cfb8 -des-ede3-ofb -des-ofb -des3 -desx -desx-cbc \ + -id-aes128-GCM -id-aes192-GCM -id-aes256-GCM -idea -idea-cbc \ + -idea-cfb -idea-ecb -idea-ofb -rc2 -rc2-40-cbc -rc2-64-cbc \ + -rc2-cbc -rc2-cfb -rc2-ecb -rc2-ofb -rc4 -rc4-40 -rc4-hmac-md5 \ + -rc5 -rc5-cbc -rc5-cfb -rc5-ecb -rc5-ofb -seed -seed-cbc -seed-cfb \ + -seed-ecb -seed-ofb) + _arguments -C \ + '-in[input file]:file:_files' \ + '-out[output file]:file:_files' \ + '-pass[pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-e[encrypt]' \ + '-d[decrypt]' \ + '(-a -base64)'{-a,-base64}'[base64 encode/decode, depending on encryption flag]' \ + '-k[the password to derive the key from]:password: ' \ + '-kfile[read the password to derive the key from the first line of the file]:file:_files' \ + '-md[the md to use to create a key from a passphrase]:alg:(md2 md5 sha sha1)' \ + '-S[the actual salt to use]:salt: ' \ + '-K[the actual key to use]:key: ' \ + '-iv[the actual IV to use]:IV: ' \ + '-p[print out the key and IV used]' \ + '-P[print out the key and IV used the exit]' \ + '-bufsize[set the buffer size for I/O]:size: ' \ + '-nopad[disable standard block padding]' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + "(${ciphers})-aes-128-cbc[cipher types]" \ + "(${ciphers})-aes-128-cbc-hmac-sha1[cipher types]" \ + "(${ciphers})-aes-128-cfb[cipher types]" \ + "(${ciphers})-aes-128-cfb1[cipher types]" \ + "(${ciphers})-aes-128-cfb8[cipher types]" \ + "(${ciphers})-aes-128-ctr[cipher types]" \ + "(${ciphers})-aes-128-ecb[cipher types]" \ + "(${ciphers})-aes-128-gcm[cipher types]" \ + "(${ciphers})-aes-128-ofb[cipher types]" \ + "(${ciphers})-aes-128-xts[cipher types]" \ + "(${ciphers})-aes-192-cbc[cipher types]" \ + "(${ciphers})-aes-192-cfb[cipher types]" \ + "(${ciphers})-aes-192-cfb1[cipher types]" \ + "(${ciphers})-aes-192-cfb8[cipher types]" \ + "(${ciphers})-aes-192-ctr[cipher types]" \ + "(${ciphers})-aes-192-ecb[cipher types]" \ + "(${ciphers})-aes-192-gcm[cipher types]" \ + "(${ciphers})-aes-192-ofb[cipher types]" \ + "(${ciphers})-aes-256-cbc[cipher types]" \ + "(${ciphers})-aes-256-cbc-hmac-sha1[cipher types]" \ + "(${ciphers})-aes-256-cfb[cipher types]" \ + "(${ciphers})-aes-256-cfb1[cipher types]" \ + "(${ciphers})-aes-256-cfb8[cipher types]" \ + "(${ciphers})-aes-256-ctr[cipher types]" \ + "(${ciphers})-aes-256-ecb[cipher types]" \ + "(${ciphers})-aes-256-gcm[cipher types]" \ + "(${ciphers})-aes-256-ofb[cipher types]" \ + "(${ciphers})-aes-256-xts[cipher types]" \ + "(${ciphers})-aes128[cipher types]" \ + "(${ciphers})-aes192[cipher types]" \ + "(${ciphers})-aes256[cipher types]" \ + "(${ciphers})-bf[cipher types]" \ + "(${ciphers})-bf-cbc[cipher types]" \ + "(${ciphers})-bf-cfb[cipher types]" \ + "(${ciphers})-bf-ecb[cipher types]" \ + "(${ciphers})-bf-ofb[cipher types]" \ + "(${ciphers})-blowfish[cipher types]" \ + "(${ciphers})-camellia-128-cbc[cipher types]" \ + "(${ciphers})-camellia-128-cfb[cipher types]" \ + "(${ciphers})-camellia-128-cfb1[cipher types]" \ + "(${ciphers})-camellia-128-cfb8[cipher types]" \ + "(${ciphers})-camellia-128-ecb[cipher types]" \ + "(${ciphers})-camellia-128-ofb[cipher types]" \ + "(${ciphers})-camellia-192-cbc[cipher types]" \ + "(${ciphers})-camellia-192-cfb[cipher types]" \ + "(${ciphers})-camellia-192-cfb1[cipher types]" \ + "(${ciphers})-camellia-192-cfb8[cipher types]" \ + "(${ciphers})-camellia-192-ecb[cipher types]" \ + "(${ciphers})-camellia-192-ofb[cipher types]" \ + "(${ciphers})-camellia-256-cbc[cipher types]" \ + "(${ciphers})-camellia-256-cfb[cipher types]" \ + "(${ciphers})-camellia-256-cfb1[cipher types]" \ + "(${ciphers})-camellia-256-cfb8[cipher types]" \ + "(${ciphers})-camellia-256-ecb[cipher types]" \ + "(${ciphers})-camellia-256-ofb[cipher types]" \ + "(${ciphers})-camellia128[cipher types]" \ + "(${ciphers})-camellia192[cipher types]" \ + "(${ciphers})-camellia256[cipher types]" \ + "(${ciphers})-cast[cipher types]" \ + "(${ciphers})-cast-cbc[cipher types]" \ + "(${ciphers})-cast5-cbc[cipher types]" \ + "(${ciphers})-cast5-cfb[cipher types]" \ + "(${ciphers})-cast5-ecb[cipher types]" \ + "(${ciphers})-cast5-ofb[cipher types]" \ + "(${ciphers})-des[cipher types]" \ + "(${ciphers})-des-cbc[cipher types]" \ + "(${ciphers})-des-cfb[cipher types]" \ + "(${ciphers})-des-cfb1[cipher types]" \ + "(${ciphers})-des-cfb8[cipher types]" \ + "(${ciphers})-des-ecb[cipher types]" \ + "(${ciphers})-des-ede[cipher types]" \ + "(${ciphers})-des-ede-cbc[cipher types]" \ + "(${ciphers})-des-ede-cfb[cipher types]" \ + "(${ciphers})-des-ede-ofb[cipher types]" \ + "(${ciphers})-des-ede3[cipher types]" \ + "(${ciphers})-des-ede3-cbc[cipher types]" \ + "(${ciphers})-des-ede3-cfb[cipher types]" \ + "(${ciphers})-des-ede3-cfb1[cipher types]" \ + "(${ciphers})-des-ede3-cfb8[cipher types]" \ + "(${ciphers})-des-ede3-ofb[cipher types]" \ + "(${ciphers})-des-ofb[cipher types]" \ + "(${ciphers})-des3[cipher types]" \ + "(${ciphers})-desx[cipher types]" \ + "(${ciphers})-desx-cbc[cipher types]" \ + "(${ciphers})-id-aes128-GCM[cipher types]" \ + "(${ciphers})-id-aes192-GCM[cipher types]" \ + "(${ciphers})-id-aes256-GCM[cipher types]" \ + "(${ciphers})-idea[cipher types]" \ + "(${ciphers})-idea-cbc[cipher types]" \ + "(${ciphers})-idea-cfb[cipher types]" \ + "(${ciphers})-idea-ecb[cipher types]" \ + "(${ciphers})-idea-ofb[cipher types]" \ + "(${ciphers})-rc2[cipher types]" \ + "(${ciphers})-rc2-40-cbc[cipher types]" \ + "(${ciphers})-rc2-64-cbc[cipher types]" \ + "(${ciphers})-rc2-cbc[cipher types]" \ + "(${ciphers})-rc2-cfb[cipher types]" \ + "(${ciphers})-rc2-ecb[cipher types]" \ + "(${ciphers})-rc2-ofb[cipher types]" \ + "(${ciphers})-rc4[cipher types]" \ + "(${ciphers})-rc4-40[cipher types]" \ + "(${ciphers})-rc4-hmac-md5[cipher types]" \ + "(${ciphers})-rc5[cipher types]" \ + "(${ciphers})-rc5-cbc[cipher types]" \ + "(${ciphers})-rc5-cfb[cipher types]" \ + "(${ciphers})-rc5-ecb[cipher types]" \ + "(${ciphers})-rc5-ofb[cipher types]" \ + "(${ciphers})-seed[cipher types]" \ + "(${ciphers})-seed-cbc[cipher types]" \ + "(${ciphers})-seed-cfb[cipher types]" \ + "(${ciphers})-seed-ecb[cipher types]" \ + "(${ciphers})-seed-ofb[cipher types]" +} + + +_openssl_engine() { + # written for openssl 1.0.1k + _arguments -C \ + '(-vv -vvv -vvvv)-v[verbose mode, for each engine, list its "control commands"]' \ + "(-v -vvv -vvvv)-vv[like -v, but additionally display each command's description]" \ + '(-v -vv -vvvv)-vvv[like -vv, but also add the input flags for each command]' \ + '(-v -vv -vvv)-vvvv[like -vvv, but also show internal input flags]' \ + '-c[for each engine, also list the capabilities]' \ + '(-tt)-t[for each engine, check that they are really available]' \ + '(-t)-tt[display error trace for unavailable engines]' \ + "-pre[runs command 'cmd' against the ENGINE before any attempts to load it (if -t is used)]:cmd: " \ + "-post[runs command 'cmd' against the ENGINE after loading it (only used if -t is also provided)]:cmd: " \ + '*:engine:_engines' + # TODO: can cmd (for -pre and -post) be completed? +} + + +_openssl_errstr() { + # written for openssl 1.0.1k + # written for openssl 1.0.2a + _arguments -C \ + '-stats' \ + ':errno: ' +} + + +_openssl_gendh() { + # written for openssl 1.0.1k + _arguments -C \ + "-out[output the key to 'file']:file:_files" \ + '-2[use 2 as the generator value]' \ + '-5[use 5 as the generator value]' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-rand[files to use for random number input]:file:_rand_files' \ + ':numbits: ' +} + + +_openssl_gendsa() { + # written for openssl 1.0.1k + _arguments -C \ + "-out[output the key to 'file']:file:_files" \ + '-des[encrypt the generated key with DES in cbc mode]' \ + '-des3[encrypt the generated key with DES in ede cbc mode (168 bit key)]' \ + '-idea[encrypt the generated key with IDEA in cbc mode]' \ + '-seed[encrypt PEM output with cbc seed]' \ + '-aes128[encrypt PEM output with cbc aes]' \ + '-aes192[encrypt PEM output with cbc aes]' \ + '-aes256[encrypt PEM output with cbc aes]' \ + '-camellia128[encrypt PEM output with cbc camellia]' \ + '-camellia192[encrypt PEM output with cbc camellia]' \ + '-camellia256[encrypt PEM output with cbc camellia]' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-rand[files to use for random number input]:file:_rand_files' \ + ':dsaparam-file:_files' +} + + +_openssl_genpkey() { + # written for openssl 1.0.1k + local ciphers cipher_opts + if ! ciphers=( ${$(openssl list-cipher-algorithms | cut -d' ' -f1)} ) 2>/dev/null ; then + ciphers=( ${$(openssl list -cipher-algorithms | cut -d' ' -f1)} ) + fi + cipher_opts=() + for alg in ${ciphers}; do + cipher_opts=(${cipher_opts} "(${${(l:32:: ::-:)ciphers[@]}// / })-${alg}[use this cipher to encrypt the key]") + done + _arguments -C \ + '-out[output file]:file:_files' \ + '-outform[output format]:format:(PEM DER)' \ + '-pass[output file pass phrase source]:pass phrase source:_pass_phrase_source' \ + $cipher_opts \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '(-algorithm)-paramfile[parameters file]:file:_files' \ + '(-paramfile)-algorithm[the public key algorithm]:algorithm:(EC RSA DSA DH)' \ + '-pkeyopt[public key options]:option\:value: ' \ + '-genparam[generate parameters, not key]' \ + '-text[print the in text]' + # NB: options order may be important! See the manual page. + # TODO: complete pkeyopts + # However: "The precise set of options supported depends on the public key + # algorithm used and its implementation." +} + + +_openssl_genrsa() { + # written for openssl 1.0.1k + _arguments -C \ + '-des[encrypt the generated key with DES in cbc mode]' \ + '-des3[encrypt the generated key with DES in ede cbc mode (168 bit key)]' \ + '-idea[encrypt the generated key with IDEA in cbc mode]' \ + '-seed[encrypt PEM output with cbc seed]' \ + '-aes128[encrypt PEM output with cbc aes]' \ + '-aes192[encrypt PEM output with cbc aes]' \ + '-aes256[encrypt PEM output with cbc aes]' \ + '-camellia128[encrypt PEM output with cbc camellia]' \ + '-camellia192[encrypt PEM output with cbc camellia]' \ + '-camellia256[encrypt PEM output with cbc camellia]' \ + '-out[output the key to file]:file:_files' \ + '-passout[output file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-f4[use F4 (0x10001) for the E value]' \ + '-3[use 3 for the E value]' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-rand[files to use for random number input]:file:_rand_files' \ + ':numbits: ' +} + + +_openssl_nseq() { + # written for openssl 1.0.1k + _arguments -C \ + '-in[input file]:file:_files' \ + '-out[output file]:file:_files' \ + '-toseq[output NS Sequence file]' +} + + +_openssl_ocsp() { + # written for openssl 1.0.1k + _arguments -C \ + '-out[output filename]:file:_files' \ + '-issuer[issuer certificate]:file:_files' \ + '-cert[certificate to check]:file:_files' \ + '-serial[serial number to check]:serial: ' \ + '-signer[certificate to sign OCSP request with]:file:_files' \ + '-signkey[private key to sign OCSP request with]:file:_files' \ + '-sign_other[additional certificates to include in signed request]:file:_files' \ + "-no_certs[don't include any certificates in signed request]" \ + '-req_text[print text form of request]' \ + '-resp_text[print text form of response]' \ + '-text[print text form of request and response]' \ + '-reqout[write DER encoded OCSP request to "file"]:file:_files' \ + '-respout[write DER encoded OCSP response to "file"]:file:_files' \ + '-reqin[read DER encoded OCSP request from "file"]:file:_files' \ + '-respin[read DER encoded OCSP response from "file"]:file:_files' \ + '-nonce[add OCSP nonce to request]' \ + "-no_nonce[don't add OCSP nonce to request]" \ + '-url[OCSP responder URL]:URL: ' \ + '-host[send OCSP request to given host on given port]:host\:port: ' \ + '-path[path to use in OCSP request]' \ + '-CApath[trusted certificates directory]:directory:_files -/' \ + '-CAfile[trusted certificates file]:file:_files' \ + '-VAfile[validator certificates file]:file:_files' \ + '-validity_period[maximum validity discrepancy in seconds]:seconds: ' \ + '-status_age[maximum status age in seconds]:seconds: ' \ + "-noverify[don't verify response at all]" \ + '-verify_other[additional certificates to search for signer]:file:_files' \ + "-trust_other[don't verify additional certificates]" \ + "-no_intern[don't search certificates contained in response for signer]" \ + "-no_signature_verify[don't check signature on response]" \ + "-no_cert_verify[don't check signing certificate]" \ + "-no_chain[don't chain verify response]" \ + "-no_cert_checks[don't do additional checks on signing certificate]" \ + '-port[port to run responder on]:port: ' \ + '-index[certificate status index file]:file:_files' \ + '-CA[CA certificate]:file:_files' \ + '-rsigner[responder certificate to sign responses with]:file:_files' \ + '-rkey[responder key to sign responses with]:file:_files' \ + '-rother[other certificates to include in response]:file:_files' \ + "-resp_no_certs[don't include any certificates in response]" \ + '-nmin[number of minutes before next update]:minutes: ' \ + '-ndays[number of days before next update]:days: ' \ + '-resp_key_id[identify response by signing certificate key ID]' \ + '-nrequest[number of requests to accept (default unlimited)]:limit: ' \ + '-dss1[use specified digest in the request]' \ + '-md4[use specified digest in the request]' \ + '-md5[use specified digest in the request]' \ + '-mdc2[use specified digest in the request]' \ + '-ripemd160[use specified digest in the request]' \ + '-ripemd[use specified digest in the request]' \ + '-rmd160[use specified digest in the request]' \ + '-sha1[use specified digest in the request]' \ + '-sha224[use specified digest in the request]' \ + '-sha256[use specified digest in the request]' \ + '-sha384[use specified digest in the request]' \ + '-sha512[use specified digest in the request]' \ + '-sha[use specified digest in the request]' \ + '-ssl2-md5[use specified digest in the request]' \ + '-ssl3-md5[use specified digest in the request]' \ + '-ssl3-sha1[use specified digest in the request]' \ + '-whirlpool[use specified digest in the request]' \ + '-timeout[timeout connection to OCSP responder after n seconds]:seconds: ' +} + + +_openssl_passwd() { + # written for openssl 1.0.1k + _arguments -C \ + '-crypt[standard Unix password algorithm (default)]' \ + '-1[MD5-based password algorithm]' \ + '-apr1[MD5-based password algorithm, Apache variant]' \ + '-salt[use provided salt]:salt: ' \ + '-in[read passwords from file]:file:_files' \ + '-stdin[read passwords from stdin]' \ + '-noverify[never verify when reading password from terminal]' \ + '-quiet[no warnings]' \ + '-table[format output as table]' \ + '-reverse[switch table columns]' \ + '*:password:' +} + + +_openssl_pkcs12() { + # written for openssl 1.0.2d + local algorithms + algorithms=(aes-128-cbc aes-128-ecb aes-192-cbc aes-192-ecb aes-256-cbc \ + aes-256-ecb bf-cbc bf-cfb bf-ecb bf-ofb camellia-128-cbc \ + camellia-128-ecb camellia-192-cbc camellia-192-ecb \ + camellia-256-cbc camellia-256-ecb cast-cbc cast5-cbc cast5-cfb \ + cast5-ecb cast5-ofb des-cbc des-cfb des-ecb des-ede des-ede-cbc \ + des-ede-cfb des-ede-ofb des-ede3 des-ede3-cbc des-ede3-cfb \ + des-ede3-ofb des-ofb idea-cbc idea-cfb idea-ecb idea-ofb \ + rc2-40-cbc rc2-64-cbc rc2-cbc rc2-cfb rc2-ecb rc2-ofb rc4 \ + rc4-40 rc5-cbc rc5-cfb rc5-ecb rc5-ofb seed-cbc seed-cfb \ + seed-ecb seed-ofb PBE-MD2-DES PBE-MD5-DES PBE-SHA1-RC2-64 \ + PBE-MD2-RC2-64 PBE-MD5-RC2-64 PBE-SHA1-DES PBE-SHA1-RC4-128 \ + PBE-SHA1-RC4-40 PBE-SHA1-3DES PBE-SHA1-2DES PBE-SHA1-RC2-128 \ + PBE-SHA1-RC2-40) + _arguments -C \ + '-export[output PKCS12 file]' \ + '-chain[add certificate chain]' \ + '-inkey[private key if not infile]:file:_files' \ + '-certfile[add all certs in the specified file]:file:_files' \ + "-CApath[PEM format directory of CA's]:file:_files" \ + "-CAfile[PEM format file of CA's]:file:_files" \ + '-name[use specified friendly name]:name: ' \ + '*-caname[use specified CA friendly name]:name: ' \ + '-in[input filename]:file:_files' \ + '-out[output filename]:file:_files' \ + "-noout[don't output anything, just verify]" \ + "-nomacver[don't verify MAC]" \ + "-nocerts[don't output certificates]" \ + '-clcerts[only output client certificates]' \ + '-cacerts[only output CA certificates]' \ + "-nokeys[don't output private keys]" \ + '-info[give info about PKCS#12 structure]' \ + '-des[encrypt private keys with DES]' \ + '-des3[encrypt private keys with triple DES (default)]' \ + '-idea[encrypt private keys with idea]' \ + '-seed[encrypt private keys with seed]' \ + '-aes128[encrypt PEM output with cbc aes]' \ + '-aes192[encrypt PEM output with cbc aes]' \ + '-aes256[encrypt PEM output with cbc aes]' \ + '-camellia128[encrypt PEM output with cbc camellia]' \ + '-camellia192[encrypt PEM output with cbc camellia]' \ + '-camellia256[encrypt PEM output with cbc camellia]' \ + "-nodes[don't encrypt private keys]" \ + "-noiter[don't use encryption iteration]" \ + "-nomaciter[don't use MAC iteration]" \ + '-maciter[use MAC iteration]' \ + "-nomac[don't generate MAC]" \ + '-twopass[separate MAC, encryption passwords]' \ + '-descert[encrypt PKCS#12 certificates with triple DES (default RC2-40)]' \ + "-certpbe[specify certificate PBE algorithm (default RC2-40)]:alg:(${algorithms})" \ + '-keypbe[specify private key PBE algorithm (default 3DES)]:alg:(${algorithms})' \ + '-macalg[digest algorithm used in MAC (default SHA1)]:alg:_list_message_digest_algorithms' \ + '-keyex[set MS key exchange type]' \ + '-keysig[set MS key signature type]' \ + '-password[set import/export password source]:pass phrase source:_pass_phrase_source' \ + '-passin[input file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-passout[output file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-rand[files to use for random number input]:file:_rand_files' \ + '-CSP[Microsoft CSP name]:name: ' \ + '-LMK[add local machine keyset attribute to private key]' +} + + +_openssl_pkcs7() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format]:format:(PEM DER)' \ + '-outform[output format]:format:(PEM DER)' \ + '-in[input file]:file:_files' \ + '-out[output file]:file:_files' \ + '-print_certs[print any certs or crl in the input]' \ + '-text[print full details of certificates]' \ + "-noout[don't output encoded data]" \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' +} + + +_openssl_pkcs8() { + # written for openssl 1.0.2d + _arguments -C \ + '-in[input file]:file:_files' \ + '-inform[input format]:format:(PEM DER)' \ + '-passin[input file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-outform[output format]:format:(PEM DER)' \ + '-out[output file]:file:_files' \ + '-passout[output file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-topk8[output PKCS8 file]' \ + '-nooct[use (nonstandard) no octet format]' \ + '-embed[use (nonstandard) embedded DSA parameters format]' \ + '-nsdb[use (nonstandard) DSA Netscape DB format]' \ + '-noiter[use 1 as iteration count]' \ + '-nocrypt[use or expect unencrypted private key]' \ + '-v2[use PKCS#5 v2.0 and given cipher]:alg:(aes-128-cbc aes-128-ecb aes-192-cbc aes-192-ecb aes-256-cbc aes-256-ecb bf bf-cbc bf-cfb bf-ecb bf-ofb camellia-128-cbc camellia-128-ecb camellia-192-cbc camellia-192-ecb camellia-256-cbc camellia-256-ecb cast cast-cbc cast5-cbc cast5-cfb cast5-ecb cast5-ofb des des-cbc des-cfb des-ecb des-ede des-ede-cbc des-ede-cfb des-ede-ofb des-ede3 des-ede3-cbc des-ede3-cfb des-ede3-ofb des-ofb des3 desx idea idea-cbc idea-cfb idea-ecb idea-ofb rc2 rc2-40-cbc rc2-64-cbc rc2-cbc rc2-cfb rc2-ecb rc2-ofb rc4 rc4-40 rc5 rc5-cbc rc5-cfb rc5-ecb rc5-ofb seed seed-cbc seed-cfb seed-ecb seed-ofb)' \ + '-v2prf[set the PRF algorithm to use with PKCS#5 v2.0]:alg:(hmacWithMD5 hmacWithRMD160 hmacWithSHA1 hmacWithSHA224 hmacWithSHA256 hmacWithSHA384 hmacWithSHA512)' \ + '-v1[use PKCS#5 v1.5 and given cipher]:obj:(PBE-MD2-DES PBE-MD5-DES PBE-SHA1-RC2-64 PBE-MD2-RC2-64 PBE-MD5-RC2-64 PBE-SHA1-DES PBE-SHA1-RC4-128 PBE-SHA1-RC4-40 PBE-SHA1-3DES PBE-SHA1-2DES PBE-SHA1-RC2-128 PBE-SHA1-RC2-40)' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' +} + + +_openssl_pkey() { + # written for openssl 1.0.1k + _arguments -C \ + '-in[input file]:file:_files' \ + '-inform[input format]:format:(PEM DER)' \ + '-passin[input file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-outform[output format]:format:(PEM DER)' \ + '-out[output file]:file:_files' \ + '-passout[output file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' +} + + +_openssl_pkeyparam() { + # written for openssl 1.0.1k + _arguments -C \ + '-in[the input filename to read parameters from]:file:_files' \ + '-out[the output filename to write parameters]:file:_files' \ + '-text[prints out the parameters in plain text in addition to the encoded version]' \ + '-noout[do not output the encoded version of the parameters]' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' +} + + +_openssl_pkeyutl() { + # written for openssl 1.0.1k + _arguments -C \ + '-in[input file]:file:_files' \ + '-out[output file]:file:_files' \ + '-sigfile[signature file (verify operation only)]:file:_files' \ + '-inkey[input key]:file:_files' \ + '-keyform[private key format]:format:(PEM DER)' \ + '-pubin[input is a public key]' \ + '-certin[input is a certificate carrying a public key]' \ + '-pkeyopt[public key options]:option\:value:_pkeyopts' \ + '-sign[sign with private key]' \ + '-verify[verify with public key]' \ + '-verifyrecover[verify with public key, recover original data]' \ + '-encrypt[encrypt with public key]' \ + '-decrypt[decrypt with private key]' \ + '-derive[derive shared secret]' \ + '-hexdump[hex dump output]' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-passin[pass phrase source]:pass phrase source:_pass_phrase_source' +} + + +_openssl_prime() { + # written for openssl 1.0.1k + _arguments -C \ + '-hex[hex]' \ + '-checks[number of checks]:checks: ' \ + ':number:' +} + + +_openssl_rand() { + # written for openssl 1.0.1k + _arguments -C \ + '-out[write to file]:file:_files' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-rand[files to use for random number input]:file:_rand_files' \ + '-base64[base64 encode output]' \ + '-hex[hex encode output]' \ + ':num:' +} + + +_openssl_req() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format]:format:(PEM DER)' \ + '-outform[output format]:format:(PEM DER)' \ + '-in[input file]:file:_files' \ + '-out[output file]:file:_files' \ + '-text[text form of request]' \ + '-pubkey[output public key]' \ + '-noout[do not output REQ]' \ + '-verify[verify signature on REQ]' \ + '-modulus[RSA modulus]' \ + "-nodes[don't encrypt the output key]" \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + "-subject[output the request's subject]" \ + '-passin[private key pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-key[use the private key contained in the specified file]:file:_files' \ + '-keyform[key file format]:format:(PEM DER)' \ + '-keyout[file to send the key to]:file:_files' \ + '-rand[files to use for random number input]:file:_rand_files' \ + "-newkey rsa\:-[generate a new RSA key of the specified number of bits in size]:bits: " \ + "-newkey dsa\:[generate a new DSA key, parameters taken from CA in the specified file]:file:_files" \ + "-newkey ec\:[generate a new EC key, parameters taken from CA in the specified file]:file:_files" \ + '-md2[digest to sign with]' \ + '-md4[digest to sign with]' \ + '-md5[digest to sign with]' \ + '-mdc2[digest to sign with]' \ + '-sha1[digest to sign with]' \ + '-config[request template file]:file:_files' \ + '-subj[set or modify request subject]:subject: ' \ + '-multivalue-rdn[enable support for multivalued RDNs]' \ + '-new[new request]' \ + '-batch[do not ask anything during request generation]' \ + '-x509[output a x509 structure instead of a certificate request]' \ + '-days[number of days a certificate generated by -x509 is valid for]:days: ' \ + '-set_serial[serial number to use for a certificate generated by -x509]:serial: ' \ + '-newhdr[output "NEW" in the header lines]' \ + "-asn1-kludge[output the 'request' in a format that is wrong but some CA's have been reported as requiring]" \ + '-extensions[specify certificate extension section (override value in config file)]:section: ' \ + '-reqexts[specify request extension section (override value in config file)]:section: ' \ + '-utf8[input characters are UTF8 (default ASCII)]' \ + '*-nameopt[various certificate name options]:options:_nameopts' \ + '*-reqopt[- various request text options]:options:_certopts' + # TODO: complete -extensions and -reqexts +} + + +_openssl_rsa() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format]:format:(PEM DER NET)' \ + '-outform[output format]:format:(PEM DER NET)' \ + '-in[input file]:file:_files' \ + '-sgckey[use IIS SGC key format]' \ + '-passin[input file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-out[output file]:file:_files' \ + '-passout[output file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-des[encrypt PEM output with cbc des]' \ + '-des3[encrypt PEM output with ede cbc des using 168 bit key]' \ + '-idea[encrypt PEM output with cbc idea]' \ + '-seed[encrypt PEM output with cbc seed]' \ + '-aes128[encrypt PEM output with cbc aes]' \ + '-aes192[encrypt PEM output with cbc aes]' \ + '-aes256[encrypt PEM output with cbc aes]' \ + '-camellia128[encrypt PEM output with cbc camellia]' \ + '-camellia192[encrypt PEM output with cbc camellia]' \ + '-camellia256[encrypt PEM output with cbc camellia]' \ + '-text[print the key in text]' \ + "-noout[don't print key out]" \ + '-modulus[print the RSA key modulus]' \ + '-check[verify key consistency]' \ + '-pubin[expect a public key in input file]' \ + '-pubout[output a public key]' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' +} + + +_openssl_rsautl() { + # written for openssl 1.0.1k + _arguments -C \ + '-in[input file]:file:_files' \ + '-out[output file]:file:_files' \ + '-inkey[input key]:file:_files' \ + '-keyform[private key format]:format:(PEM DER)' \ + '-pubin[input is an RSA public]' \ + '-certin[input is a certificate carrying an RSA public key]' \ + '-ssl[use SSL v2 padding]' \ + '-raw[use no padding]' \ + '-pkcs[use PKCS#1 v1.5 padding (default)]' \ + '-oaep[use PKCS#1 OAEP]' \ + '-sign[sign with private key]' \ + '-verify[verify with public key]' \ + '-encrypt[encrypt with public key]' \ + '-decrypt[decrypt with private key]' \ + '-hexdump[hex dump output]' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-passin[pass phrase source]:pass phrase source:_pass_phrase_source' +} + + +_openssl_s_client() { + # written for openssl 1.0.1k + _arguments -C \ + '(-6)-4[use IPv4 only]' \ + '(-4)-6[use IPv6 only]' \ + '(-connect)-host[use -connect instead]:host: ' \ + '(-connect)-port[use -connect instead]:port: ' \ + '(-host -port)-connect[who to connect to (default is localhost:4433)]:host\:port: ' \ + '-verify[turn on peer certificate verification]:depth: ' \ + '-verify_return_error[return verification errors]' \ + '-cert[certificate file to use, PEM format assumed]:file:_files' \ + '-certform[certificate format (PEM or DER) PEM default]:format:(PEM DER)' \ + '-key[private key file to use, in cert file if not specified but cert file is]:file:_files' \ + '-keyform[key format (PEM or DER) PEM default]:format:(PEM DER)' \ + '-pass[private key file pass phrase source]:pass phrase source:_pass_phrase_source' \ + "-CApath[PEM format directory of CA's]:directory:_files -/" \ + "-CAfile[PEM format file of CA's]:file:_files" \ + '-reconnect[drop and re-make the connection with the same Session-ID]' \ + '-pause[sleep(1) after each read(2) and write(2) system call]' \ + '-prexit[print session information even on connection failure]' \ + '-showcerts[show all certificates in the chain]' \ + '-debug[extra output]' \ + '-msg[show protocol messages]' \ + '-nbio_test[more ssl protocol testing]' \ + "-state[print the 'ssl' states]" \ + '-nbio[run with non-blocking IO]' \ + '-crlf[convert LF from terminal into CRLF]' \ + '-quiet[no s_client output]' \ + '(-no_ign_eof)-ign_eof[ignore input eof (default when -quiet)]' \ + "(-ign_eof)-no_ign_eof[don't ignore input eof]" \ + '-psk_identity[PSK identity]:identity: ' \ + '-psk[PSK in hex (without 0x)]:key: ' \ + "-srpuser[SRP authentication for 'user']:user: " \ + "-srppass[password for 'user']:password: " \ + '-srp_lateuser[SRP username into second ClientHello message]' \ + '-srp_moregroups[tolerate other than the known g N values]' \ + '-srp_strength[minimal length in bits for N (default 1024)]:int: ' \ + '(-no_ssl2 -ssl3 -tls1 -tls1_1 -tls1_2 -dtls1)-ssl2[just use SSLv2]' \ + '(-no_ssl3 -ssl2 -tls1 -tls1_1 -tls1_2 -dtls1)-ssl3[just use SSLv3]' \ + '(-no_tls1_2 -ssl2 -ssl3 -tls1 -tls1_1 -dtls1)-tls1_2[just use TLSv1.2]' \ + '(-no_tls1_1 -ssl2 -ssl3 -tls1 -tls1_1 -dtls1)-tls1_1[just use TLSv1.1]' \ + '(-no_tls1 -ssl2 -ssl3 -tls1 -tls1_1 -dtls1)-tls1[just use TLSv1.0]' \ + '(-no_dtls1 -ssl2 -ssl3 -tls1 -tls1_1 -tls1_2)-dtls1[just use DTLSv1]' \ + '-fallback_scsv[send TLS_FALLBACK_SCSV]' \ + '-mtu[set the link layer MTU]' \ + '(-tls1_2)-no_tls1_2[turn off TLSv1.2]' \ + '(-tls1_1)-no_tls1_1[turn off TLSv1.1]' \ + '(-tls1)-no_tls1[turn off TLSv1.0]' \ + '(-ssl3)-no_ssl3[turn off SSLv3]' \ + '(-ssl2)-no_ssl2[turn off SSLv2]' \ + '-bugs[switch on all SSL implementation bug workarounds]' \ + "-serverpref[use server's cipher preferences (only SSLv2)]" \ + '-cipher[preferred cipher to use]:cipher suite:_list_ciphers' \ + "-starttls[use the STARTTLS command before starting TLS for those protocols that support it]:protocol:(smtp pop3 imap ftp xmpp)" \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-rand[files to use for random number input]:file:_rand_files' \ + '-sess_out[file to write SSL session to]:file:_files' \ + '-sess_in[file to read SSL session from]:file:_files' \ + '-servername[set TLS extension servername in ClientHello]:host: ' \ + '-tlsextdebug[hex dump of all TLS extensions received]' \ + '-status[request certificate status from server]' \ + '-no_ticket[disable use of RFC4507bis session tickets]' \ + '-nextprotoneg[enable NPN extension, considering named protocols supported (comma-separated list)]:protocols: ' \ + '-legacy_renegotiation[enable use of legacy renegotiation (dangerous)]' \ + '-use_srtp[offer SRTP key management with a colon-separated profile list]:profiles: ' \ + '-keymatexport[export keying material using label]:label: ' \ + '-keymatexportlen[export len bytes of keying material (default 20)]:len: ' +} + + +_openssl_s_server() { + # written for openssl 1.0.1k + _arguments -C \ + '-accept[port to accept on (default is 4433)]:port: ' \ + '-context[set session ID context]:id: ' \ + '-verify[turn on peer certificate verification]:depth: ' \ + '-Verify[turn on peer certificate verification, must have a cert]:depth: ' \ + '-verify_return_error[return verification errors]' \ + '-cert[certificate file to use (default is server.pem)]:file:_files' \ + '-crl_check[check the peer certificate has not been revoked by its CA]' \ + '-crl_check_all[check the peer certificate has not been revoked by its CA or any other CRL in the CA chain]' \ + '-certform[certificate format]:format:(PEM DER)' \ + '-key[Private Key file to use, in cert file if not specified (default is server.pem)]:file:_files' \ + '-keyform[key format]:format:(PEM DER ENGINE)' \ + '-pass[private key file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-dcert[second certificate file to use (usually for DSA)]:file:_files' \ + '-dcertform[second certificate format]:format:(PEM DER)' \ + '-dkey[second private key file to use (usually for DSA)]:file:_files' \ + '-dkeyform[second key format]:format:(PEM DER ENGINE)' \ + '-dpass[second private key file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-dhparam[DH parameter file to use, in cert file if not specified or a default set of parameters is used]:file:_files' \ + '-named_curve[elliptic curve name to use for ephemeral ECDH keys. (default is nistp256)]:named curve:_list_curves' \ + '-nbio[run with non-blocking IO]' \ + '-nbio_test[test with the non-blocking test bio]' \ + '-crlf[convert LF from terminal into CRLF]' \ + '-debug[print more output]' \ + '-msg[show protocol messages]' \ + '-state[print the SSL states]' \ + "-CApath[PEM format directory of CA's]:file:_files -/" \ + "-CAfile[PEM format file of CA's]:file:_files" \ + "-nocert[don't use any certificates (Anon-DH)]" \ + '-cipher[preferred cipher to use]:cipher suite:_list_ciphers' \ + "-serverpref[use server's cipher preferences]" \ + '-quiet[no server output]' \ + '-no_tmp_rsa[do not generate a tmp RSA key]' \ + '-psk_hint[PSK identity hint to use]:hint: ' \ + '-psk[PSK in hex (without 0x)]:PSK: ' \ + '-srpvfile[the verifier file for SRP]:file:_files' \ + '-srpuserseed[a seed string for a default user salt]:seed: ' \ + '-ssl2[just talk SSLv2]' \ + '-ssl3[just talk SSLv3]' \ + '-tls1_2[just talk TLSv1.2]' \ + '-tls1_1[just talk TLSv1.1]' \ + '-tls1[just talk TLSv1]' \ + '-dtls1[just talk DTLSv1]' \ + '-timeout[enable timeouts]' \ + '-mtu[set link layer MTU]' \ + '-chain[read a certificate chain]' \ + '-no_ssl2[just disable SSLv2]' \ + '-no_ssl3[just disable SSLv3]' \ + '-no_tls1[just disable TLSv1]' \ + '-no_tls1_1[just disable TLSv1.1]' \ + '-no_tls1_2[just disable TLSv1.2]' \ + '-no_dhe[disable ephemeral DH]' \ + '-no_ecdhe[disable ephemeral ECDH]' \ + '-bugs[turn on SSL bug compatibility]' \ + '-hack[workaround for early Netscape code]' \ + "-www[respond to a 'GET /' with a status page]" \ + "-WWW[respond to a 'GET / HTTP/1.0' with file ./]" \ + "-HTTP[respond to a 'GET / HTTP/1.0' with file ./ with the assumption it contains a complete HTTP response]" \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-id_prefix[generate SSL/TLS session IDs prefixed by arg]:prefix: ' \ + '-rand[files to use for random number input]:file:_rand_files' \ + '-servername[servername for HostName TLS extension]:hostname: ' \ + '-servername_fatal[on mismatch send fatal alert (default warning alert)]' \ + '-cert2[certificate file to use for servername (default is server2.pem)]:file:_files' \ + '-key2[Private Key file to use for servername, in cert file if not specified (default is server2.pem)]:file:_files' \ + '-tlsextdebug[hex dump of all TLS extensions received]' \ + '-no_ticket[disable use of RFC4507bis session tickets]' \ + '-legacy_renegotiation[enable use of legacy renegotiation (dangerous)]' \ + '-nextprotoneg[set the advertised protocols for the NPN extension (comma-separated list)]:protocol:(http/1.0 http/1.1)' \ + '-use_srtp[offer SRTP key management with a colon-separated profile list]:profiles: ' \ + '-4[use IPv4 only]' \ + '-6[use IPv6 only]' \ + '-keymatexport[export keying material using label]:label: ' \ + '-keymatexportlen[export len bytes of keying material (default 20)]:length: ' \ + '-status[respond to certificate status requests]' \ + '-status_verbose[enable status request verbose printout]' \ + '-status_timeout[status request responder timeout]:seconds: ' \ + '-status_url[status request fallback URL]:URL: ' + # TODO: srtp profiles +} + + +_openssl_s_time() { + # written for openssl 1.0.1k + _arguments -C \ + '-connect[host:port to connect to (default is localhost:4433)]:host\:port: ' \ + '-nbio[run with non-blocking IO]' \ + '-ssl2[just use SSLv2]' \ + '-ssl3[just use SSLv3]' \ + '-bugs[turn on SSL bug compatibility]' \ + '-new[just time new connections]' \ + '-reuse[just time connection reuse]' \ + "-www[retrieve the specified page from the site]:page: " \ + '-time[max number of seconds to collect data, default 30]:seconds: ' \ + '-verify[turn on peer certificate verification]:depth: ' \ + '-cert[certificate file to use, PEM format assumed]:file:_files' \ + '-key[RSA file to use, PEM format assumed, key is in cert file]:file:_files' \ + "-CApath[PEM format directory of CA's]:file:_files -/" \ + "-CAfile[PEM format file of CA's]:file:_files" \ + '-cipher[preferred cipher to use]:cipher suite:_list_ciphers' +} + + +_openssl_sess_id() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format]:format:(PEM DER)' \ + '-outform[output format]:format:(PEM DER)' \ + '-in[input file (default stdin)]:file:_files' \ + '-out[output file (default stdout)]:file:_files' \ + '-text[print ssl session id details]' \ + '-cert[output certificate ]' \ + '-noout[no CRL output]' \ + '-context[set the session ID context]:id: ' +} + + +_openssl_smime() { + # written for openssl 1.0.1k + _arguments -C \ + '-encrypt[encrypt message]' \ + '-decrypt[decrypt encrypted message]' \ + '-sign[sign message]' \ + '-verify[verify signed message]' \ + '-pk7out[output PKCS#7 structure]' \ + '-des3[encrypt with triple DES]' \ + '-des[encrypt with DES]' \ + '-seed[encrypt with SEED]' \ + '-rc2-40[encrypt with RC2-40 (default)]' \ + '-rc2-64[encrypt with RC2-64]' \ + '-rc2-128[encrypt with RC2-128]' \ + '-aes128[encrypt PEM output with cbc aes]' \ + '-aes192[encrypt PEM output with cbc aes]' \ + '-aes256[encrypt PEM output with cbc aes]' \ + '-camellia128[encrypt PEM output with cbc camellia]' \ + '-camellia192[encrypt PEM output with cbc camellia]' \ + '-camellia256[encrypt PEM output with cbc camellia]' \ + "-nointern[don't search certificates in message for signer]" \ + "-nosigs[don't verify message signature]" \ + "-noverify[don't verify signers certificate]" \ + "-nocerts[don't include signers certificate when signing]" \ + '-nodetach[use opaque signing]' \ + "-noattr[don't include any signed attributes]" \ + "-binary[don't translate message to text]" \ + '-certfile[other certificates file]:file:_files' \ + '-signer[signer certificate file]:file:_files' \ + '-recip[recipient certificate file for decryption]:file:_files' \ + '-in[input file]:file:_files' \ + '-inform[input format]:format:(SMIME PEM DER)' \ + '-inkey[input private key (if not signer or recipient)]:file:_files' \ + '-keyform[input private key format]:format:(PEM ENGINE)' \ + '-out[output file]:file:_files' \ + '-outform[output format]:format:(SMIME PEM DER)' \ + '-content[supply or override content for detached signature]:file:_files' \ + '-to[to address]:address: ' \ + '-from[from address]:address: ' \ + '-subject[subject]:subject: ' \ + '-text[include or delete text MIME headers]' \ + '-CApath[trusted certificates directory]:directory:_files -/' \ + '-CAfile[trusted certificates file]:file:_files' \ + "-crl_check[check revocation status of signer's certificate using CRLs]" \ + "-crl_check_all[check revocation status of signer's certificate chain using CRLs]" \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-passin[input file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-rand[files to use for random number input]:file:_rand_files' \ + ':certificate:_files' +} + + +_openssl_speed() { + # written for openssl 1.0.1k + local algorithms + algorithms=(mdc2 md4 md5 hmac sha1 sha256 sha512 whirlpoolrmd160 idea-cbc \ + seed-cbc rc2-cbc rc5-cbc bf-cbc des-cbc des-ede3 aes-128-cbc \ + aes-192-cbc aes-256-cbc aes-128-ige aes-192-ige aes-256-ige \ + camellia-128-cbc camellia-192-cbc camellia-256-cbc rc4 rsa512 \ + rsa1024 rsa2048 rsa4096 dsa512 dsa1024 dsa2048 ecdsap160 \ + ecdsap192 ecdsap224 ecdsap256 ecdsap384 ecdsap521 ecdsak163 \ + ecdsak233 ecdsak283 ecdsak409 ecdsak571 ecdsab163 ecdsab233 \ + ecdsab283 ecdsab409 ecdsab571 ecdsa ecdhp160 ecdhp192 ecdhp224 \ + ecdhp256 ecdhp384 ecdhp521 ecdhk163 ecdhk233 ecdhk283 ecdhk409 \ + ecdhk571 ecdhb163 ecdhb233 ecdhb283 ecdhb409 ecdhb571 ecdh idea \ + seed rc2 des aes camellia rsa blowfish) + _arguments -C \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-evp[use the specified EVP]:EVP: ' \ + '-decrypt[time decryption instead of encryption (only EVP)]' \ + '-mr[produce machine readable output]' \ + '-multi[run n benchmarks in parallel]:benchmarks: ' \ + "*:algorithm:(${algorithms})" +} + + +_openssl_spkac() { + # written for openssl 1.0.1k + _arguments -C \ + '-in[input file]:file:_files' \ + '-out[output file]:file:_files' \ + '-key[create SPKAC using private key]:file:_files' \ + '-passin[input file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-challenge[challenge string]:string: ' \ + '-spkac[alternative SPKAC name]:spkacname: ' \ + '-spksect[alternative section name]:section: ' \ + "-noout[don't print SPKAC]" \ + '-pubkey[output public key]' \ + '-verify[verify SPKAC signature]' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' +} + + +_openssl_srp() { + # written for openssl 1.0.1k + _arguments -C \ + '-verbose[talk a lot while doing things]' \ + '-config[a config file]:file:_files' \ + '-name[the particular srp definition to use]:definition: ' \ + '-srpvfile[the srp verifier file name]:file:_files' \ + '(-modify -delete -list)-add[add an user and srp verifier]' \ + '(-add -delete -list)-modify[modify the srp verifier of an existing user]' \ + '(-add -modify -list)-delete[delete user from verifier file]' \ + '(-add -modify -delete)-list[list user]' \ + '-gn[g and N values to be used for new verifier]:g and N: ' \ + '-userinfo[additional info to be set for user]:userinfo: ' \ + '-passin[input file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-passout[output file pass phrase source]:pass phrase source:_pass_phrase_source' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '-rand[files to use for random number input]:file:_rand_files' \ + ':user:' +} + + +_openssl_ts() { + # written for openssl 1.0.1k + # written for openssl 1.0.2e + local action digests + digests=(-dss1 -md4 -md5 -mdc2 -ripemd160 -sha -sha1 -sha224 -sha256 \ + -sha384 -sha512 -whirlpool) + if [[ "${CURRENT}" -eq 2 ]]; then + # first parameter to ts + _values 'openssl time stamp action' '-query[time stamp request generation]' '-reply[time stamp response generation]' '-verify[time stamp response verification]' + else + action="${words[2]}" + case "${action}" in + -query) + _arguments -C \ + '-rand[files to use for random number input]:file:_rand_files' \ + '-config[config file to use]:file:_files' \ + '(-digest)-data[data file for which the time stamp request needs to be created]:file:_files' \ + '(-data)-digest[digest of the data file]:bytes: ' \ + "($digests)-dss1[use the dss1 message digest algorithm]" \ + "($digests)-md4[to use the md4 message digest algorithm]" \ + "($digests)-md5[to use the md5 message digest algorithm]" \ + "($digests)-mdc2[to use the mdc2 message digest algorithm]" \ + "($digests)-ripemd160[to use the ripemd160 message digest algorithm]" \ + "($digests)-sha[to use the sha message digest algorithm]" \ + "($digests)-sha1[to use the sha1 message digest algorithm]" \ + "($digests)-sha224[to use the sha224 message digest algorithm]" \ + "($digests)-sha256[to use the sha256 message digest algorithm]" \ + "($digests)-sha384[to use the sha384 message digest algorithm]" \ + "($digests)-sha512[to use the sha512 message digest algorithm]" \ + "($digests)-whirlpool[to use the whirlpool message digest algorithm]" \ + '-policy[policy to use for creating the time stamp token]:policy ID: ' \ + '-no_nonce[do not include a nonce in the request]' \ + '-cert[request a signing certificate in the response]' \ + '-in[use the previously created time stamp request]:file:_files' \ + '-out[name of the output file to which the request will be written]:file:_files' \ + '-text[output in human-readable format instead of DER]' + ;; + -reply) + _arguments -C \ + '-config[config file to use]:file:_files' \ + '-section[config file section for response generation]:section: ' \ + '-queryfile[file containing a DER encoded time stamp request]:file:_files' \ + '-passin[private key password source]:pass phrase source:_pass_phrase_source' \ + '-signer[signer certificate of the TSA in PEM format]:file:_files' \ + '-inkey[signer private key in PEM format]:file:_files' \ + '-chain[signer certificate chain in PEM format]:file:_files' \ + '-policy[default policy to use for response]:policy ID: ' \ + '-in[use the previously created time stamp response in DER format]:file:_files' \ + '-token_in[the parameter to -in is a time stamp token in DER format]' \ + '-out[name of the output file to which the response will be written]:file:_files' \ + '-token_out[output a time stamp token instead of a time stamp response]' \ + '-text[output in human-readable format instead of DER]' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' + ;; + -verify) + _arguments -C \ + '(-digest -queryfile)-data[verify response against the specified file]:file:_files' \ + '(-data -queryfile)-digest[verify the response against the specified message digest]:digest bytes: ' \ + '(-data -digest)-queryfile[the original time stamp request in DER format]:file:_files' \ + '-in[time stamp response that needs to be verified in DER format]:file:_files' \ + '-token_in[the parameter to -in is a time stamp token in DER format]' \ + '-CApath[directory containing the trusted CA certificates of the client]:directory:_files -/' \ + '-CAFile[file containing a set of trusted self-signed CA certificates in PEM format]:file:_files' \ + '-untrusted[set of additional untrusted certificates in PEM format which may be needed when building the certificate chain]:file:_files' + ;; + esac + fi +} + + +_openssl_verify() { + # written for openssl 1.0.1k + _arguments -C \ + '-CApath[a directory of trusted certificates]:directory:_files -/' \ + '-CAfile[file A file of trusted certificates]:file:_files' \ + '-purpose[the intended use for the certificate]:purpose:(sslclient sslserver nssslserver smimesign smimeencrypt crlsign any ocsphelper timestampsign)' \ + '*-policy[enable policy processing and add arg to the user-initial-policy-set]:object name or OID: ' \ + '-ignore_critical[ignore critical extensions]' \ + '-attime[perform validation checks using the given time]:timestamp: ' \ + '-check_ss_sig[verify the signature on the self-signed root CA]' \ + "-crlfile[file containing one or more CRL's (in PEM format) to load]:file:_files" \ + '-crl_check[check end entity certificate in CRL]' \ + '-crl_check_all[check all certificates in CRL]' \ + '-policy_check[enables certificate policy processing]' \ + '-explicit_policy[set policy variable require-explicit-policy]' \ + '-inhibit_any[set policy variable inhibit-any-policy]' \ + '-inhibit_map[set policy variable inhibit-policy-mapping]' \ + '-x509_strict[strict X.509-compliance]' \ + '-extended_crl[enable extended CRL features]' \ + '-use_deltas[enable support for delta CRLs]' \ + '-policy_print[print out diagnostics related to policy processing]' \ + '-untrusted[a file of untrusted certificates]:file:_files' \ + '(-*)-help[print out a usage message]' \ + '-issuer_checks[print out diagnostics relating to searches for the issuer certificate of the current certificate]' \ + '-verbose[print extra information about the operations being performed]' \ + '*:certificate:_files' + # TODO: - may be used to separate certificates from options + # TODO: Do not hardcode purposes +} + + +_openssl_version() { + # written for openssl 1.0.1k + _arguments -C \ + '-a[all information, this is the same as setting all the other flags]' \ + '-v[the current OpenSSL version]' \ + '-b[the date the current version of OpenSSL was built]' \ + '-o[option information: various options set when the library was built]' \ + '-f[compilation flags]' \ + '-p[platform setting]' \ + '-d[OPENSSLDIR setting]' +} + + +_openssl_x509() { + # written for openssl 1.0.1k + _arguments -C \ + '-inform[input format - default PEM (one of DER, NET or PEM)]:format:(DER NET PEM)' \ + '-outform[output format - default PEM (one of DER, NET or PEM)]:arg:(DER NET PEM)' \ + '-keyform[private key format - default PEM]:arg:(DER PEM)' \ + '-CAform[CA format - default PEM]:arg:(DER PEM)' \ + '-CAkeyform[CA key format - default PEM]:arg:(DER PEM)' \ + '-in[input file - default stdin]:file:_files' \ + '-out[output file - default stdout]:file:_files' \ + '-passin[private key password source]:pass phrase source:_pass_phrase_source' \ + '-serial[print serial number value]' \ + '-subject_hash[print subject hash value]' \ + '-subject_hash_old[print old-style (MD5) subject hash value]' \ + '-issuer_hash[print issuer hash value]' \ + '-issuer_hash_old[print old-style (MD5) issuer hash value]' \ + '-hash[synonym for -subject_hash]' \ + '-subject[print subject DN]' \ + '-issuer[print issuer DN]' \ + '-email[print email address(es)]' \ + '-startdate[notBefore field]' \ + '-enddate[notAfter field]' \ + '-purpose[print out certificate purposes]' \ + '-dates[both Before and After dates]' \ + '-modulus[print the RSA key modulus]' \ + '-pubkey[output the public key]' \ + '-fingerprint[print the certificate fingerprint]' \ + '-alias[output certificate alias]' \ + '-noout[no certificate output]' \ + '-ocspid[print OCSP hash values for the subject name and public key]' \ + '-ocsp_uri[print OCSP Responder URL(s)]' \ + '-trustout[output a "trusted" certificate]' \ + '-clrtrust[clear all trusted purposes]' \ + '-clrreject[clear all rejected purposes]' \ + '-addtrust[trust certificate for a given purpose]:purpose:(clientAuth serverAuth emailProtection)' \ + '-addreject[reject certificate for a given purpose]:purpose:(clientAuth serverAuth emailProtection)' \ + '-setalias[set certificate alias]:alias: ' \ + '-days[how long till expiry of a signed certificate (default 30 days)]:days: ' \ + '-checkend[check whether the cert expires in the specified time]:seconds: ' \ + '-signkey[self sign cert with arg]:file:_files' \ + '-x509toreq[output a certification request object]' \ + '-req[input is a certificate request, sign and output]' \ + '-CA[set the CA certificate, must be PEM format]:file:_files' \ + '-CAkey[set the CA key, must be PEM format]:file:_files' \ + '-CAcreateserial[create serial number file if it does not exist]' \ + '-CAserial[serial file]:file:_files' \ + '-set_serial[serial number to use]' \ + '-text[print the certificate in text form]' \ + '-C[print out C code forms]' \ + '(-md5 -sha1 -mdc2)-md2[digest to use]' \ + '(-md2 -sha1 -mdc2)-md5[digest to use]' \ + '(-md2 -md5 -mdc2)-sha1[digest to use]' \ + '(-md2 -md5 -sha1)-mdc2[digest to use]' \ + '-extfile[configuration file with X509V3 extensions to add]' \ + '-extensions[section from config file with X509V3 extensions to add]' \ + '-clrext[delete extensions before signing and input certificate]' \ + '*-nameopt[various certificate name options]:options:_nameopts' \ + '-engine[use the specified engine, possibly a hardware device]:engine:_engines' \ + '*-certopt[various certificate text options]:options:_certopts' +} + + +_pass_phrase_source() { + # pass:password + # env:var + # file:pathname + # fd:number + # stdin + _values -S : 'pass phrase source' \ + 'pass[obtain the password from the command line]:password: ' \ + 'env[obtain the password from the environment variable var]:var:_parameters -g "*export*"' \ + 'file[obtain the password from a file]:file:_files' \ + 'fd[read the password from the file descriptor number]:number: ' \ + 'stdin[read the password from standard input]' +} + + +_rand_files() { + # FIXME: this does not allow using multiple files separated by : + # the following would probably work, but how to generate $files? + #_values -s : -S ' ' 'random source file or directory' ${files} + _files +} + + +_engines() { + # openssl engines + local engines + engines=(${${${(@f)"$(_call_program engines openssl engine)"}%)*}#\(}) + _values 'engines' ${engines} +} + + +_list_ciphers() { + # openssl ciphers + local ciphers + # add cipher suites + ciphers=(${(@s/:/)"$(_call_program ciphers openssl ciphers)"}) + # add static cipher strings + ciphers=(${ciphers} \ + 'DEFAULT[the default cipher list]' \ + 'COMPLEMENTOFDEFAULT[the ciphers included in ALL but not enabled by default]' \ + 'ALL[all cipher suites except the eNULL ciphers]' \ + 'COMPLEMENTOFALL[the cipher suites not enabled by ALL]' \ + 'HIGH["high" encryption cipher suites]' \ + 'MEDIUM["medium" encryption cipher suites]' \ + 'LOW["low" encryption cipher suites]' \ + {EXP,EXPORT}'[export encryption algorithms]' \ + 'EXPORT40[40 bit export encryption algorithms]' \ + 'EXPORT56[56 bit export encryption algorithms]' \ + {eNULL,NULL}'[ciphers offering no encryption]' \ + 'aNULL[ciphers offering no authentication]' \ + {kRSA,RSA}'[cipher suites using RSA key exchange]' \ + 'kDHr[cipher suites using DH key agreement signed by CAs with RSA keys]' \ + 'kDHd[cipher suites using DH key agreement signed by CAs with DSS keys]' \ + 'kDH[cipher suites using DH key agreement]' \ + {kDHE,kEDH}'[cipher suites using ephemeral DH key agreement, including anonymous cipher suites]' \ + {DHE,EDH}'[cipher suites using authenticated ephemeral DH key agreement]' \ + 'ADH[anonymous DH cipher suites, not including anonymous ECDH ciphers]' \ + 'DH[cipher suites using DH, including anonymous DH, ephemeral DH and fixed DH]' \ + 'kECDHr[cipher suites using fixed ECDH key agreement signed by CAs with RSA keys]' \ + 'kECDHe[cipher suites using fixed ECDH key agreement signed by CAs with ECDSA keys]' \ + 'kECDH[cipher suites using fixed ECDH key agreement]' \ + {kECDHE,kEECDH}'[cipher suites using ephemeral ECDH key agreement, including anonymous cipher suites]' \ + {ECDHE,kEECDH}'[cipher suites using authenticated ephemeral ECDH key agreement]' \ + 'AECDH[anonymous Elliptic Curve Diffie Hellman cipher suites]' \ + 'ECDH[cipher suites using ECDH key exchange, including anonymous, ephemeral and fixed ECDH]' \ + 'aRSA[cipher suites using RSA authentication]' \ + {aDSS,DSS}'[cipher suites using DSS authentication]' \ + 'aDH[cipher suites effectively using DH authentication]' \ + 'aECDH[cipher suites effectively using ECDH authentication]' \ + {aECDSA,ECDSA}'[cipher suites using ECDSA authentication]' \ + 'TLSv1.2[TLSv1.2 cipher suites]' \ + 'TLSv1[TLSv1.0 cipher suites]' \ + 'SSLv3[SSLv3.0 cipher suites]' \ + 'SSLv2[SSLv2.0 cipher suites]' \ + 'AES128[cipher suites using 128 bit AES]' \ + 'AES256[cipher suites using 256 bit AES]' \ + 'AES[cipher suites using AES]' \ + 'AESGCM[AES in Galois Counter Mode (GCM)]' \ + 'CAMELLIA128[cipher suites using 128 bit CAMELLIA]' \ + 'CAMELLIA256[cipher suites using 256 bit CAMELLIA]' \ + 'CAMELLIA[cipher suites using CAMELLIA]' \ + '3DES[cipher suites using triple DES]' \ + 'DES[cipher suites using DES (not triple DES)]' \ + 'RC4[cipher suites using RC4]' \ + 'RC2[cipher suites using RC2]' \ + 'IDEA[cipher suites using IDEA]' \ + 'SEED[cipher suites using SEED]' \ + 'MD5[cipher suites using MD5]' \ + {SHA1,SHA}'[cipher suites using SHA1]' \ + 'SHA256[cipher suites using SHA256]' \ + 'SHA384[cipher suites using SHA284]' \ + 'aGOST[cipher suites using GOST R 34.10 for authentication]' \ + 'aGOST01[cipher suites using GOST R 34.10-2001 authentication]' \ + 'aGOST94[cipher suites using GOST R 34.10-94 authentication]' \ + 'kGOST[cipher suites, using VKO 34.10 key exchange]' \ + 'GOST94[cipher suites, using HMAC based on GOST R 34.11-94]' \ + 'GOST89MAC[cipher suites using GOST 28147-89 MAC instead of HMAC]' \ + 'PSK[cipher suites using pre-shared keys (PSK)]' \ + 'SUITEB128[suite B mode operation using 128 or 192 bit level of security]' \ + 'SUITEB128ONLY[suite B mode operation using 128 bit level of security]' \ + 'SUITEB192[suite B mode operation using 192 bit level of security]' \ + ) + # FIXME: support !, + and - before each cipher suite + _values -s : 'cipher suite' ${ciphers} +} + + +_list_curves() { + # openssl ecparam -list_curves + local curves not_curves + curves="$(_call_program list_curves openssl ecparam -list_curves)" + # identify lines that do not contain curve names but only descriptions + not_curves=(${${(f)curves[@]}:#*:*}) + # remove non-curve lines, trailing descriptions and leading spaces + curves=(${${${${(f)curves[@]}:|not_curves}%:*}##* }) + _values 'named curves' ${curves} +} + + +_list_message_digest_algorithms() { + # openssl list-message-digest-algorithms + local algorithms + algorithms=(${${(@f)"$(_call_program message_digest_algorithms openssl list-message-digest-algorithms)"}%% *}) + _values 'message digest algorithms' ${algorithms} +} + + +_nameopts() { + _values -s ',' -w 'nameopts' \ + '(-compat compat)'{-compat,compat}'[use the old format. This is equivalent to specifying no name options at all]' \ + '(-RFC2253 RFC2253)'{-RFC2253,RFC2253}'[displays names compatible with RFC2253 equivalent to esc_2253, esc_ctrl, esc_msb, utf8, dump_nostr, dump_unknown, dump_der, sep_comma_plus, dn_rev and sname]' \ + '(-oneline oneline)'{-oneline,oneline}'[a oneline format which is more readable than RFC2253. Equivalent to esc_2253, esc_ctrl, esc_msb, utf8, dump_nostr, dump_der, use_quote, sep_comma_plus_space, space_eq and sname options]' \ + '(-multiline multiline)'{-multiline,multiline}'[a multiline format. Equivalent to esc_ctrl, esc_msb, sep_multiline, space_eq, lname and align]' \ + '(-esc_2253 esc_2253)'{-esc_2253,esc_2253}'[escape the "special" characters required by RFC2253 in a field]' \ + '(-esc_ctrl esc_ctrl)'{-esc_ctrl,esc_ctrl}'[escape control characters]' \ + '(-esc_msb esc_msb)'{-esc_msb,esc_msb}'[escape characters with the MSB set]' \ + '(-use_quote use_quote)'{-use_quote,use_quote}'[escapes some characters by surrounding the whole string with " characters]' \ + '(-utf8 utf8)'{-utf8,utf8}'[convert all strings to UTF8 format first]' \ + '(-ignore_type ignore_type)'{-ignore_type,ignore_type}'[this option does not attempt to interpret multibyte characters in any way]' \ + '(-show_type show_type)'{-show_type,show_type}'[show the type of the ASN1 character string]' \ + '(-dump_der dump_der)'{-dump_der,dump_der}'[use DER encoding when hexdumping fields]' \ + '(-dump_nostr dump_nostr)'{-dump_nostr,dump_nostr}'[dump non character string types]' \ + '(-dump_all dump_all)'{-dump_all,dump_all}'[dump all fields]' \ + '(-dump_unknown dump_unknown)'{-dump_unknown,dump_unknown}'[dump any field whose OID is not recognised by OpenSSL]' \ + '(-sep_comma_plus sep_comma_plus)'{-sep_comma_plus,sep_comma_plus}'[these options determine the field separators]' \ + '(-sep_comma_plus_space sep_comma_plus_space)'{-sep_comma_plus_space,sep_comma_plus_space}'[these options determine the field separators]' \ + '(-sep_semi_plus_space sep_semi_plus_space)'{-sep_semi_plus_space,sep_semi_plus_space}'[these options determine the field separators]' \ + '(-sep_multiline sep_multiline)'{-sep_multiline,sep_multiline}'[these options determine the field separators]' \ + '(-dn_rev dn_rev)'{-dn_rev,dn_rev}'[reverse the fields of the DN]' \ + '(-nofname nofname)'{-nofname,nofname}'[do not display field names]' \ + '(-sname sname)'{-sname,sname}'[display field names in short form]' \ + '(-lname lname)'{-lname,lname}'[display field names in long form]' \ + '(-oid oid)'{-oid,oid}'[display field names in numerical form]' \ + '(-align align)'{-align,align}'[align field values for a more readable output. Only usable with sep_multiline]' \ + '(-space_eq space_eq)'{-space_eq,space_eq}'[places spaces around the = character which follows the field name]' +} + + +_certopts() { + _values -s ',' -w 'certopts' \ + 'compatible[use the old format. This is equivalent to specifying no output options at all]' \ + "no_header[don't print header information: that is the lines saying \"Certificate\" and \"Data\"]" \ + "no_version[don't print out the version number]" \ + "no_serial[don't print out the serial number]" \ + "no_signame[don't print out the signature algorithm used]" \ + "no_validity[don't print the validity, that is the notBefore and notAfter fields]" \ + "no_subject[don't print out the subject name]" \ + "no_issuer[don't print out the issuer name]" \ + "no_pubkey[don't print out the public key]" \ + "no_sigdump[don't give a hexadecimal dump of the certificate signature]" \ + "no_aux[don't print out certificate trust information]" \ + "no_extensions[don't print out any X509V3 extensions]" \ + 'ext_default[retain default extension behaviour: attempt to print out unsupported certificate extensions]' \ + 'ext_error[print an error message for unsupported certificate extensions]' \ + 'ext_parse[ASN1 parse unsupported extensions]' \ + 'ext_dump[hex dump unsupported extensions]' \ + '(no_issuer no_pubkey no_header no_version no_sigdump no_signame)ca_default[the value used by the ca utility, equivalent to no_issuer, no_pubkey, no_header, no_version, no_sigdump and no_signame]' +} + + +_openssl "$@" + +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_openvpn3 b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_openvpn3 new file mode 100644 index 00000000..a6329b4c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_openvpn3 @@ -0,0 +1,246 @@ +#compdef openvpn3 +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for openvpn 3 (https://github.com/openvpn/openvpn3) (https://openvpn.net/openvpn-client-for-linux/). +# version: 13_beta-1 (Jul 1 2021) +# openvpn 3/Linux git:makepkg:2031975261858750 (openvpn3) +# openvpn core 3.git:HEAD:ce0c9963 linux x86_64 64-bit +# +# ------------------------------------------------------------------------------ +# Author +# ------- +# +# * undg (https://github.com/undg) +# +# ------------------------------------------------------------------------------ + +local sessions_configs_names=$(openvpn3 sessions-list | grep 'Config name:' | awk '{print $3}' | xargs) +local sessions_paths=$(openvpn3 sessions-list | grep 'Path:' | awk '{print $2}' | xargs) +local sessions_interfaces=$(openvpn3 sessions-list | grep 'Device:' | awk '{print $4}' | xargs) +local sessions_users=$(openvpn3 sessions-list | grep 'Owner:' | awk '{print $2}' | xargs) +local sessions_names=$(openvpn3 sessions-list | grep 'Session name:' | awk '{print $2}' | xargs) +local configs_names=$(openvpn3 configs-list | awk 'count&&!--count; /\/net\/openvpn\//{count=2}' | awk '{print $1}' | xargs) +local configs_paths=$(openvpn3 configs-list | grep '/net/openvpn/v3/configuration/' | xargs) + +_openvpn3_config-acl(){ + _arguments \ + {-s,--show}"[Show the current access control lists]" \ + {-o,--path}"[OBJ-PATH Path to the configuration in the configuration manager]: :($configs_paths)" \ + {-h,--help}"[This help screen]" \ + {-c,--config}"[CONFIG-NAME Alternative to --path, where configuration profile name is used instead]: :($configs_names)" \ + {-S,--seal}"[Make the configuration profile permanently read-only]" \ + {-R,--revoke}"[ Revoke this user access from this configuration profile]" \ + {-G,--grant}"[ Grant this user access to this configuration profile]" \ + "--public-access[ Set/unset the public access flag]" \ + "--lock-down[ Set/unset the lock-down flag.Will disable config retrieval for users]: :(true false)" \ + "--config-path[OBJ-PATH Alias for --path]: :($configs_paths)" \ +} + +_openvpn3_config-import(){ + _arguments \ + {-p,--persistent}"[Make the configuration profile persistent through service restarts]" \ + {-n,--name}"[NAME Provide a different name for the configuration (default: CFG-FILE)]" \ + {-h,--help}"[This help screen]" \ + {-c,--config}"[CFG-FILE Configuration file to import]: :_files" \ +} + +_openvpn3_config-manage(){ + _arguments \ + {-s,--show}"[Show current configuration options]" \ + {-r,--rename}"[NEW-CONFIG-NAME Renames the configuration]" \ + {-o,--path}"[CONFIG-PATH Path to the configuration in the configuration manager]: :($configs_paths)" \ + {-h,--help}"[This help screen]" \ + {-c,--config}"[CONFIG-NAME Alternative to --path, where configuration profile name is used instead]: :($configs_names)" \ + "--unset-override[ Removes the override]" \ + "--tls-version-min[ Sets the minimal TLS version for the control channel]: :(tls_1_0 tls_1_1 tls_1_2 tls_1_3)" \ + "--tls-cert-profile[ Sets the control channel tls profile]: :(legacy preferred suiteb)" \ + "--server-override[ Replace the remote, connecting to this server instead the server specified in the configuration]" \ + "--proxy-username[ HTTP Proxy username to authenticate as]" \ + "--proxy-port[ HTTP Proxy port to connect on]" \ + "--proxy-password[ HTTP Proxy password to use for authentication]" \ + "--proxy-host[ HTTP Proxy to connect via, overrides configuration file http-proxy]" \ + "--proxy-auth-cleartext[ Adds the boolean override proxy-auth-cleartext]: :(true false)" \ + "--proto-override[ Overrides the protocol being used]: :(tcp upd)" \ + "--port-override[ Replace the remote port, connecting to this port instead of the configuration value]" \ + "--persist-tun[ Adds the boolean override persist-tun]: :(true false)" \ + "--ipv6[ Sets the IPv6 policy of the client]: :(yes no default)" \ + "--force-cipher-aes-cbc[ Adds the boolean override force-cipher-aes-cbc]: :(true false)" \ + "--dns-sync-lookup[ Adds the boolean override dns-sync-lookup]: :(true false)" \ + "--dns-setup-disabled[ Adds the boolean override dns-setup-disabled]: :(true false)" \ + "--dns-fallback-google[ Adds the boolean override dns-fallback-google]: :(true false)" \ + "--config-path[CONFIG-PATH Alias for --path]: :($configs_paths)" \ + "--auth-fail-retry[ Adds the boolean override auth-fail-retry]: :(true false)" \ + "--allow-compression[ Set compression mode]: :(no asym yes)" \ +} + +_openvpn3_config-remove(){ + _arguments \ + {-o,--path}"[OBJ-PATH Path to the configuration in the configuration manager]: :($configs_paths)" \ + {-h,--help}"[This help screen]" \ + {-c,--config}"[CONFIG-NAME Alternative to --path, where configuration profile name is used instead]: :($configs_names)" \ + "--force[Force the deletion process without asking for confirmation]" \ + "--config-path[OBJ-PATH Alias for --path]: :($configs_paths)" \ +} + +_openvpn3_config-show(){ + _arguments \ + {-o,--path}"[OBJ-PATH Path to the configuration in the configuration manager]: :($configs_paths)" \ + {-j,--json}"[Dump the configuration in JSON format]" \ + {-h,--help}"[This help screen]" \ + {-c,--config}"[CONFIG-NAME Alternative to --path, where configuration profile name is used instead]: :($configs_names)" \ + "--config-path[OBJ-PATH Alias for --path]: :($configs_paths)" \ +} + +_openvpn3_configs-list(){ + _arguments \ + {-h,--help}"[This help screen]" \ +} + +_openvpn3_help(){ + _arguments \ + {-h,--help}"[This help screen]" \ +} + +_openvpn3_log(){ + _arguments \ + {-h,--help}"[This help screen]" \ + {-c,--config}"[CONFIG-NAME Alternative to --session-path, where configuration profile name is used instead]: :($sessions_configs_names $configs_names)" \ + {-I,--interface}"[INTERFACE Alternative to --session-path, where tun interface name is used instead]: :($sessions_interfaces)" \ + "--session-path[SESSION-PATH Receive log events for a specific session]: :($sessions_paths)" \ + "--log-level[LOG-LEVEL Set the log verbosity level of messages to be shown (default: 4)]" \ + "--config-events[Receive log events issued by the configuration manager]" \ +} + +_openvpn3__session-acl(){ + _arguments \ + {-s,--show}"[Show the current access control lists]" \ + {-o,--path}"[SESSION-PATH Path to the session in the session manager]: :($sessions_paths)" \ + {-h,--help}"[This help screen]" \ + {-c,--config}"[CONFIG-NAME Alternative to --path, where configuration profile name is used instead]: :($sessions_configs_names)" \ + {-R,--revoke}"[ Revoke this user access from this session]" \ + {-I,--interface}"[INTERFACE Alternative to --path, where tun interface name is used instead]: :($sessions_interfaces)" \ + {-G,--grant}"[ Grant this user access to this session]" \ + "--session-path[SESSION-PATH Alias for --path]: :($sessions_paths)" \ + "--public-access[ Set/unset the public access flag]: :(true false)" \ + "--allow-log-access[ Can users granted access also access the session log?]: :(true false)" \ +} + +_openvpn3_session-manage(){ + _arguments \ + {-o,--path}"[SESSION-PATH Path to the session in the session manager]: :($sessions_paths)" \ + {-h,--help}"[This help screen]" \ + {-c,--config}"[CONFIG-NAME Alternative to --path, where configuration profile name is used instead]: :($sessions_configs_names)" \ + {-R,--resume}"[Resumes a paused VPN session]" \ + {-P,--pause}"[Pauses the VPN session]" \ + {-I,--interface}"[INTERFACE Alternative to --path, where tun interface name is used instead]: :($sessions_interfaces)" \ + {-D,--disconnect}"[Disconnects a VPN session]" \ + "--session-path[SESSION-PATH Alias for --path]: :($sessions_paths)" \ + "--restart[Disconnect and reconnect a running VPN session]" \ + "--cleanup[Clean up stale sessions]" \ +} + +_openvpn3_session-start(){ + _arguments \ + {-p,--config-path}"[CONFIG-PATH Configuration path to an already imported configuration]: :($configs_paths)" \ + {-h,--help}"[This help screen]" \ + {-c,--config}"[CONFIG-FILE Configuration file to start directly]: :_files" \ + "--persist-tun[Enforces persistent tun/seamless tunnel (requires --config)]" \ +} + +_openvpn3_session-stats(){ + _arguments \ + {-o,--path}"[SESSION-PATH Path to the configuration in the configuration manager]: :($sessions_paths)" \ + {-j,--json}"[Dump the configuration in JSON format]" \ + {-h,--help}"[This help screen]" \ + {-c,--config}"[CONFIG-NAME Alternative to --path, where configuration profile name is used instead]: :($sessions_configs_names)" \ + {-I,--interface}"[INTERFACE Alternative to --path, where tun interface name is used instead]: :($sessions_interfaces)" \ + "--session-path[SESSION-PATH Alias for --path]: :($sessions_paths)" \ +} + +_openvpn3_sessions-list(){ + _arguments \ + {-h,--help}"[This help screen]" \ +} + +_openvpn3_shell-completion(){ + _arguments \ + {-h,--help}"[This help screen]" \ + "--list-commands[List all available commands]" \ + "--list-options[COMMAND List all available options for a specific command]: :($(openvpn3 shell-completion --list-commands))" \ + "--arg-helper[OPTION Used together with --list-options, lists value hint to an option]" +} + +_openvpn3_version(){ + _arguments \ + {-h,--help}"[This help screen]" \ +} + + +_openvpn3_command(){ + local -a _openvpn3_cmds + _openvpn3_cmds=( + "config-acl: Manage access control lists for configurations" \ + "config-import: Import configuration profiles" \ + "config-manage: Manage configuration properties" \ + "config-remove: Remove an available configuration profile" \ + "config-show: Show/dump a configuration profile" \ + "configs-list: List all available configuration profiles" \ + "help: This help screen" \ + "log: Receive log events as they occur" \ + "session-acl: Manage access control lists for sessions" \ + "session-manage: Manage VPN sessions" \ + "session-start: Start a new VPN session" \ + "session-stats: Show session statistics" \ + "sessions-list: List available VPN sessions" \ + "shell-completion: Helper function to provide shell completion data" \ + "version: Show program version information" \ + ) + + if ((CURRENT == 1)); then + _describe -t commands 'openvpn3 commands' _openvpn3_cmds + else + local curcontext="$curcontext" + cmd="${${_openvpn3_cmds[(r)$words[1]:*]%%:*}}" + if (($#cmd)); then + if (( $+functions[_openvpn3_$cmd] )); then + _openvpn3_$cmd + else + _message "no options for $cmd" + fi + else + _message "no more options" + fi + fi +} + +_arguments \ + {-h,--help}"[that This help screen]" \ + "*::openvpn3 commands:_openvpn3_command" \ + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_optirun b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_optirun new file mode 100644 index 00000000..dbd01fc9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_optirun @@ -0,0 +1,75 @@ +#compdef optirun +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for the optirun command from bumblebee +# (https://github.com/Bumblebee-Project/Bumblebee). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Christophe-Marie Duquesne +# +# ------------------------------------------------------------------------------ + +local curcontext="$curcontext" state line +typeset -A opt_args + +local -a arguments + +arguments=( + '--version[output version information]' + '(-h --help)'{-h,--help}'[show help]' + '(-c --vgl-compress)'{-c,--vgl-compress}'[image transport method]:method:(proxy jpeg rgb xb yuv)' + '--failsafe[run a program even if the nvidia card is unavailable]:boolean:(true false)' + '--no-failsafe[do not run a program if the nvidia card is unavailable]' + '--vgl-options[options to be passed to vglrun (example: +tr)]' + '(-q --quiet --silent)'{-q,--quiet,--silent}'[suppress all logging messages]' + '(-v --verbose)'{-v,--verbose}'[increase the verbosity level of log messages]' + '--debug[set the verbosity level to the maximum]' + '(-b --bridge)'{-b,--bridge}'[specify bridge library to use: VirtualGL, Primus or auto]:method:(auto primus virtualgl none)' + '(-d --display)'{-d,--display}'[the X display number to use]' + '(-C --config)'{-C,--config}'[retrieve settings for Bumblebee from FILE]:file:_files' + '(-l --ldpath)'{-l,--ldpath}'[PATH the libraries like libGL.so are searched in]:file:_files' + '--primus-ldpath[a colon-separated list of paths which are searched for the primus libGL.so.1]:file:_files' + '(-s --socket)'{-s,--socket}'[use FILE for communication with the daemon]:file:_files' + '--no-xorg[do not start secondary X server (implies -b none)]' + '*::arguments: _normal' +) + +_arguments $arguments + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_patool b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_patool new file mode 100644 index 00000000..5abe6b2c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_patool @@ -0,0 +1,95 @@ +#compdef patool +# ------------------------------------------------------------------------------ +# Copyright (c) 2017 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for patool (https://github.com/wummel/patool). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Sergei Eremenko (https://github.com/SmartFinn) +# +# ------------------------------------------------------------------------------ + +local state line ret=1 + +_arguments -C \ + '(-h --help)'{-h,--help}'[show help message and exit]' \ + '(--non-interactive)'--non-interactive'[do not query for user input]' \ + '(-v --verbose)'{-v,--verbose}'[verbose operation]' \ + '1:cmd:->cmds' \ + '*:arg:->args' && ret=0 + +case $state in + (cmds) + local -a cmds + + cmds=( + 'create:create an archive from given files' + 'diff:show differences between two archives' + 'extract:extract files from given archives' + 'formats:show all supported archive formats' + 'list:list files in archives' + 'repack:repackage archive to a different format' + 'recompress:recompress an archive to smaller size' + 'search:search in archive contents for given pattern' + 'test:test the given archives' + ) + + _describe -t commands 'patool commands' cmds && ret=0 + ;; + (args) + case $line[1] in + (extract) + _arguments \ + '--outdir[extract to the given output directory]:select directory:_files -/' \ + '*:files:_files' && ret=0 + ;; + (formats) + _message 'no more arguments' && ret=0 + ;; + (search) + _arguments \ + '2:search pattern:' \ + '*:files:_files' && ret=0 + ;; + (*) + _arguments \ + '*:files:_files' && ret=0 + ;; + esac + ;; +esac + +return $ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_periscope b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_periscope new file mode 100644 index 00000000..a4fa29e0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_periscope @@ -0,0 +1,36 @@ +#compdef periscope +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Periscope (https://code.google.com/archive/p/periscope/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# +# ------------------------------------------------------------------------------ + + +_arguments \ + '(- : *)'{-h,--help}'[show help message and exit]' \ + '(- : *)--version[show version number and exit]' \ + '*'{-l,--language}'[wanted language]: :_language_codes ISO-639-1' \ + '(-f --force)'{-f,--force}'[replace existing subtitle file]' \ + '(-q --query)'{-q,--query}'[query to send to the subtitles website]:queries' \ + '--list-plugins[list all plugins supported by periscope]' \ + '--list-active-plugins[list all plugins used to search subtitles]' \ + '--cache-folder[cache/config directory to use]: :_files -/' \ + '--quiet[run in quiet mode (only show warn and error messages)]' \ + '--debug[set the logging level to debug]' \ + '*: :_files' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_pgsql_utils b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_pgsql_utils new file mode 100644 index 00000000..b6e8b599 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_pgsql_utils @@ -0,0 +1,590 @@ +#compdef psql pg_dump pg_dumpall pg_restore createdb dropdb vacuumdb createuser dropuser initdb +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users, Dominic Mitchell, Johann 'Myrkraverk' Oskarsson, Daniel Serodio, J Smith +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for PostgreSQL utils (https://www.postgresql.org/). +# +# Source: https://www.zsh.org/mla/users/2004/msg01006.html +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Dominic Mitchell +# +# * Johann 'Myrkraverk' Oskarsson +# +# * Daniel Serodio pg_dumpall completion +# +# * J Smith various completion additions +# +# ------------------------------------------------------------------------------ + + +_pgsql_get_identity () { + _pgsql_user=${(v)opt_args[(i)-U|--username]} + _pgsql_port=${(v)opt_args[(i)-p|--port]} + _pgsql_host=${(v)opt_args[(i)-h|--host]} + + _pgsql_params=( + ${_pgsql_user:+"--username=$_pgsql_user"} + ${_pgsql_port:+"--port=$_pgsql_port"} + ${_pgsql_host:+"--host=$_pgsql_host"} + ) +} + +# Postgres Allows specifying the path to the directory containing the +# socket as well as a hostname. +_pgsql_host_or_dir() { + _alternative \ + 'hosts:host:_hosts' \ + 'directories:directory:_directories' +} + +# This creates a port completion list based on socket files on the +# local computer. Be default, Postgres puts them in /tmp/ but Debian +# changed that to /var/run/postgresql/ in their packages. +_pgsql_ports() { + compadd "$@" - /tmp/.s.PGSQL.<->(N:e) /var/run/postgresql/.s.PGSQL.<->(N:e) +} + +_pgsql_users () { + local _pgsql_user _pgsql_port _pgsql_host _pgsql_params + local _pgsql_user_sql + _pgsql_get_identity + + # We use _pgsql_port and _pgsql_host directly here instead of + # _pgsql_params so as to not pick up a partially completed + # username. + _pgsql_params=( + ${_pgsql_port:+"--port=$_pgsql_port"} + ${_pgsql_host:+"--host=$_pgsql_host"} + ) + + _pgsql_user_sql='select r.rolname from pg_catalog.pg_roles r where r.rolcanlogin = true' + + compadd "$@" - $( psql $_pgsql_params[@] -XAqt -c $_pgsql_user_sql template1 2>/dev/null ) + +} + +_pgsql_tables () { + local _pgsql_user _pgsql_port _pgsql_host _pgsql_params + _pgsql_get_identity + + # Need to pull out the database name from the existing arguments. + # This is going to vary between commands. Thankfully, it's only + # used by pg_dump, which always has the dbname in arg1. If it's + # not present it defaults to ${PGDATABASE:-$LOGNAME}, which + # matches (I think) the PostgreSQL behaviour. + + local db + db=${line[1]:-${PGDATABASE:-$LOGNAME}} + + ## Instead of parsing the output of the psql \ commands, we look + ## up the tables ourselves. The following query has been tested + ## with Postgres 8.2 - 9.2. + + local _pgsql_table_sql + _pgsql_table_sql="select n.nspname || '.' || c.relname \ + from pg_catalog.pg_class c \ + left join pg_catalog.pg_namespace n on n.oid = c.relnamespace \ + where c.relkind in ('r', '') \ + and n.nspname <> 'pg_catalog' \ + and n.nspname <> 'information_schema' \ + and n.nspname !~ '^pg_toast' \ + and pg_catalog.pg_table_is_visible( c.oid ) \ + order by 1" + + compadd "$@" - \ + $( psql $_pgsql_params[@] -AXqt -c $_pgsql_table_sql $db 2>/dev/null ) +} + +_pgsql_schemas () { + local _pgsql_user _pgsql_port _pgsql_host _pgsql_params + _pgsql_get_identity + + local db + db=${line[1]:-${PGDATABASE:-$LOGNAME}} + + local _pgsql_schema_sql="select n.nspname \ + from pg_catalog.pg_namespace n \ + where n.nspname !~ '^pg_' \ + and n.nspname <> 'information_schema' \ + order by 1;" + + compadd "$@" - \ + $( psql $_pgsql_params[@] -AXqt -c $_pgsql_schema_sql $db 2>/dev/null ) +} + +_pgsql_databases () { + local _pgsql_user _pgsql_port _pgsql_host _pgsql_params + _pgsql_get_identity + + local _pgsql_services _pgsql_service_files + _pgsql_service_files=(~/.pg_service.conf) + (( $+commands[pg_config] )) && _pgsql_service_files+=$(pg_config --sysconfdir)/pg_service.conf + + _pgsql_services=$( grep -h '^\[.*\]' $_pgsql_service_files 2>/dev/null \ + | sed -e 's/^\[/service=/' -e 's/\].*$//' ) + + local _pgsql_db_sql + _pgsql_db_sql="select d.datname from pg_catalog.pg_database d \ + where d.datname <> 'template0'" + + compadd "$@" - \ + ${(f)_pgsql_services} \ + $( psql $_pgsql_params[@] -AXtq -c $_pgsql_db_sql template1 2>/dev/null ) +} + +_pgsql_encodings () { + local _pgsql_user + _pgsql_get_identity + + local _pgsql_db_sql + _pgsql_db_sql="select pg_encoding_to_char(i) from generate_series(0,100) i;" + + compadd "$@" - $( psql $_pgsql_params[@] -AXtq -c $_pgsql_db_sql template1 ) +} + + +## +## The actual completion code for the commands +## + +_psql () { + local curcontext="$curcontext" state line expl + typeset -A opt_args + + _arguments -C -s "-*" \ + "$_pgsql_common_opts[@]" \ + {-c+,--command=}':execute SQL command:' \ + {-d+,--dbname=}':database to connect to:_pgsql_databases' \ + {-f+,--file=}':SQL file to read:_files' \ + {-l,--list}'[list databases]' \ + {-v+,--set=,--variable=}':set SQL variable:' \ + {-V,--version}'[output version information, then exit]' \ + {-X,--no-psqlrc}'[don'\''t read ~/.psqlrc]' \ + {-1,--single-transaction}'[restore as a single transaction]' \ + {-\?,--help=}':display help:' \ + \ + {-a,--echo-all}'[print commands read]' \ + {-b,--echo-errors}'[echo failed commands]' \ + {-e,--echo-queries}'[display queries submitted]' \ + {-E,--echo-hidden}'[display hidden queries]' \ + {-L,--log-file=}'[send session log to file]' \ + {-n,--no-readline}'[disable enhanced command line editing (readline)]' \ + {-o+,--output=}':query output:_files' \ + {-q,--quiet}'[non verbose mode]' \ + {-s,--single-step}'[prompt before each query]' \ + {-S,--single-line}'[newline sends query]' \ + \ + {-A,--no-align}'[unaligned output mode]' \ + --csv'[CSV (Comma-Separated Values) table output mode]' \ + {-F+,--field-separator=}':field separator char:' \ + {-H,--html}'[HTML output]' \ + {-P+,--pset=}':set psql variable:' \ + {-R+,--record-separator=}':record separator char:' \ + {-t,--tuples-only}'[don'\''t display header/footer]' \ + {-T+,--table-attr=}':HTML table options:' \ + {-x,--expanded}'[one column per line]' \ + {-z,--field-separator-zero}'[set field separator for unaligned output to zero byte]' \ + {-0,--record-separator-zero}'[set record separator for unaligned output to zero byte]' \ + -u'[prompt for username/password]' \ + ':PostgreSQL database:_pgsql_databases' \ + ':PostgreSQL user:_pgsql_users' +} + +_pg_dump () { + local curcontext="$curcontext" state line expl + typeset -A opt_args + + _arguments -C -s \ + "$_pgsql_common_opts[@]" \ + {-f+,--file=}':output file:_files' \ + {-F+,--format=}':output format:_values "format" "p[plain text]" "t[tar]" "c[custom]"' \ + {-j,--jobs=}'[use this many parallel jobs to dump]' \ + {-v,--verbose}'[verbose mode]' \ + {-V,--version}'[output version information, then exit]' \ + {-Z+,--compress=}':compression level:_values "level" 9 8 7 6 5 4 3 2 1 0' \ + --lock-wait-timeout='[fail after waiting TIMEOUT for a table lock]' \ + --no-sync'[do not wait for changes to be written safely to disk]' \ + {-\?,--help}'[display help]' \ + \ + {-a,--data-only}'[dump only data]' \ + {-b,--blobs}'[dump blobs as well]' \ + {-B,--no-blobs}'[exclude large objects in dump]' \ + {-c,--clean}'[include clean cmds in dump]' \ + {-C,--create}'[include createdb cmds in dump]' \ + {-e+,--extension=}'[dump the specified extension(s) only]' \ + {-E+,--encoding=}':database encoding:_pgsql_encodings' \ + {-n+,--schema=}':schema to dump:_pgsql_schemas' \ + {-N+,--exclude-schema=}':schema to NOT dump:_pgsql_schemas' \ + {-O,--no-owner}'[don'\''t recreate as same owner]' \ + {-s,--schema-only}'[no data, only schema]' \ + {-S+,--superuser=}':superuser name:_pgsql_users' \ + {-t+,--table=}':table to dump:_pgsql_tables' \ + {-T+,--exclude-table=}':table to NOT dump:_pgsql_tables' \ + {-x,--no-{acl,privileges}}'[don'\''t dump ACLs]' \ + --binary-upgrade'[for use by upgrade utilities only]' \ + {-D,--{attribute,column}-inserts}'[use INSERT (cols) not COPY]' \ + --disable-dollar-quoting'[disable dollar quoting, use SQL standard quoting]' \ + --disable-triggers'[disable triggers during data-only restore]' \ + --enable-row-security'[enable row security (dump only content user has access to)]' \ + --exclude-table-data='[do NOT dump data for the named table(s)]' \ + --if-exists'[use IF EXISTS when dropping objects]' \ + --include-foreign-data='[include data of foreign servers]' \ + --inserts'[dump data as INSERT commands, rather than COPY]' \ + --load-via-partition-root'[load partitions via the root table]' \ + --no-comments'[do not dump comments]' \ + --no-publications'[do not dump publications]' \ + --no-security-labels'[do not dump security label assignments]' \ + --no-subscriptions'[do not dump subscriptions]' \ + --no-synchronized-snapshots'[do not use synchronized snapshots in parallel jobs]' \ + --no-tablespaces'[do not dump tablespace assignments]' \ + --no-toast-compression'[do not dump TOAST compression methods]' \ + --no-unlogged-table-data'[do not dump unlogged table data]' \ + --on-conflict-do-nothing'[add ON CONFLICT DO NOTHING to INSERT commands]' \ + --quote-all-identifiers'[quote all identifiers, even if not key words]' \ + --rows-per-insert=['number of rows per INSERT'] \ + --section=':dump named section:_values "section" pre-data data post-data' \ + --serializable-deferrable'[wait until the dump can run without anomalies]' \ + --snapshot='[use given snapshot for the dump]' \ + --strict-names'[require table and/or schema include patterns to match at least one entity each]' \ + --use-set-session-authorization'[use SET SESSION AUTHORIZATION commands instead of ALTER OWNER]' \ + \ + {-i,--ignore-version}'[ignore version mismatch]' \ + {-o,--oids}'[dump objects identifiers for every table]' \ + {-R,--no-reconnect}'[don'\''t output connect]' \ + -X+':option:_values "option" use-set-session-authorization disable-triggers' \ + ':PostgreSQL database:_pgsql_databases' +} + +_pg_restore () { + local curcontext="$curcontext" state line expl + typeset -A opt_args + + _arguments -C -s \ + "$_pgsql_common_opts[@]" \ + {-d+,--dbname=}':database to connect to:_pgsql_databases' \ + {-f+,--file=}':output file:_files' \ + {-F+,--format=}':output format:_values "format" "p[plain text]" "t[tar]" "c[custom]"' \ + {-l,--list}'[list databases]' \ + {-v,--verbose}'[verbose mode]' \ + {-V,--version}'[output version information, then exit]' \ + {-\?,--help}'[display help]' \ + \ + {-a,--data-only}'[dump only data]' \ + {-c,--clean}'[include clean (drop) cmds before recreating]' \ + {-C,--create}'[include createdb cmds in dump]' \ + {-e,--exit-on-error}'[exit on error, default is to continue]' \ + {-I,--index=}':index name:' \ + {-j,--jobs=}':use this many parallel jobs to restore:' \ + {-L,--use-list=}':use table of contents from this file for selecting/ordering output:' \ + {-n,--schema=}':restore only objects in this schema:' \ + {-O,--no-owner}'[skip restoration of object ownership]' \ + {-P,--function=}':restore named function:' \ + {-s,--schema-only}'[restore only the schema, no data]' \ + {-S,--superuser=}':superuser user name to use for disabling triggers:' \ + {-t,--table=}':restore named table:' \ + {-T,--trigger=}':restore named trigger:' \ + {-x,--no-privileges}'[skip restoration of access privileges (grant/revoke)]' \ + {-1,--single-transaction}'[restore as a single transaction]' \ + --disable-triggers'[disable triggers during data-only restore]' \ + --enable-row-security'[enable row security]' \ + --if-exists'[use IF EXISTS when dropping objects]' \ + --no-comments'[do not restore comments]' \ + --no-data-for-failed-tables'[do not restore data of tables that could not be created]' \ + --no-publications'[do not restore publications]' \ + --no-security-labels'[do not restore security labels]' \ + --no-subscriptions'[do not restore subscriptions]' \ + --no-tablespaces'[do not restore tablespace assignments]' \ + --section=':dump named section:_values "section" pre-data data post-data' \ + --strict-names'[require table and/or schema include patterns to match at least one entity each]' \ + --use-set-session-authorization'[use SET SESSION AUTHORIZATION commands instead of ALTER OWNER commands to set ownership]' \ + \ + {-b,--blobs}'[include large objects in dump]' \ + {-B,--no-blobs}'[exclude large objects in dump]' \ + \ + "1: :_files" +} + +_pg_dumpall () { + local curcontext="$curcontext" state line expl + typeset -A opt_args + + _arguments -C -s \ + "$_pgsql_common_opts[@]" \ + {-f+,--file=}':output file:_files' \ + {-v,--verbose}'[verbose mode]' \ + {-V,--version}'[output version information, then exit]' \ + --lock-wait-timeout='[fail after waiting TIMEOUT for a table lock]' \ + {-\?,--help}'[display help]' \ + \ + {-a,--data-only}'[dump only data]' \ + {-c,--clean}'[include clean (drop) cmds before recreating]' \ + {-E,--encoding=}'[dump the data in encoding]' \ + {-g,--globals-only}'[dump only global objects, no databases]' \ + {-O,--no-owner}'[don'\''t recreate as same owner]' \ + {-r,--roles-only}'[no databases or tablespaces, only roles]' \ + {-s,--schema-only}'[no data, only schema]' \ + {-S+,--superuser=}':superuser name:_pgsql_users' \ + {-t,--tablespaces-only}'[no databases or roles, only tablespaces]' \ + {-x,--no-privileges}'[don'\''t dump ACLs]' \ + --binary-upgrade'[for use by upgrade utilities only]' \ + --column-inserts'[use INSERT with column names not COPY]' \ + --disable-dollar-quoting'[disable dollar quoting, use SQL standard quoting]' \ + --disable-triggers'[disable triggers during data-only restore]' \ + --exclude-database=':exclude databases:_pgsql_databases' \ + --extra-float-digits='[override default setting for extra_float_digits]' \ + --if-exists'[use IF EXISTS when dropping objects]' \ + --inserts'[use INSERT not COPY]' \ + --load-via-partition-root'[pload partitions via the root table]' \ + --no-comments'[do not dump comments]' \ + --no-publications'[do not dump publications]' \ + --no-role-passwords'[do not dump passwords for roles]' \ + --no-security-labels'[do not dump security label assignments]' \ + --no-subscriptions'[do not dump subscriptions]' \ + --no-sync'[do not wait for changes to be written safely to disk]' \ + --no-tablespaces'[do not dump tablespace assignments]' \ + --no-toast-compression'[do not dump TOAST compression methods]' \ + --no-unlogged-table-data'[do not dump unlogged table data]' \ + --on-conflict-do-nothing'[add ON CONFLICT DO NOTHING to INSERT commands]' \ + --quote-all-identifiers'[quote all identifiers, even if not key words]' \ + --rows-per-insert='[number of rows per INSERT]' \ + --use-set-session-authorization'[use SET SESSION AUTHORIZATION cmds instead of ALTER OWNER]' \ + {-o,--oids}'[dump objects identifiers for every table]' \ +} + +_createdb () { + local curcontext="$curcontext" state line expl + typeset -A opt_args + + _arguments -C -s \ + "$_pgsql_common_opts[@]" \ + {-D+,--tablespace=}'[default tablespace for the database]' \ + {-e,--echo}'[display SQL queries]' \ + {-E+,--encoding=}':database encoding:_pgsql_encodings' \ + {-l+,--locale=}'[locale settings for the database]' \ + --lc-collate='[LC_COLLATE setting for the database]' \ + --lc-ctype='[LC_CTYPE setting for the database]' \ + {-O+,--owner=}':database user to own the new database:_pgsql_users' \ + {-T+,--template=}':database template:_pgsql_databases' \ + '--version[output version information, then exit]' \ + {-\?,--help}'[display help]' \ + \ + --maintenance-db=':alternate maintenance database:_pgsql_databases' \ + {-q,--quiet}'[non verbose mode]' \ + --location=':database location (unsupported since PostgreSQL 8.0):_directories' \ + ':PostgreSQL database:' \ + ':comment:' +} + +_dropdb () { + local curcontext="$curcontext" state line expl + typeset -A opt_args + + _arguments -C -s \ + "$_pgsql_common_opts[@]" \ + {-e,--echo}'[display SQL queries]' \ + {-f,--force}'[try to terminate other connections before dropping]' \ + {-i,--interactive}'[confirm before drop]' \ + {-V,--version}'[output version information, then exit]' \ + --if-exists'[don'\''t report error if database does'\''t exist]' \ + --maintenance-db=':alternate maintenance database:_pgsql_databases' \ + {-q,--quiet}'[non verbose mode]' \ + ':PostgreSQL database:_pgsql_databases' +} + +_vacuumdb () { + local curcontext="$curcontext" state line expl + typeset -A opt_args + + _arguments -C -s \ + "$_pgsql_common_opts[@]" \ + {-a,--all}'[vacuum all databases]' \ + {-d+,--dbname=}':database to connect to:_pgsql_databases' \ + --disable-page-skipping'[disable all page-skipping behavior]' \ + {-e,--echo}'[show the commands being sent to the server]' \ + {-f,--full}'[do full vacuuming]' \ + {-F,--freeze}'[freeze row transaction information]' \ + --force-index-cleanup'[always remove index entries that point to dead tuples]' \ + {-j,--jobs=}'[use this many concurrent connections to vacuum]' \ + '--min-mxid-age=[minimum multixact ID age of tables to vacuum]' \ + '--min-xid-age=[minimum transaction ID age of tables to vacuum]' \ + --no-index-cleanup'[don'\''t remove index entries that point to dead tuples]' \ + --no-process-toast'[skip the TOAST table associated with the table to vacuum]' \ + --no-truncate'[don'\''t truncate empty pages at the end of the table]' \ + {-P+,--parallel=}'[use this many background workers for vacuum, if available]' \ + {-q,--quiet}'[do not write any messages]' \ + '--skip-locked[skip relations that cannot be immediately locked]' \ + {-t+,--table=}':table to dump:_pgsql_tables' \ + {-v,--verbose}'[write a lot of output]' \ + {-V,--version}'[output version information, then exit]' \ + {-z,--analyze}'[update optimizer hints]' \ + {-Z,--analyze-only}'[only update optimizer statistics; no vacuum]' \ + --analyze-in-stages'[only update optimizer statistics, in multiple stages for faster results; no vacuum]' \ + {-\?,--help}'[display help]' \ + --maintenance-db='[alternate maintenance database]' \ + '1:PostgreSQL database:_pgsql_databases' +} + +_createuser () { + local curcontext="$curcontext" state line expl + typeset -A opt_args + + _arguments -C -s \ + "$_pgsql_common_opts[@]" \ + {-c,--connection-limit=}'[connection limit for role (default: no limit)]' \ + {-d,--createdb}'[role can create new databases]' \ + {-D,--no-createdb}'[role cannot create databases]' \ + {-e,--echo}'[display SQL queries]' \ + {-g,--role=}'[new role will be a member of this role]' \ + {-i,--inherit}'[role inherits privileges of roles it is a member of (default)]' \ + {-I,--no-inherit}'[role does not inherit privileges]' \ + {-l,--login}'[role can login (default)]' \ + {-L,--no-login}'[role cannot login]' \ + {-P,--pwprompt}'[assign a password to new role]' \ + {-r,--createrole}'[role can create new roles]' \ + {-R,--no-createrole}'[role cannot create roles]' \ + {-s,--superuser}'[role will be superuser]' \ + {-S,--no-superuser}'[role will not be superuser]' \ + --interactive'[prompt for missing role name and attributes rather than using defaults]' \ + --replication'[role can initiate replication]' \ + --no-replication'[role cannot initiate replication]' \ + {-E,--encrypted}'[encrypt stored password]' \ + {-N,--unencrypted}'[do not encrypt stored password]' \ + {-\?,--help}'[display help]' +} + +_dropuser () { + local curcontext="$curcontext" state line expl + typeset -A opt_args + + _arguments -C -s \ + "$_pgsql_common_opts[@]" \ + {-e,--echo}'[display SQL queries]' \ + {-q,--quiet}'[non verbose mode]' \ + {-i,--interactive}'[prompt before deleting anything, and prompt for role name if not specified]' \ + {-V,--version}'[output version information, then exit]' \ + --if-exists'[don'\''t report error if user doesn'\''t exist]' \ + ':PostgreSQL user:_pgsql_users' +} + +_initdb () { + local curcontext="$curcontext" state line expl + typeset -A opt_args + + _arguments -C -s \ + {--auth=,-A+}':default authentication method for local connections:_values "auth methods" $_pgsql_auth_methods[@]' \ + --auth-host=':default authentication method for local TCP/IP connections:_values "auth methods" $_pgsql_auth_methods[@]' \ + --auth-local=':default authentication method for local-socket connections:_values "auth methods" $_pgsql_auth_methods[@]' \ + {-D+,--pgdata=}':location for this database cluster:_files' \ + {-E+,--encoding=}':set default encoding for new databases:_pgsql_encodings' \ + {-g,--allow-group-access}'[allow group readexecute on data directory]' \ + {-k,--data-checksums}':use data page checksums:' \ + --locale=':set default locale for new databases:' \ + --lc-collate=':set the default locale for collate:' \ + --lc-ctype=':set the default locale for ctype:' \ + --lc-messages=':set the default locale for messages:' \ + --lc-monetary=':set the default locale for monetary:' \ + --lc-numeric=':set the default locale for numeric:' \ + --lc-time=':set the default local for time:' \ + --no-locale'[equivalent to --locale=C]' \ + --pwfile=':read password for the new superuser from file:_files' \ + {-T+,--text-search-config=}'[default text search configuration]' \ + {-U+,--username=NAME}':database superuser name:' \ + {-W,--pwprompt}'[prompt for a password for the new superuser]' \ + {-X+,--waldir=}':location for the write-ahead log directory:_files' \ + --xlogdir=':location for the transaction log directory (unsupported since PostgreSQL 10):_files' \ + --wal-segsize='[size of WAL segments, in megabytes]' \ + {-d,--debug}'[generate lots of debugging output]' \ + --discard-caches'[set debug_discard_caches=1]' \ + -L+':where to find the input files:_files' \ + {-n,--no-clean}'[do not clean up after errors]' \ + {-N,--no-sync}':do not wait for changes to be written safely to disk:' \ + --instructions'[do not print instructions for next steps]' \ + {-s,--show}'[show internal settings]' \ + {-S,--sync-only}'[only sync data directory]' \ + {-V,--version}'[output version information, then exit]' \ + {-\?,--help}'[display help]' \ + ':location for this database cluster:_files' +} + +_pgsql_utils () { + local _pgsql_common_opts _pgsql_auth_methods + + _pgsql_common_opts=( + {-\?,--help}'[display help]' + {-h+,--host=}':database host:_pgsql_host_or_dir' + {-p+,--port=}':database port number:_pgsql_ports' + {-U+,--username=}':connect as user:_pgsql_users' + {-W,--password}'[prompt for password]' + {-w,--no-password}'[never prompt for password]' + --role='[do SET ROLE before restore]' + ) + + _pgsql_auth_methods=( + trust + reject + md5 + password + gss + sspi + krb5 + ident + peer + ldap + radius + cert + pam + ) + + case "$service" in + psql) _psql "$@" ;; + pg_dump) _pg_dump "$@" ;; + pg_dumpall) _pg_dumpall "$@" ;; + pg_restore) _pg_restore "$@" ;; + createdb) _createdb "$@" ;; + dropdb) _dropdb "$@" ;; + vacuumdb) _vacuumdb "$@" ;; + createuser) _createuser "$@" ;; + dropuser) _dropuser "$@" ;; + initdb) _initdb "$@" ;; + esac +} + +_pgsql_utils "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_phing b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_phing new file mode 100644 index 00000000..eab4f981 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_phing @@ -0,0 +1,94 @@ +#compdef phing +# ------------------------------------------------------------------------------ +# Copyright (c) Igor M. Timoshenko +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Phing (https://www.phing.info/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Igor Timoshenko +# +# ------------------------------------------------------------------------------ + +_phing() { + local context curcontext="$curcontext" state line ret=1 + integer NORMARG + typeset -A opt_args + + # Follow https://www.phing.info/guide/chunkhtml/sec.commandlineargs.html for more information + _arguments \ + '(-h -help)'{-h,-help}'[display the help screen]' \ + '(-v -version)'{-v,-version}'[print version information and exit]' \ + '(-l -list)'{-l,-list}'[list all available targets in buildfile (excluding targets that have their hidden attribute set to true)]' \ + '(-q -quiet)'{-q,-quiet}'[quiet operation, no output at all]' \ + '-verbose[verbose, give some more output]' \ + '-debug[output debug information]' \ + '-logfile [use given file for log]:file:_files' \ + '-D[set the property to the specified value to be used in the buildfile]' \ + '-find []:file:_files' \ + '-buildfile [specify an alternate buildfile name. Default is build.xml]:file:_files' \ + '-logger [specify an alternate logger. Default is phing.listener.DefaultLogger. Other options include phing.listener.NoBannerLogger, phing.listener.AnsiColorLogger, phing.listener.XmlLogger, phing.listener.TargetLogger and phing.listener.HtmlColorLogger]' \ + '-propertyfile [load properties from the specified file]:file:_files' \ + '(-v --version)'{-v,--version}'[show version]' \ + '1: :->targets' \ + '*:: :->args' \ + && ret=0 + + case $state in + targets) + local buildfile; buildfile=build.xml + if [[ ! -f $buildfile ]] + then + ret=0 + else + local targets; targets=($(sed -nE "/ +# +# ------------------------------------------------------------------------------ + + +local -a command_options +command_options=( + '--version[Show the program version and exit]' + '--filter[Set the filter, e.g. installed]' + "--root[Set the install root, e.g. '/' or '/mnt/ltsp']" + '(-n --nowait)'{-n,--nowait}'[Exit without waiting for actions to complete]' + '(-y --noninteractive)'{-g,--noninteractive}'[Install the packages without asking for confirmation]' + '--background[Run the command using idle network bandwidth and also using less power]' + '(-p --plain)'{-p,--plain}'[Print to screen a machine readable output, rather than using animated widgets]' + '(-c --cache-age)'{-c,--cache-age}"[The maximum metadata cache age. Use -1 for 'never'.]" + '(-h --help)'{-h,--help}'[Show help options.]' + '(-v --verbose)'{-v,--verbose}'[Show debugging information for all files]' +) + +local -a actions +actions=( + 'accept-eula' + 'get-roles' + 'get-distro-upgrades' + 'get-categories' + 'get-actions' + 'get-groups' + 'get-filters' + 'get-transactions' + 'get-time' + 'search' + 'install' + 'install-local' + 'download' + 'remove' + 'update' + 'refresh' + 'resolve' + 'get-updates' + 'get-depends' + 'get-requires' + 'get-details' + 'get-files' + 'get-update-detail' + 'get-packages' + 'repo-list' + 'repo-enable' + 'repo-disable' + 'repo-set-data' + 'what-provides' + 'upgrade-system' +) + +local context state line expl cmd +local -A opt_args + +integer i=2 +while (( i < $#words )); do + case "$words[$i]" in + -*) + # skip option + (( i++ )) + continue + ;; + esac + + if [[ -z "$cmd" ]]; then + cmd="$words[$i]" + words[$i]=() + (( CURRENT-- )) + fi + (( i++ )) +done + +if [[ -z "$cmd" ]] +then + _arguments -s -w : $command_options \ + ":action:($actions)" + return +fi + +case "$cmd" in + search) + _arguments : $command_options \ + ':type:(name details group file)' \ + ':data: :' + ;; + refresh) + _arguments -s -w : $command_options \ + '--force' + ;; + *) + _arguments -s -w : $command_options + ;; +esac +return 1 + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_play b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_play new file mode 100644 index 00000000..6b35899b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_play @@ -0,0 +1,190 @@ +#compdef play +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Play! framework 1.2.2 (https://www.playframework.com/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# * Mario Fernandez (https://github.com/sirech) +# +# ------------------------------------------------------------------------------ + + +_play() { + local context curcontext="$curcontext" state line + typeset -A opt_args + + local ret=1 + + _arguments -C \ + '1: :_play_cmds' \ + '*::arg:->args' \ + && ret=0 + + case $state in + (args) + curcontext="${curcontext%:*:*}:play-cmd-$words[1]:" + case $line[1] in + (build-module|list-modules|lm|check|id) + _message 'no more arguments' && ret=0 + ;; + (dependencies|deps) + _arguments \ + '1:: :_play_apps' \ + '(--debug)--debug[Debug mode (even more information logged than in verbose mode)]' \ + '(--jpda)--jpda[Listen for JPDA connection. The process will be suspended until a client is plugged to the JPDA port.]' \ + '(--sync)--sync[Keep lib/ and modules/ directory synced. Delete unknown dependencies.]' \ + '(--verbose)--verbose[Verbose Mode]' \ + && ret=0 + ;; + (clean|javadoc|jd|out|pid|secret|stop) + _arguments '1:: :_play_apps' && ret=0 + ;; + (help) + _arguments '1: :_play_cmds -F "(cp deps ec idea jd st lm nb nm help antify evolutions evolutions:apply evolutions:markApplied evolutions:resolve)"' && ret=0 + ;; + (status|st) + _arguments \ + '1:: :_play_apps' \ + '(--url)--url[If you want to monitor an application running on a remote server, specify the application URL using this option]:URL:_urls' \ + '(--secret)--secret[You can provide your own secret key using this option]:Secret key' \ + && ret=0 + ;; + (new) + _arguments \ + '1: :_play_apps' \ + '(--with)--with[Automatically enable this set of module for the newly created application]:Modules list:_play_modules_list' \ + && ret=0 + ;; + (install) + _arguments '1:Play! module:_play_modules_dash_versions' && ret=0 + ;; + (new-module) + _arguments '1:Module directory:_files -/' && ret=0 + ;; + (test|precompile|run|start|war|auto-test|classpath|cp|eclipsify|ec|idealize|idea|modules|netbeansify|nb) + local cmd_args; cmd_args=( + '1:: :_play_apps' + '(--deps)--deps[Resolve and install dependencies before running the command]' + ) + case $line[1] in + (precompile|run|start|restart|war) + local app_dir="$line[2]" + [[ -d "$app_dir" ]] || app_dir=. + [[ -f "$app_dir/conf/application.conf" ]] && cmd_args+=('--'${(u)${(M)$(<$app_dir/conf/application.conf):#%*}%%.*}'[Use this ID to run the application (override the default framework ID)]') + ;| + (test|run) + cmd_args+=('(-f)-f[Disable the JPDA port checking and force the jpda.port value]') + ;| + (war) + cmd_args+=( + '(-o --output)'{-o,--output}'[The path where the WAR directory will be created. The contents of this directory will first be deleted]:output directory:_files -/' + '(--zip)--zip[By default, the script creates an exploded WAR. If you want a zipped archive, specify the --zip option]' + '(--exclude)--exclude[Excludes a list of colon separated directories]:excluded directories list:_play_colon_dirs_list' + ) + ;| + (test|run|start|restart|war) + cmd_args+=('*:Java option') + ;; + esac + _arguments "$cmd_args[@]" && ret=0 + ;; + *) + _call_function ret _play_cmd_$words[1] && ret=0 + (( ret )) && _message 'no more arguments' + ;; + esac + ;; + esac +} + +# FIXME Completes only core commands, some modules add commands too (eg Maven). Where do we get them ? +# FIXME Parse 'play help' and 'play help ' (for aliases) instead of hard-coding. +(( $+functions[_play_cmds] )) || +_play_cmds() { + local commands; commands=( + 'antify:Create a build.xml file for this project' + 'auto-test:Automatically run all application tests' + 'build-module:Build and package a module' + 'check:Check for a release newer than the current one' + {classpath,cp}':Display the computed classpath' + 'clean:Delete temporary files (including the bytecode cache)' + {dependencies,deps}':Resolve and retrieve project dependencies' + {eclipsify,ec}':Create all Eclipse configuration files' + 'evolutions:Run the evolution check' + 'evolutions\:apply:Automatically apply pending evolutions' + 'evolutions\:mark:AppliedMark pending evolutions as manually applied' + 'evolutions\:resolve:Resolve partially applied evolution' + 'help:Display help on a specific command' + 'id:Define the framework ID' + {idealize,idea}':Create all IntelliJ Idea configuration files' + 'install:Install a module' + {javadoc,jd}':Generate your application Javadoc' + {list-modules,lm}':List modules available from the central modules repository' + 'modules:Display the computed modules list' + {netbeansify,nb}':Create all NetBeans configuration files' + 'new:Create a new application' + {new-module,nm}':Create a module' + 'out:Follow logs/system.out file' + 'pid:Show the PID of the running application' + 'precompile:Precompile all Java sources and templates to speed up application start-up' + 'restart:Restart the running application' + 'run:Run the application in the current shell' + 'secret:Generate a new secret key' + 'start:Start the application in the background' + {status,st}':Display the running application status' + 'stop:Stop the running application' + 'test:Run the application in test mode in the current shell' + 'war:Export the application as a standalone WAR archive' + ) + _describe -t commands 'Play! command' commands "$@" +} + +(( $+functions[_play_apps] )) || +_play_apps() { + _wanted application expl 'Play! application directory' _files -/ +} + +(( $+functions[_play_modules] )) || +_play_modules() { + local modules; modules=(${(ps:,:)${${${(S)${(f)$(_call_program modules $service list-modules)}//\]*\[/,}%%\]*}##*\[}}) + _describe -t modules 'Play! module' modules "$@" +} + +(( $+functions[_play_modules_dash_versions] )) || +_play_modules_dash_versions() { + local ret=1 + if compset -P '*-'; then + local versions; versions=(${(ps:,:)${${${${${(f)$(_call_program versions $service list-modules)}##*${IPREFIX%-}\]}#*Versions:}%%"~"*}//[[:space:]]/}}) + _describe -t module-versions "${IPREFIX%-} module versions" versions && ret=0 + else + _wanted modules expl 'Play! module' _play_modules -qS- && ret=0 + fi +} + +(( $+functions[_play_modules_list] )) || +_play_modules_list() { + compset -P '*,'; compset -S ',*' + _wanted module-list expl 'Play! modules list' _play_modules -qS, +} + +(( $+functions[_play_colon_dirs_list] )) || +_play_colon_dirs_list() { + compset -P '*:'; compset -S ':*' + _wanted directories-list expl 'Directories list' _files -/ -qS: +} + +_play "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_pm2 b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_pm2 new file mode 100644 index 00000000..8a3b0f28 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_pm2 @@ -0,0 +1,370 @@ +#compdef pm2 +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for pm2 5.2.2 (https://pm2.keymetrics.io/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Myoungdo Park +# * Shohei Yoshida +# +# ------------------------------------------------------------------------------ + +_pm2() { + typeset -A opt_args + local context state line + + local curcontext="$curcontext" + + local ret=1 + + _arguments -C \ + '(- *)'{-v,-V,--version}'[print pm2 version]' \ + '(-s --silent)'{-s,--silent}'[hide all messages]' \ + '--ext[watch only this file extension]:extension' \ + '(-n --name)'{-n,--name}'[set a name for the process in the process list]:name' \ + '(-m --mini-list)'{-m,--mini-list}'[display a compacted list without formatting]' \ + '--interpreter[set a specific interpreter to use for executing app(default: node)]:prog' \ + '(--interpreter-args --node-args)'{--interpreter-args,--node-args}'[set arguments to pass to the interpreter]:args' \ + '(-o --output)'{-o,--output}'[specify log file for stdout]: :_files' \ + '(-e --error)'{-e,--error}'[specify log file for stderr]: :_files' \ + '(-l --log)'{-l,--log}'[specify log file which gathers both stdout and stderr]' \ + '--filter-env[filter out outgoing global values that contain provided strings]:envs' \ + '--log-type[specify log output style]: :(raw json)' \ + '--log-date-format[specify log output style]:format' \ + '--time[enable time logging]' \ + '--disable-logs[disable all logs storage]' \ + '*--env[specify which set of environment variables from ecosystem file must be injected]:env' \ + '(-a --update-env)'{-a,--update-env}'[force and update of the environment with restart/reload]' \ + '(-f --force)'{-f,--force}'[force actions]' \ + '(-i --instances)'{-i,--instances}'[launch number instances]:num' \ + '--parallel[number of parallel actions]:num' \ + '--shutdown-with-message[shutdown an application with process.send("shutdown") instead of process.kill(pid, SIGINT)]' \ + '(-p --pid)'{-p,--pid}'[specify pid file]: :_files' \ + '(-k --kill-timeout)'{-k,--kill-timeout}'[delay before sending final SIGKILL signal to process]:delay' \ + '--listen-timeout[listen timeout an application reload]:delay' \ + '--max-memory-restart[restart the app if an amount of memory is exceeded (in bytes)]:bytes' \ + '--restart-delay[specify a delay between restarts(in milliseconds)]:delay' \ + '--exp-backoff-restart-delay[specify a delay between restarts(in milliseconds)]:delay' \ + '(-x --execute-command)'{-e,--execute-command}'[execute a program using fork system]' \ + '--max-restarts[only start the script COUNT times]:count' \ + '(-u --user)'{-u,--user}'[define user when generating startup script]:username' \ + '--uid[run target script with rights]:uid' \ + '--gid[run target script with rights]:gui' \ + '--namespace[start application within specified namespace]:namespace' \ + '--cwd[run target script from path ]:cwd:_paths -/' \ + '--hp[define home path when generating startup script]: :_paths -/' \ + '--wait-ip[override systemd script to wait for full internet connectivity to launch pm2]' \ + '--service-name[define service name when generating startup script]' \ + '(-c --cron --cron-restart)'{-c,--cron,--cron-restart}'[restart a running process based on a cron pattern]:pattern' \ + '(-w --write)'{-w,--write}'[write configuration in local folder]' \ + '--no-daemon[run pm2 daemon in the foreground if it does not exist already]' \ + '(--disable-source-map-support --source-map-support)--source-map-support[force source map support]' \ + '--only[with json declaration, allow to only act on one application]:app' \ + '(--disable-source-map-support --source-map-support)--disable-source-map-support[force disable source map support]' \ + '--wait-ready[ask pm2 to wait for ready event from your app]' \ + '--merge-logs[merge logs from different instances but keep error and out separated]' \ + '*--watch[watch application folder for changes]: :_files -/' \ + '*--ignore-watch[list of paths to ignore]: :_files' \ + '--no-color[skip colors]' \ + '--no-vizion[start an app without vizion feature]' \ + '--np-autorestart[start an app without automatic restart]' \ + '--no-treekill[Only kill the main process, not detached children]' \ + '--no-pmx[start an app without pmx]' \ + '--no-automation[start an app without automation]' \ + '(--disable-trace --trace)--trace[enable transaction tracing with km]' \ + '(--disable-trace --trace)--disable-trace[disable transaction tracing with km]' \ + "--sort[sort process according to field's]:field_name" \ + '--attach[attach logging after your start/restart/stop/reload]' \ + '--v8[enable v8 data collecting]' \ + '--event-loop-inspector[enable event-loop-inspector dump in pmx]' \ + '--deep-monitoring[enable all monitoring tools]' \ + '(- *)'{-h,--help}'[output usage information]' \ + '1: :_pm2_subcommands' \ + '*:: :->subcmds' && return 0 + + case "$state" in + (subcmds) + case $words[1] in + (start) + _arguments \ + '--watch[watch folder for changes]' \ + '--fresh[Rebuild Dockerfile]' \ + '--daemon[Run container in Daemon mode(debug purposes)]' \ + '--container[Start application in container mode]' \ + '--dist[--with-container; change local Dockerfile to containerize all files in current directory]' \ + '--image-name[with --dist; set the exported image name]:name' \ + '--node-version[with --container, set a specific major Node.js version]:version' \ + '--dockerdaemon[for debugging purpose]' \ + '(- *)'{-h,--help}'[output usage information]' \ + '*: :_pm2_id_namespace_file' \ + && ret=0 + ;; + (trigger) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '1: :_pm2_id_names' \ + && ret=0 + ;; + (deploy|startOrRestart|startOrReload|startOrGracefulReload) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '1: :_files -g "*.json"' \ + && ret=0 + ;; + (stop|restart) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '--watch[Stop watching folder for changes]' \ + '*: :_pm2_id_namespace_all' \ + && ret=0 + ;; + (reload|delete|reset) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '*: :_pm2_id_namespace_all' \ + && ret=0 + ;; + (module:install) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '--tarball[is local tarball]' \ + '--install[run yarn install before starting module]' \ + '--docker[is docker container]' \ + '--v1[install module in v1 manner(do not use it)]' \ + '--safe[keep module backup, if new module fail = restore with previous]:time' \ + && ret=0 + ;; + (publish|module:publish) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '--npm[publish on npm]' \ + '*: :_files -/' \ + && ret=0 + ;; + (link) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '--info-node[set url info node]:url' \ + && ret=0 + ;; + (plus) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '--info-node[set url info node]:url' \ + '(-d --discrete)'{-d,--discrete}'[silent mode]' \ + '(-a --install-all)'{-a,--install-all}'[install all modules (force yes)]' \ + && ret=0 + ;; + (dump|save) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '--force[force deletion of dump file even if empty]' \ + && ret=0 + ;; + (send|attach|describe|env) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '1: :_pm2_id_names' \ + && ret=0 + ;; + (slist|sysinfos) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '--tree[show as tree]' \ + && ret=0 + ;; + (logs) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '--json[json log output]' \ + '--format[formatted log output]' \ + '--raw[raw output]' \ + '--err[only shows error output]' \ + '--out[only shows standard output]' \ + '--line[output the last N lines, instead of the last 15 by default]:lines' \ + '--timestamp[add timestamps(default format YYYY-MM-DD-HH:mm:ss)]:format' \ + '--nostream[print logs without launching the log stream]' \ + '*--highlight[highlights the given value]' \ + '1: :_pm2_id_namespace' \ + && ret=0 + ;; + (serve) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '--port[specify port to listen to]:port' \ + '--spa[always serving index.html on inexistent sub path]' \ + '--basic-auth-username[set basic auth username]:username' \ + '--basic-auth-password[set basic auth password]:password' \ + '--monitor[frontend app monitoring]:app' \ + '*: :_files -/' \ + && ret=0 + ;; + (*) + _arguments \ + '(- *)'{-h,--help}'[output usage information]' \ + '*: :_files' \ + && ret=0 + ;; + esac + ;; + esac + + return ret +} + +(( $+functions[_pm2_subcommands] )) || +_pm2_subcommands() { + local -a subcommands=( + "start:start and daemonize an app" + "trigger:trigger process action" + "deploy:deploy your json" + "startOrRestart:start or restart JSON file" + "startOrReload:start or gracefully reload JSON file" + "pid:return pid of [app_name] or all" + "create:return pid of [app_name] or all" + "startOrGracefulReload:start or gracefully reload JSON file" + "stop:stop a process" + "restart:restart a process" + "scale:scale up/down a process in cluster mode depending on total_number param" + "profile\:mem:Sample PM2 heap memory" + "profile\:cpu:Profile PM2 cpu" + "reload:reload processes (note that its for app using HTTP/HTTPS)" + "id:get process id by name" + "inspect:inspect a process" + "delete:stop and delete a process from pm2 process list" + "sendSignal:send a system signal to the target process" + "ping:ping pm2 daemon - if not up it will launch it" + "updatePM2:update in-memory PM2 with local PM2" + "update:update in-memory PM2 with local PM2" + "install:install or update a module and run it forever" + "module\:install:install or update a module and run it forever" + "module\:update:update a module and run it forever" + "module\:generate:Generate a sample module in current folder" + "uninstall:stop and uninstall a module" + "module\:uninstall:stop and uninstall a module" + "package:Check & Package TAR type module" + "publish:Publish the module you are currently on" + "module\:publish:Publish the module you are currently on" + "set:sets the specified config " + "multiset:multiset eg \"key1 val1 key2 val2\"" + "get:get value for " + "conf:get / set module config values" + "config:get / set module config values" + "unset:clears the specified config " + "report:give a full pm2 report for https://github.com/Unitech/pm2/issues" + "link:link with the pm2 monitoring dashboard" + "unlink:unlink with the pm2 monitoring dashboard" + "monitor:monitor target process" + "unmonitor:unmonitor target process" + "open:open the pm2 monitoring dashboard" + "plus:enable pm2 plus" + "login:Login to pm2 plus" + "logout:Logout from pm2 plus" + "dump:dump all processes for resurrecting them later" + "save:dump all processes for resurrecting them later" + "cleardump:Create empty dump file" + "send:send stdin to " + "attach:attach stdin/stdout to application identified by " + "resurrect:resurrect previously dumped processes" + "unstartup:disable the pm2 startup hook" + "startup:enable the pm2 startup hook" + "logrotate:copy default logrotate configuration" + "ecosystem:generate a process conf file" + "init:generate a process conf file" + "reset:reset counters for process" + "describe:describe all parameters of a process" + "desc:describe all parameters of a process" + "info:describe all parameters of a process" + "show:describe all parameters of a process" + "env:list all environment variables of a process id" + "list:list all processes" + "l:list all processes" + "ps:list all processes" + "status:list all processes" + "jlist:list all processes in JSON format" + "sysmonit:start system monitoring daemon" + "slist:list system infos in JSON" + "sysinfos:list system infos in JSON" + "prettylist:print json in a prettified JSON" + "monit:launch termcaps monitoring" + "imonit:launch legacy termcaps monitoring" + "dashboard:launch dashboard with monitoring and logs" + "dash:launch dashboard with monitoring and logs" + "flush:flush logs" + "reloadLogs:reload all logs" + "logs:stream logs file. Default stream all logs" + "kill:kill daemon" + "pull:updates repository for a given app" + "forward:updates repository to the next commit for a given app" + "backward:downgrades repository to the previous commit for a given app" + "deepUpdate:performs a deep update of PM2" + "serve:serve a directory over http via port" + "autoinstall:auto install" + "examples:display pm2 usage examples" + ) + + _describe -t subcommands 'subcommand' subcommands "$@" +} + +(( $+functions[_pm2_id_names] )) || +_pm2_id_names() { + local app_list=$(pm2 list -m) + local -a names=(${(@f)"$(echo $app_list | awk '/^\+---/{sub("+--- ", ""); print}')"}) + local -a ids=(${(@f)"$(echo $app_list | awk '/^pm2 id/{sub("pm2 id :", ""); print}')"}) + + if (( ${#ids} > 0 )); then + local -a id_names + for i in {1..${#ids}}; do + id_names+=( "${ids[i]}:${names[i]}" ) + done + + _describe 'id' id_names + fi +} + +(( $+functions[_pm2_namespaces] )) || +_pm2_namespaces() { + local -a namespaces=(${(@f)"$(pm2 list -m | awk '/^namespace :/{ print $3 }')"}) + if (( ${#namespaces} > 0 )); then + _values 'namespace' $namespaces + fi +} + +(( $+functions[_pm2_id_namespace] )) || +_pm2_id_namespace() { + _alternative \ + 'ids:id:_pm2_id_names' \ + 'namespaces:namespace:_pm2_namespaces' +} + +(( $+functions[_pm2_id_namespace_all] )) || +_pm2_id_namespace_all() { + _alternative \ + 'ids:id:_pm2_id_names' \ + 'namespaces:namespace:_pm2_namespaces' \ + 'all:all:(all)' +} + +(( $+functions[_pm2_id_namespace_file] )) || +_pm2_id_namespace_file() { + _alternative \ + 'ids:id:_pm2_id_names' \ + 'namespaces:namespace:_pm2_namespaces' \ + 'files:file:_files' +} + +_pm2 "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: + +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_port b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_port new file mode 100644 index 00000000..8a257ec1 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_port @@ -0,0 +1,291 @@ +#compdef port +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for MacPorts (https://www.macports.org/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Matt Cable +# * Sorin Ionescu +# * Aljaž Srebrnič +# ----------------------------------------------------------------------------- +# License +# ------- +# +# Copyright (c) 2016, Matt Cable, Sorin Ionescu, Aljaž Srebrnič +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# ------------------------------------------------------------------------------ + +_port() { + local -a revupgrade_options select_options \ + pseudo_common pseudo_advanced port_prefix + + local port_path=$(which port) + port_prefix=${port_path%/bin/port} + + pseudo_common=(all current active inactive actinact installed uninstalled outdated + obsolete requested unrequested leaves rleaves) + + pseudo_advanced=('variants:' 'variant:' 'description:' 'depends:' + 'depends_lib:' 'depends_run:' 'depends_build:' 'depends_fetch:' 'depends_extract:' + 'portdir:' 'homepage:' 'epoch:' 'platforms:' 'platform:' 'name:' 'long_description:' + 'maintainers:' 'maintainer:' 'categories:' 'category:' 'version:' 'revision:' 'license:') + + select_options=( + '--summary:Display summary of selected options' + '--list:List available versions for the group' + '--set:Select the given version for the group' + '--show:Show which version is currently selected for the group (default if none given)' + ) + + revupgrade_options=('--id-loadcmd-check:Run more checks against a special loadcommand in Mach-O binaries') + + _arguments -s -C \ + '-v[Verbose mode (generate verbose messages)]' \ + '-d[Debug mode (generate debugging messages, implies -v)]' \ + '-q[Quiet mode (suppress messages)]' \ + "-n[Don't upgrade dependencies (affects upgrade and install)]" \ + "-R[Also upgrade dependents (only affects upgrade) - note that this does not upgrade dependents' dependencies]" \ + '-u[Uninstall non-active ports when upgrading and uninstalling]' \ + '-f[Force mode (ignore state file)]' \ + '-o[Honor state files even if the Portfile has been modified since (called -o because it used to mean "older")]' \ + '-s[Source-only mode (build and install from source, do not attempt to fetch binary archives)]' \ + '-b[Binary-only mode (build and install from binary archives, ignore source, abort if no archive available)]' \ + '-c[Autoclean mode (execute clean after install)]' \ + "-k[Keep mode (don't autoclean after install)]" \ + '-D[Specify portdir]' \ + '-F[Read and process the file of commands specified by the argument.]' \ + '-p[Despite any errors encountered, proceed to process multiple ports and commands.]' \ + '-y[Perform a dry run.]' \ + '-t[Enable trace mode debug facilities on platforms that support it (macOS).]' \ + "1:Port actions:_port_actions" \ + '::Per-action arguments:_port_dispatch' \ + && return 0 +} + +(( $+functions[_port_actions] )) || +_port_actions() { + local -a actions + actions=( + 'activate:Activate the given ports' + 'archive:Archive the given ports, i.e. install the port image but do not activate' + 'archivefetch:Fetch archive for the given ports' + 'build:Build the given ports' + 'bump:Update the outdated checksums of a Portfile' + 'cat:Writes the Portfiles of the given ports to stdout' + 'checksum:Compares the checksums for the downloaded files of the given ports' + 'clean:Removes files associated with the given ports' + 'configure:Configure the given ports' + 'contents:Returns a list of files installed by given ports' + 'deactivate:Deactivates the given ports' + 'dependents:Returns a list of installed dependents for each of the given ports' + 'deps:Display a dependency listing for the given ports' + 'destroot:Destroot the given ports' + 'diagnose:Detects common issues' + 'dir:Returns the directories of the given ports' + 'distcheck:Checks if the given ports can be fetched from all of its master_sites' + 'distfiles:Returns a list of distfiles for the given port' + 'dmg:Creates a dmg for each of the given ports' + 'dpkg:Creates a dpkg for each of the given ports' + 'echo:Returns the list of ports the argument expands to' + 'edit:Edit given ports' + 'extract:Extract the downloaded files of the given ports' + 'fetch:Downloaded distfiles for the given ports' + 'file:Returns the path to the Portfile for each of the given ports' + 'gohome:Opens the homepages of the given ports in your browser' + 'help:Displays short help texts for the given actions' + 'info:Returns information about the given ports ' + 'install:Installs the given ports' + 'installed:List installed versions of the given port, or all installed ports if no port is given' + 'lint:Checks if the Portfile is lint-free for each of the given ports' + 'list:List the available version for each of the given ports' + 'livecheck:Checks if a new version of the software is available' + 'load:Interface to launchctl(1) for ports providing startup items' + 'location:Returns the install location for each of the given ports' + 'log:Shows main log for given ports' + 'logfile:Returns the log file path for each of the given ports' + 'mdmg:Creates a dmg containing an mpkg for each of the given ports and their dependencies' + 'mirror:Fetches distfiles for the given ports' + 'mpkg:Creates an mpkg for each of the given ports and their dependencies' + 'notes:Displays informational notes for each of the given ports' + 'outdated:Returns a list of outdated ports' + 'patch:Applies patches to each of the given ports' + 'pkg:Creates a pkg for each of the given ports' + 'platform:Returns the current platform that port is running on' + 'provides:Return which port provides each of the files given' + 'rdependents:Recursive version of dependents' + 'rdeps:Display a recursive dependency listing for the given ports' + 'reclaim:Reclaims disk space' + 'rev-upgrade:Scan for broken binaries in the installed ports and rebuild them as needed' + 'rpm:Creates a rpm for each of the given ports' + 'search:Search for a port' + 'select:Select between multiple versions of a versioned port' + 'selfupdate:Upgrade MacPorts itself and run the sync target' + 'setrequested:Marks each of the given ports as requested' + 'space:Show the disk space used by the given ports' + 'srpm:Creates a srpm for each of the given ports' + 'sync:Synchronize the set of Portfiles' + 'test:Run tests on each of the given ports' + 'unarchive:Unarchive the destroot of the given ports from installed images' + 'uninstall:Uninstall the given ports' + 'unload:Interface to launchctl(1) for ports providing startup items' + 'unsetrequested:Marks each of the given ports as unrequested' + 'upgrade:Upgrades the given ports to the latest version' + 'url:Returns the URL for each of the given ports' + 'usage:Returns basic usage of the port command' + 'variants:Returns a list of variants provided by the given ports, with descriptions if present' + 'version:Returns the version of MacPorts' + 'work:Returns the path to the work directory for each of the given ports' + ) + + _describe -t actions 'actions' actions +} + +_port_dispatch() { + local cache_policy + zstyle -s ":completion:${curcontext}:" cache-policy cache_policy + zstyle ":completion:${curcontext}:" cache-policy ${cache_policy:-_port_caching_policy} + + case "$words[2]" in + provides) + _files + ;; + search) + _message 'pattern' + ;; + help) + _port_actions + ;; + select) + _call_function - _port_select + ;; + contents|deactivate|setrequested|space|uninstall|unsetrequested) + # Cache the list of installed ports. + if ( [[ ${+_port_installed_packages} -eq 0 ]] || _cache_invalid PORT_INSTALLED_PACKAGES ) && + ! _retrieve_cache PORT_INSTALLED_PACKAGES; + then + _port_installed_packages=( $(_call_program path-all "port -q echo installed") ) + _store_cache PORT_INSTALLED_PACKAGES _port_installed_packages + fi + _alternative \ + "ports:Installed ports:($_port_installed_packages)" \ + "pseudo-common:Common Pseudo-portnames:($pseudo_common)" \ + "pseudo-advanced:Advanced Pseudo-portnames:($pseudo_advanced)" + ;; + upgrade) + # No good reason to actually cache outdated ports list + local outdated_packages + outdated_packages=( $(_call_program path-outdated "port -q echo outdated") ) + _alternative -- \ + "upgrade-options:Upgrade options:_port_upgrade_options" \ + "ports:Outdated ports:($outdated_packages)" \ + "pseudo-common:Common Pseudo-portnames:($pseudo_common)" \ + "pseudo-advanced:Advanced Pseudo-portnames:($pseudo_advanced)" + ;; + rev-upgrade) + if (( CURRENT == 3 )); then + _describe 'Rev-upgrade options' revupgrade_options + fi + ;; + outdated|sync) + # No need to complete anything more here. + return 0; + ;; + selfupdate) + _all_labels 'Selfupdate options' '--nosync' + ;; + *) + # Cache the list of all ports. + if ( [[ ${+_port_available_packages} -eq 0 ]] || _cache_invalid PORT_AVAILABLE_PACKAGES ) && + ! _retrieve_cache PORT_AVAILABLE_PACKAGES; + then + _port_available_packages=( $(_call_program path-all "port -q echo all") ) + _store_cache PORT_AVAILABLE_PACKAGES _port_available_packages + fi + _alternative \ + "ports:Available ports:($_port_available_packages)" \ + "pseudo-common:Common Pseudo-portnames:($pseudo_common)" \ + "pseudo-advanced:Advanced Pseudo-portnames:($pseudo_advanced)" + ;; + esac +} + +(( $+functions[_port_upgrade_options] )) || +_port_upgrade_options() { + local -a options + options=( + '--enforce-variants:Upgrade all given ports and their dependencies' + '--force:Ignore circumstances that would normally cause ports to be skipped' + '--no-replace:Do not automatically install ports that replace a new-obsolete port you have installed' + '--no-rev-upgrade:Do not run rev-upgrade after upgrading' + ) + + _describe -t options 'options' options +} + +_port_select() { + if (( CURRENT == 3 )); then + _describe 'Port select options' select_options + elif (( CURRENT == 4 )); then + local select_group=($port_prefix/etc/select/*(N:t)) + _describe "Port select groups" select_group + elif [[ $CURRENT -eq 5 && $words[3] == '--set' ]]; then + local select_variants + select_variants=("${(f)$(port select --list $words[4] | sed -e '1 d' -e 's/^[ \t]*//' -e 's/ (active)$//')}") + _describe "Port select group $words[4] variants" select_variants + fi +} + +_port_caching_policy() { + local reg_time comp_time check_file + + zmodload -F zsh/stat b:zstat 2> /dev/null + case "${1##*/}" in + PORT_INSTALLED_PACKAGES) + check_file=$port_prefix/var/macports/registry/registry.db + ;; + PORT_AVAILABLE_PACKAGES) + check_file=${$(port dir MacPorts)%/*/*}/PortIndex + ;; + esac + reg_time=$(zstat +mtime $check_file) + comp_time=$(zstat +mtime $1) + return $(( reg_time < comp_time )) +} + +_port "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_protoc b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_protoc new file mode 100644 index 00000000..e82c6068 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_protoc @@ -0,0 +1,90 @@ +#compdef protoc +# ------------------------------------------------------------------------------ +# Copyright (c) 2020 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for protoc 24.0(https://github.com/protocolbuffers/protobuf) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei YOSHIDA (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +__protoc_files() { + if compset -P '@'; then + _files + else + _files -g '*.proto' + fi +} + +_protoc() { + _arguments \ + '(- : *)'{-h,--help}'[Show summary of options]' \ + '(- : *)--version[Show version of program]' \ + '*'{-I,--proto_path}'=[Specify the directory which to search for imports]:import_dir:_files -/' \ + '--encode=[Read a text-format message of given type from stdin and write it in binary to stdout]:message_type' \ + '--deterministic_output[When using --encode, ensure map fields are deterministically ordered]' \ + '--decode=[Read a text-format message of given type from stdin and write it in binary to stdout]:message_type' \ + '--decode_raw[Read an arbitrary protocol message from stdin and write the raw tag/value pairs in text format to stdout]' \ + '--descriptor_set_in=[Specifies a delimited list of FILES each containing a FileDescriptorSet]:desc_in:_files' \ + {-o,--descriptor_set_out}'=[Writes a FileDescriptorSet to FILE]:desc_out:_files' \ + '--include_imports[When using --descriptor_set_out, also include all dependencies of the input files in the set]' \ + '--include_source_info[When using --descriptor_set_out, do not strip SourceCodeInfo from the FileDescriptorProto]' \ + '--retain_options[when using --descriptor_set_out, do not strip any options from the FileDescriptorProto]' \ + '--dependency_out=[Write a dependency output file in the format expected by make]:dep_out:_files' \ + '--error_format=[Set the format in which print errors]:error_format:(gcc msvc)' \ + '--fatal_warnings[Make warnings be fatal]' \ + '--print_free_field_numbers[Print the free field numbers of the messages]'\ + '--enable_codegen_trace[Enables tracing which parts of protoc are responsible for what codegen output]' \ + '--plugin=[Specifies a plugin executable to use]:plugin:_files' \ + '--cpp_out=[Generate C++ header and source]:out_dir:_files -/' \ + '--csharp_out=[Generate C# source file]:out_dir:_files -/' \ + '--java_out=[Generate Java source file]:out_dir:_files -/' \ + '--kotlin_out[Generate Kotlin file]:out_dir:_files -/' \ + '--js_out=[Generate JavaScript source]:out_dir:_files -/' \ + '--objc_out=[Generate Objective C header and source]:out_dir:_files -/' \ + '--php_out=[Generate PHP source file]:out_dir:_files -/' \ + '--python_out=[Generate Python source file]:out_dir:_files -/' \ + '--ruby_out=[Generate Ruby source file]:out_dir:_files -/' \ + '--rust_out=[Generate Rust sources]:out_dir:_files -/' \ + '*: :__protoc_files' +} + +_protoc "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_pygmentize b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_pygmentize new file mode 100644 index 00000000..02e3600e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_pygmentize @@ -0,0 +1,149 @@ +#compdef pygmentize +# ------------------------------------------------------------------------------ +# Copyright (c) 2012 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for pygmentize 2.13.0 (https://github.com/pygments/pygments) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Hideo Hattori +# +# ------------------------------------------------------------------------------ + +_pygmentize() { + local context state line + + _arguments -s -S \ + '(-g)-l[Specify the lexer to use]:LEXER:_pygmentize_get_lexers' \ + '(-l)-g[Guess the lexer from the file contents]' \ + '-F[Add a filter to the token stream]:STYLE:_pygmentize_get_filters' \ + '-f[Specify the formatter to use]:FORMATTER:_pygmentize_get_formatters' \ + '-O[Give options to the lexer and formatter as a comma-separated list of key-value pairs]' \ + '-P[Give a single option to the lexer and formatter]' \ + '-o[output file]:FILENAME:_files' \ + '-v[Print a detailed traceback on unhandled exceptions]' \ + '-s[Process lines one at a time until EOF]' \ + '-x[Allow custom lexers and formatters to be loaded from a .py file]' \ + '--json[Output as JSON]' \ + '(-L -o -F -H -g -l -N)-S[Print style definitions for STYLE for a formatter given with -f]:STYLE:_pygmentize_get_styles' \ + '-L[lists lexers, formatters, styles or filters]:args:(lexers formatters styles filters)' \ + '(-L -f -o -S -F -H -g -l)-N[guesses and prints out a lexer name based solely on given filename]:FILENAME:_files' \ + '-C[Like -N, but print out a lexer name based solely on a given content from standard input]' \ + '-H[prints detailed help for the object of type ]:' \ + '-a[Formatter-specific additional argument for the -S mode]:' \ + '(* -)-V[prints the package version]' \ + '(* -)'{-h,--help}'[prints help]' \ + '*:args:_files' +} + +_pygmentize_get_filters() { + local cache_policy + zstyle -s ":completion:${curcontext}:" cache-policy cache_policy + if [[ -z "$cache_policy" ]]; then + zstyle ":completion:${curcontext}:" cache-policy _pygmentize_caching_policy + fi + + if ( [[ ${+_pygmentize_filters} -eq 0 ]] || _cache_invalid pygmentize_filters ) \ + && ! _retrieve_cache pygmentize_filters; then + _pygmentize_filters=(${${(f)"$(pygmentize -L filters | grep '* ' | cut -c3- | sed -e 's/:$//')"}}) + _store_cache pygmentize_filters _pygmentize_filters + fi + + local expl + _wanted pygmentize_filters expl 'pygmentize filters' compadd -a _pygmentize_filters +} + +_pygmentize_get_formatters() { + local cache_policy + zstyle -s ":completion:${curcontext}:" cache-policy cache_policy + if [[ -z "$cache_policy" ]]; then + zstyle ":completion:${curcontext}:" cache-policy _pygmentize_caching_policy + fi + + if ( [[ ${+_pygmentize_formatter} -eq 0 ]] || _cache_invalid pygmentize_formatter ) \ + && ! _retrieve_cache pygmentize_formatter; then + _pygmentize_formatter=(${${(f)"$(pygmentize -L formatters | grep '* ' | cut -c3- | sed -e 's/, /\n/g' -e 's/:$//')"}}) + _store_cache pygmentize_formatter _pygmentize_formatter + fi + + local expl + _wanted pygmentize_formatter expl 'pygmentize formatters' compadd -a _pygmentize_formatter +} + +_pygmentize_get_lexers() { + local cache_policy + zstyle -s ":completion:${curcontext}:" cache-policy cache_policy + if [[ -z "$cache_policy" ]]; then + zstyle ":completion:${curcontext}:" cache-policy _pygmentize_caching_policy + fi + + if ( [[ ${+_pygmentize_lexer} -eq 0 ]] || _cache_invalid pygmentize_lexer ) \ + && ! _retrieve_cache pygmentize_lexer; then + _pygmentize_lexer=(${${(f)"$(pygmentize -L lexers | grep '* ' | cut -c3- | sed -e 's/, /\n/g' -e 's/:$//')"}}) + _store_cache pygmentize_lexer _pygmentize_lexer + fi + + local expl + _wanted pygmentize_lexer expl 'pygmentize lexers' compadd -a _pygmentize_lexer +} + +_pygmentize_get_styles() { + local cache_policy + zstyle -s ":completion:${curcontext}:" cache-policy cache_policy + if [[ -z "$cache_policy" ]]; then + zstyle ":completion:${curcontext}:" cache-policy _pygmentize_caching_policy + fi + + if ( [[ ${+_pygmentize_style} -eq 0 ]] || _cache_invalid pygmentize_style ) \ + && ! _retrieve_cache pygmentize_style; then + _pygmentize_style=(${${(f)"$(pygmentize -L styles | grep '* ' | cut -c3- | sed -e 's/:$//')"}}) + _store_cache pygmentize_style _pygmentize_style + fi + + local expl + _wanted pygmentize_style expl 'pygmentize styles' compadd -a _pygmentize_style +} + +_pygmentize_caching_policy() { + local -a oldp + oldp=( "$1"(Nmh+24) ) # 24 hour + (( $#oldp )) +} + +_pygmentize "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_qmk b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_qmk new file mode 100644 index 00000000..24f3368b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_qmk @@ -0,0 +1,404 @@ +#compdef qmk +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for QMK CLI (https://qmk.fm/). +# version: 1.1.1 +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * precondition (https://github.com/precondition) +# * undg (https://github.com/undg) +# * Shohei Yoshida(https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_qmk() { + local curcontext="$curcontext" state line ret=1 + typeset -A opt_args + + _arguments -C \ + '(- *)'{-h,--help}"[Print help text.]" \ + '(- *)'{-V,--version}"[Prints version information]" \ + '(-v --verbose)'{-v,--verbose}"[Make the logging more verbose]" \ + '--datetime-fmt[Format string for datetimes]:DATETIME_FMT' \ + '--log-fmt[Format string for printed log output]:LOG_FMT' \ + '--log-file-fmt[Format string for log file.]:LOG_FILE_FMT' \ + '--log-file-level[Logging level for log file]:(debug,info,warning,error,critical)' \ + '--log-file[File to write log messages to]:filename:_files' \ + '(--no-color --color)--color[Enable color in output]' \ + '(--no-color --color)--no-color[Disable color in output]' \ + '(--no-unicode --unicode)--unicode[Enable unicode loglevels]' \ + '(--no-unicode --unicode)--no-unicode[Disable unicode loglevels]' \ + '--interactive[Force interactive mode even when stdout is not a tty]' \ + '--config-file[The location for the configuration file]:filename:_files' \ + '1:commands:_qmk_commands' \ + '*::qmk commands:->args' && ret=0 + + case "$state" in + (args) + if (( $+functions[_qmk_${words[1]}] )); then + _qmk_${words[1]} && ret=0 + else + ret=0 + fi + ;; + esac + + return $ret +} + +(( $+functions[_qmk_commands] )) || +_qmk_commands() { + local -a commands=( + 'config:Read and write configuration settings' + 'clone:Clone a qmk_firmware fork' + 'console:Acquire debugging information from usb hid devices' + 'env:Prints environment information.' + 'setup:Setup your computer for qmk_firmware' + 'c2json:Creates a keymap.json from a keymap.c file' + 'cd:Go to QMK Home' + 'chibios-confmigrate:Generates a migrated ChibiOS configuration file, as a result of comparing the input against a reference' + 'clean:Clean the QMK firmware folder of build artifacts' + 'compile:Compile a QMK Firmware' + 'doctor:Basic QMK environment checks' + 'flash:QMK Flash' + 'generate-compilation-database:Create a compilation database' + 'generate-rgb-breathe-table:Generates an RGB Light breathing table header' + 'import-kbfirmware:Import kbfirmware json export' + 'import-keyboard:Import data driven keyboard' + 'import-keymap:Import data-driven keymap' + 'info:Keyboard information' + 'json2c:Creates a keymap.c from a QMK Configurator export' + 'lint:Check keyboard and keymap for common mistakes' + 'list-keyboards:List the keyboards currently defined within QMK' + 'list-keymaps:List the keymaps for a specific keyboard' + 'list-layouts:List the layouts for a specific keyboard' + 'new-keyboard:Create a new keyboard directory' + 'new-keymap:Creates a new keymap for the keyboard of your choosing' + 'painter-convert-graphics:Converts an input image to something QMK understands' + 'painter-make-font-image:Converts an input font to something QMK understands' + 'painter-convert-font-image:Converts an input font image to something QMK firmware understands' + 'via2json:Convert a VIA backup json to keymap.json format' + ) + + _describe -t commands 'qmk commands' commands +} + +(( $+functions[_qmk_config] )) || +_qmk_config() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-ro --read-only)'{-ro,--read-only}'[Operate in read-only mode]' \ + '(-a --all)'{-a,--all}'[Show all configuration options]' +} + +(( $+functions[_qmk_clone] )) || +_qmk_clone() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-b --branch)'{-b,--branch}'[The branch to clone]:branch' \ + '--baseurl[The URL all git operations start from]:baseurl' \ + '1:fork:_files' \ + '*::destination:_files -/' +} + +(( $+functions[_qmk_console] )) || +_qmk_console() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-w --wait)'{-w,--wait}'[How many seconds to wait between check]:seconds' \ + '(-t --timestamp)'{-t,--timestamp}'[Print the timestamp for received messages as well]' \ + '(-n --numeric)'{-n,--numeric}'[Show VID/PID instead of names]' \ + '(-l --list)'{-l,--list}'[List available hid_listen devices]' \ + '(-d --device)'{-d,--device}'[Device to select]' \ + '(--bootloaders --no-bootloaders)--bootloaders[Enable displaying bootloaders]' \ + '(--bootloaders --no-bootloaders)--no-bootloaders[Enable displaying bootloaders]' +} + +(( $+functions[_qmk_env] )) || +_qmk_env() { + _arguments \ + '(-h --help)'{-h,--help}'[show help message and exit]' +} + +(( $+functions[_qmk_setup] )) || +_qmk_setup() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-H --home)'{-H,--home}'[The location for QMK Firmware]: :_files -/' \ + '(-b --branch)'{-b,--branch}'[The branch to clone]:branch' \ + '--baseurl[The URL all git operations start from]:baseurl' \ + '(-y --yes -n --no)'{-y,--yes}'[Answer yes to all questions]' \ + '(-y --yes -n --no)'{-n,--no}'[Answer no to all questions]' \ + '*:: :_files' +} + +(( $+functions[_qmk_c2json] )) || +_qmk_c2json(){ + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-km --keymap)'{-km,--keymap}"[The keymap's name]:keymap" \ + '(-kb --keyboard)'{-kb,--keyboard}"[The keyboard's name]:keyboard" \ + '(-q --quiet)'{-q,--quiet}'[Quiet mode, only output error messages]' \ + '(-o --output)'{-o,--output}'[File to write to]: :_files' \ + "--no-cpp[Do not use 'cpp' keymap.c]" \ + '*: :_files' +} + +(( $+functions[_qmk_cd] )) || +_qmk_cd() { + _arguments \ + '(-h --help)'{-h,--help}'[show help message and exit]' +} + +(( $+functions[_qmk_chibios-confmigrate] )) || +_qmk_chibios-confmigrate() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-f --force)'{-f,--force}'[Re-migrates an already migrated file, even if it does not detect a full ChibiOS config]' \ + '(-d --delete)'{-d,--delete}'[If the file has no overrides, migration will delete the input file]' \ + '(-o --overwrite)'{-o,--overwrite}'[Overwrites the input file during migration]' \ + '(-r,--reference)'{-r,--reference}'[Specify the reference file to compare against]:reference' \ + '(-i --input)'{-i,--input}'[Specify input config file]: :_files' +} + +(( $+functions[_qmk_clean] )) || +_qmk_clean() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-a --all)'{-a,--all}'[Remove *.hex and *.bin files in the QMK root as well]' +} + +(( $+functions[_qmk_compile] )) || +_qmk_compile() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-c --clean)'{-c,--clean}'[Remove object files before compiling]' \ + \*{-e,--env}'[Set a variable to be passed to make]:env' \ + '(-j --parallel)'{-j,--parallel}'[Set the number of parallel make jobs; 0 means unlimited]' \ + '(-n --dry-run)'{-d,--dry-run}"[Don't actually build, just show the make command to be run]" \ + '(-km --keymap)'{-km,--keymap}'[The keymap to build a firmware for]:keymap' \ + '(-kb --keyboard)'{-kb,--keyboard}'[The keyboard to build a firmware for]:keyboard' \ + '*: :_files' +} + +(( $+functions[_qmk_doctor] )) || +_qmk_doctor() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-n --no -y --yes)'{-n,--no}'[Answer no to all questions]' \ + '(-n --no -y --yes)'{-y,--yes}'[Answer yes to all questions]' +} + +(( $+functions[_qmk_flash] )) || +_qmk_flash() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-c --clean)'{-c,--clean}'[Remove object files before compiling]' \ + \*{-e,--env}'[Set a variable to be passed to make]:env' \ + '(-j --parallel)'{-j,--parallel}'[Set the number of parallel make jobs; 0 means unlimited]' \ + '(-n --dry-run)'{-d,--dry-run}"[Don't actually build, just show the make command to be run]" \ + '(-km --keymap)'{-km,--keymap}'[The keymap to build a firmware for]:keymap' \ + '(-kb --keyboard)'{-kb,--keyboard}'[The keyboard to build a firmware for]:keyboard' \ + '(-m --mcu)'{-m,--mcu}'[The MCS name]:mcu' \ + '(-bl --bootloader)'{-bl,--bootloader}"[The flash command, corresponding to qmk's make options of bootloaders]:bootloader" \ + '(-b --bootloaders)'{-b,--bootloaders}'[List the available bootloaders]' \ + '*: :_files' +} + +(( $+functions[_qmk_generate-compilation-database] )) || +_qmk_generate-compilation-database() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-km --keymap)'{-km,--keymap}'[The keymap to build a firmware for]:keymap' \ + '(-kb --keyboard)'{-kb,--keyboard}'[The keyboard to build a firmware for]:keyboard' +} + +(( $+functions[_qmk_generate-rgb-breathe-table] )) || +_qmk_generate-rgb-breathe-table(){ + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-q --quiet)'{-q,--quiet}'[Quiet mode, only output error messages]' \ + '(-o --output)'{-o,--output}'[File to write to]: :_files' \ + '(-m --max)'{-m,--max}'[The breathing maximum value, from 0 to 255]:num' \ + '(-c --center)'{-c,--center}'[The breathing center value, from 1 to 2.7]:num' +} + +(( $+functions[_qmk_import-kbfirmware] )) || +_qmk_import-kbfirmware() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '*: :_files' +} + +(( $+functions[_qmk_import-keyboard] )) || +_qmk_import-keyboard() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '*: :_files' +} + +(( $+functions[_qmk_import-keymap] )) || +_qmk_import-keymap() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '*: :_files' +} + +(( $+functions[_qmk_info] )) || +_qmk_info() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-r --rules-mk)'{-r,--rules-mk}"[Render the parsed values of the keyboard's rules.mk file]" \ + '--ascii[Render layout box drawings in ASCII only]' \ + '(-f --format)'{-f,--format}'[Format to display the data]: :(friendly text json)' \ + '(-m --matrix)'{-m,--matrix}'[Render the layouts with matrix information]'\ + '(-l --layouts)'{-l,--layouts}'[Render the layouts]' \ + '(-km --keymap)'{-km,--keymap}'[Keymap to show info for(Optional)]:keymap' \ + '(-kb --keyboard)'{-kb,--keyboard}'[Keyboard to show info for]:keyboard' +} + +(( $+functions[_qmk_json2c] )) || +_qmk_json2c(){ + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-q --quiet)'{-q,--quiet}'[Quiet mode, only output error messages]' \ + '(-o --output)'{-o,--output}'[File to write to]: :_files' \ + '*: :_files' +} + +(( $+functions[_qmk_lint] )) || +_qmk_lint(){ + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '--all-km[Check all keymaps]' \ + '--all-kb[Check all keyboards]' \ + '(-km --keymap)'{-km,--keymap}'[The keymap to check]:keymap' \ + '(-kb --keyboard)'{-kb,--keyboard}'[Comma separated list of keyboards to check]:keyboards' \ + '--strict[Treat warnings as errors]' +} + +(( $+functions[_qmk_list-keyboards] )) || +_qmk_list-keyboards() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' +} + +(( $+functions[_qmk_list-keymaps] )) || +_qmk_list-keymaps() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-kb --keyboard)'{-kb,--keyboard}'[Specify keyboard name]:keyboard' +} + +(( $+functions[_qmk_list-layouts] )) || +_qmk_list-layouts() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-kb --keyboard)'{-kb,--keyboard}'[Specify keyboard name]:keyboard' +} + +(( $+functions[_qmk_new-keyboard] )) || +_qmk_new-keyboard() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-n --realname)'{-n,--realname}'[Specify your real name if you want to use that]:real_name' \ + '(-u --username)'{-u,--username}'[Specify your user name]:user_name' \ + '(-t --type)'{-t,--type}'[Specify the keyboard MCU type]:type' \ + '(-l --layout)'{-l,--layout}'[Community layout to bootstrap with]:layout' \ + '(-kb --keyboard)'{-kb,--keyboard}'[Specify the name for the new keyboard directory]:keyboard' +} + +(( $+functions[_qmk_new-keymap] )) || +_qmk_new-keymap() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-km --keymap)'{-km,--keymap}'[Specify the name for the keymap directory]:keymap' \ + '(-kb --keyboard)'{-kb,--keyboard}'[Specify keyboard name]:keyboard' +} + +(( $+functions[_qmk_painter-convert-graphics] )) || +_qmk_painter-convert-graphics() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-d --no-deltas)'{-d,--no-deltas}'[Disable the use of delta frames when encoding animations]' \ + '(-r --no-rle)'{-r,--no-rle}'[Disables the use of RLE when encoding images]' \ + '(-f --format)'{-f,--format}'[Output format]: :(pal256 pal16 pal4 pal2 mono256 mono16 mono4 mono2)' \ + '(-o --output)'{-o,--output}'[Specify output directory]: :_files -/' \ + '(-i --input)'{-i,--input}'[Specify input graphic file]: :_files' \ + '(-v --verbose)'{-v,--verbose}'[Turns on verbose output]' +} + +(( $+functions[_qmk_painter-make-font-image] )) || +_qmk_painter-make-font-image() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-a --no-aa)'{-a,--no-aa}'[Disable anti-aliasing on fonts]' \ + '(-u --unicode-glyphs)'{-u,--unicode-glyphs}'[Also generate the specified unicode glyphs]:unicode_glyphs' \ + '(-n --no-ascii)'{-n,--no-ascii}'[Disable output of the full ASCII character set, exporting only the glyphs specified]' \ + '(-s --size)'{-s,--size}'[Specify font size]:font_size' \ + '(-o --output)'{-o,--output}'[Specify output image path]: :_files' \ + '(-f --font)'{-f,--font}'[Specify input font file]: :_files' +} + +(( $+functions[_qmk_painter-convert-font-image] )) || +_qmk_painter-convert-font-image() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-r --no-rle)'{-r,--no-rle}'[Disables the use of RLE when encoding images]' \ + '(-f --format)'{-f,--format}'[Output format]: :(pal256 pal16 pal4 pal2 mono256 mono16 mono4 mono2)' \ + '(-u --unicode-glyphs)'{-u,--unicode-glyphs}'[Also generate the specified unicode glyphs]:unicode_glyphs' \ + '(-n --no-ascii)'{-n,--no-ascii}'[Disable output of the full ASCII character set, exporting only the glyphs specified]' \ + '(-o --output)'{-o,--output}'[Specify output directory]: :_files -/' \ + '(-i --input)'{-i,--input}'[Specify input graphic file]: :_files' +} + +(( $+functions[_qmk_via2json] )) || +_qmk_via2json() { + _arguments \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '(-l --layout)'{-l,--layout}"[The keymap's layout]" \ + '(-km --keymap)'{-km,--keymap}"[The keymap's name]" \ + '(-kb --keyboard)'{-kb,--keyboard}"[The keyboard's name]" \ + '(-q --quiet)'{-q,--quiet}'[Quiet mode, only output error message]' \ + '(-o --output)'{-o,--output}'[File to write to]: :_files' +} + +_qmk "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rails b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rails new file mode 100644 index 00000000..153e4df5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rails @@ -0,0 +1,538 @@ +#compdef rails +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Ruby on Rails 7.1.0 (https://rubyonrails.org/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Kazuya Takeshima (https://github.com/mitukiii) +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_rails() { + local context state state_descr line curcontext="$curcontext" + typeset -A opt_args + + local -a runtime_options rails_options + runtime_options=( + '(- *)'{-h,--help}'[Show this help message and quit]' + '(- *)'{-v,--version}'[Show Rails version and quit]' + ) + + runtime_options=( + '(-f --force)'{-f,--force}'[Overwrite files that already exist]' + '(-p --pretend)'{-p,--pretend}'[Run but do not make any changes]' + '(-q --quiet)'{-q,--quiet}'[Suppress status output]' + '(-s --skip)'{-s,--skip}'[Skip files that already exist]' + ) + + local ret=1 + + _arguments -C \ + $rails_options \ + '1: :_rails_subcommands' \ + '*:: :->command' && ret=0 + + case "$state" in + (command) + case $words[1] in + (new) + _rails_new && ret=0 + ;; + (generate|g|destroy|d) + _rails_generate && ret=0 + ;; + (console|c) + _arguments \ + '(- *)'{-h,--help}'[Show this help message and quit]' \ + '(-e --environment)'{-e,--environment=}'[The environment to run "console" in]:env:(test development production)' \ + '(-s --sandbox)'{-s,--sandbox}'[Rollback database modifications on exit]' \ + && ret=0 + ;; + (server|s) + _arguments \ + '(- *)'{-h,--help}'[Show this help message and quit]' \ + '(-e --environment)'{-e,--environment=}'[The environment to run "server" in]:env:(test development production)' \ + '(-p --port)'{-p,--port}'[Run Rails on the specified port]:port' \ + '(-b --binding)'{-b,--binding=}'[Bind Rails to the specified IP]:binding' \ + '(-c --config)'{-c,--config=}'[Use a custom rackup configuration]:config file:_files -g "*.ru"' \ + '(-d --daemon)'{-d,--daemon}'[Run server as a Daemon]' \ + '(-u --using)'{-u,--using=}'[Specify the Rack server used to run the application]:server:(thin puma webrick)' \ + '(-P --pid)'{-P,--pid=}'[Specify the PID file]:pid file:_files -g "*.pid"' \ + '(-C --dev-caching --no-dev-caching)'{-C,--dev-caching}'[Perform caching in development]' \ + '(-C --dev-caching --no-dev-caching)--no-dev-caching[Not perform caching in development]' \ + '--early-hints[Enable HTTP/2 early hints]' \ + '(--log-to-stdout --no-log-to-stdout)--log-to-stdout[Log to stdout]' \ + '(--log-to-stdout --no-log-to-stdout)--no-log-to-stdout[Not log to stdout]' \ + && ret=0 + ;; + (dbconsole|db) + _arguments \ + '(- *)'{-h,--help}'[Show this help message and quit]' \ + '(-e --environment)'{-e,--environment=}'[The environment to run "server" in]:env:(test development production)' \ + '(-p --include-password)'{-p,--include-password}'[Automatically provide the password from database.yml]' \ + '--mode=[Automatically put the sqlite3 database in the specified mode]:mode:(html list line column)' \ + '(--header --no-header)--header[Display header]' \ + '(--header --no-header)--no-header[Not display header]' \ + '(--db --database)'{--db=,--database=}'[Specify the database to use]:database:_files' \ + && ret=0 + ;; + (test|t|test:system) + _arguments \ + '(- *)'{-h,--help}'[Show this help message and quit]' \ + '--no-plugins[Bypass minitest plugin auto-loading]' \ + '(-s --seed)'{-s,--seed=}'[Sets random seed]:seed' \ + '(-v -verbose)'{-v,--verbose}'[Show progress processing files]' \ + '--show-skips[Show skipped at the end of run]' \ + \*{-n,--name=}'[Filter run on /regexp/ or string]:pattern' \ + *--exclude='[Exclude /regexp/ or string from run]:pattern' \ + \*{-S,--skip=}'[Skip reporting of certain types of results]' \ + '(-w --warnings)'{-w,--warnings}'[Run with Ruby warnings enabled]' \ + '(-e --environment)'{-e,--environment=}'[Run tests in the given environment]' \ + '(-b --backtrace)'{-b,--backtrace}'[Show the complete backtrace]' \ + '(-d --defer-output)'{-d,--defer-output}'[Output test failures and errors after the test run]' \ + '(-f --fail-fast)'{-f,--fail-fast}'[Abort test run on first failure or error]' \ + '(-c --color --no-color)'{-c,--color}'[Enable color in the output]' \ + '(-c --color --no-color)--no-color[Disable color in the output]' \ + '--profile=[Enable profiling of tests and list the slowest test cases]:count' \ + '(-p --pride)'{-p,--pride}'[Show your testing pride]' \ + '*:: :_files -g "*.rb"' \ + && ret=0 + ;; + (runner|r) + _arguments \ + '(- *)'{-h,--help}'[Show this help message and quit]' \ + '(-e --environment)'{-e,--environment=}'[The environment to run "runner"]:env:(test development production)' \ + '*:: :_files -g "*.rb"' \ + && ret=0 + ;; + (plugin) + _arguments \ + '1: :(new)' \ + '*:: :_rails_new' \ + && ret=0 + ;; + (routes) + _arguments \ + '(- *)'{-h,--help}'[Show this help message and quit]' \ + '(-c --controller)'{-c,--controller=}'[Filter by a specific controller]:controller' \ + '(-g --grep)'{-g,--grep}'[Grep routes by a specific pattern]' \ + '(-E --expanded)'{-E,--expanded}'[Print routes expanded vertically with parts explained]' \ + '(-u --unused)'{-u,--unused}'[Print unused routes]' \ + && ret=0 + ;; + (*) + _arguments \ + '(- *)'{-h,--help}'[Show help message and quit]' \ + '*:: :_files' \ + && ret=0 + ;; + esac + ;; + esac + + return ret +} + +(( $+functions[_rails_subcommands] )) || +_rails_subcommands() { + local -a commands + + _rails_is_in_app + + if (( $? == 1 )); then + # is not in rails app directory + commands=( + new'[Create a new Rails application]' + ) + else + commands=( + {generate,g}'[Generate new code]' + {console,c}'[Start the Rails console]' + {server,s}'[Start the Rails server]' + {test,t}'[Run tests]' + "test\\:system[Run systems test only]" + {dbconsole,db}'[Start a console for the database specified in config/database.yml]' + plugin'[Install a plugin]' + + # generated by ./bin/rails --help | ruby -ne '(b=$2;printf("%s[%s]\n", $1.gsub(/:/,"\\:"),b.strip)) if /^([a-z0-9_:]+)\S*\s+([^(\n]+)/' + "about[List versions of all Rails frameworks and the environment]" + "action_mailbox\:ingress\:exim[Relay an inbound email from Exim to Action Mailbox]" + "action_mailbox\:ingress\:postfix[Relay an inbound email from Postfix to Action Mailbox]" + "action_mailbox\:ingress\:qmail[Relay an inbound email from Qmail to Action Mailbox]" + "action_mailbox\:install[Install Action Mailbox and its dependencies]" + "action_mailbox\:install\:migrations[Copy migrations from action_mailbox to application]" + "action_text\:install[Copy over the migration, stylesheet, and JavaScript files]" + "action_text\:install\:migrations[Copy migrations from action_text to application]" + "active_storage\:install[Copy over the migration needed to the application]" + "app\:template[Apply the template supplied by LOCATION=]" + "app\:update[Update configs and some other initially generated files]" + "assets\:clean[Remove old compiled assets]" + "assets\:clobber[Remove compiled assets]" + "assets\:environment[Load asset compile environment]" + "assets\:precompile[Compile all the assets named in config.assets.precompile]" + "cache_digests\:dependencies[Lookup first-level dependencies for TEMPLATE]" + "cache_digests\:nested_dependencies[Lookup nested dependencies for TEMPLATE]" + "credentials\:diff[Enroll/disenroll in decrypted diffs of credentials using git]" + "credentials\:edit[Open the decrypted credentials in $VISUAL or $EDITOR for editing]" + "credentials\:show[Show the decrypted credentials]" + "db\:create[Create the database from DATABASE_URL or config/database.yml for the current RAILS_ENV]" + "db\:drop[Drop the database from DATABASE_URL or config/database.yml for the current RAILS_ENV]" + "db\:encryption\:init[Generate a set of keys for configuring Active Record encryption in a given environment]" + "db\:environment\:set[Set the environment value for the database]" + "db\:fixtures\:load[Load fixtures into the current environment's database]" + "db\:migrate[Migrate the database]" + "db\:migrate\:down[Run the 'down' for a given migration VERSION]" + "db\:migrate\:redo[Roll back the database one migration and re-migrate up]" + "db\:migrate\:status[Display status of migrations]" + "db\:migrate\:up[Run the 'up' for a given migration VERSION]" + "db\:prepare[Run setup if database does not exist, or run migrations if it does]" + "db\:reset[Drop and recreate all databases from their schema for the current environment and load the seeds]" + "db\:rollback[Roll the schema back to the previous version]" + "db\:schema\:cache\:clear[Clear a db/schema_cache.yml file]" + "db\:schema\:cache\:dump[Create a db/schema_cache.yml file]" + "db\:schema\:dump[Create a database schema file]" + "db\:schema\:load[Load a database schema file]" + "db\:seed[Load the seed data from db/seeds.rb]" + "db\:seed\:replant[Truncate tables of each database for current environment and load the seeds]" + "db\:setup[Create all databases, load all schemas, and initialize with the seed data]" + "db\:system\:change[Change 'config/database.yml' and your database gem to the target database]" + "db\:version[Retrieve the current schema version number]" + "destroy[Remove code generated by 'bin/rails generate']" + "dev\:cache[Toggle development mode caching on/off]" + "encrypted\:edit[Open the decrypted file in $VISUAL or $EDITOR for editing]" + "encrypted\:show[Show the decrypted contents of the file]" + "importmap\:install[Setup Importmap for the app]" + "initializers[Print out all defined initializers in the order they are invoked by Rails.]" + "log\:clear[Truncate all/specified *.log files in log/ to zero bytes]" + "middleware[Print out your Rack middleware stack]" + "notes[Show comments in your code annotated with FIXME, OPTIMIZE, and TODO]" + "restart[Restart app by touching tmp/restart.txt]" + "routes[List all the defined routes]" + "runner[Run Ruby code in the context of your application]" + "secret[Generate a cryptographically secure secret key]" + "secrets\:edit[**deprecated** Open the secrets in $VISUAL or $EDITOR for editing]" + "secrets\:show[**deprecated** Show the decrypted secrets]" + "stats[Report code statistics]" + "stimulus\:install[Install Stimulus into the app]" + "stimulus\:install\:importmap[Install Stimulus on an app running importmap-rails]" + "stimulus\:install\:node[Install Stimulus on an app running node]" + "test\:all[Run all tests, including system tests]" + "test\:channels[Run tests in test/channels]" + "test\:controllers[Run tests in test/controllers]" + "test\:db[Reset the database and run 'bin/rails test']" + "test\:functionals[Run tests in test/controllers, test/mailers, and test/functional]" + "test\:generators[Run tests in test/lib/generators]" + "test\:helpers[Run tests in test/helpers]" + "test\:integration[Run tests in test/integration]" + "test\:jobs[Run tests in test/jobs]" + "test\:mailboxes[Run tests in test/mailboxes]" + "test\:mailers[Run tests in test/mailers]" + "test\:models[Run tests in test/models]" + "test\:units[Run tests in test/models, test/helpers, and test/unit]" + "time\:zones[List all time zones, list by two-letter country code]" + "tmp\:clear[Clear cache, socket and screenshot files from tmp/]" + "tmp\:create[Create tmp directories for cache, sockets, and pids]" + "turbo\:install[Install Turbo into the app]" + "turbo\:install\:importmap[Install Turbo into the app with asset pipeline]" + "turbo\:install\:node[Install Turbo into the app with webpacker]" + "turbo\:install\:redis[Switch on Redis and use it in development]" + "version[Show the Rails version]" + "yarn\:install[Install all JavaScript dependencies as specified via Yarn]" + "zeitwerk\:check[Check project structure for Zeitwerk compatibility]" + ) + fi + + _values 'command' $commands +} + +# rails new +(( $+functions[_rails_new] )) || +_rails_new() { + local ret=1 + + _arguments \ + $runtime_options \ + $rails_options \ + --skip-namespace'[Skip namespace]' \ + '(-n --name)'{-n,--name=}'[Name of the app]:name' \ + '(-r --ruby)'{-r,--ruby=}'[Path to the Ruby binary of your choice]:path:_files' \ + '(-b --builder)'{-b,--builder=}'[Path to a application builder(can be a filesystem path or URL)]: :_rails_path_or_url' \ + '(-m --template)'{-m,--template=}'[Path to an application template(can be a filesystem path or URL)]: :_rails_path_or_url' \ + '(-d --database)'{-d,--database=}'[Preconfigure for selected database]:database:(mysql trilogy oracle postgresql sqlite3 frontbase ibm_db sqlserver jdbcmysql jdbcsqlite3 jdbcpostgresql jdbc)' \ + --skip-gemfile"[Don't create a Gemfile]" \ + --skip-bundle"[Don't run bundle install]" \ + '(-G --skip-git)'{-G,--skip-git}'[Skip git init]' \ + --skip-docker'[Skip Dockerfile]' \ + --skip-keeps'[Skip source control .keep files]' \ + '(-M --skip-action-mailer)'{-M,--skip-action-mailer}'[Skip Action Mailer files]' \ + --skip-action-mailbox'[Skip Action Mailbox gem]' \ + --skip-action-text'[Skip Action Text gem]' \ + '(-O --skip-active-record)'{-O,--skip-active-record}'[Skip Active Record files]' \ + --skip-active-job'[Skip Active Job]' \ + --skip-active-storage'[Skip Active Storage files]' \ + '(-C --skip-action-cable)'{-C,--skip-action-cable}'[Skip Action Cable files]' \ + '(-A --skip-asset-pipeline)'{-A,--skip-asset-pipeline}'[Skip asset pipeline]' \ + '(-a --asset-pipeline)'{-a,--asset-pipeline=}'[Choose your asset pipeline]:asset pipeline:(sprockets propshaft)' \ + '(-J --skip-js)'{-J,--skip-js}'[Skip JavaScript files]' \ + --skip-hotwire'[Skip Hotwire integration]' \ + --skip-jbuilder'[Skip jbuilder gem]' \ + '(-T --skip-test)'{-T,--skip-test}'[Skip test files]' \ + --skip-system-test'[Skip system test files]' \ + --skip-bootsnap'[Skip bootsnap gem]' \ + --skip-dev-gems'[Skip development gems(e.g. web-console)]' \ + --dev'[Setup the application with Gemfile pointing to your Rails checkout]' \ + --edge'[Setup the application with Gemfile pointing to Rails repository]' \ + --master'[Set up the application with Gemfile pointing to Rails repository main branch]' \ + --rc='[Path to file containing extra configuration options for rails command]:rc:_files' \ + --api'[Preconfigure smaller stack for API only apps]' \ + --minimal'[Preconfigure a minimal rails app]' \ + '(-j --js)'{-j,--js=}'[Choose JavaScript approach]:javascript:(importmap bun webpack esbuild rollup)' \ + '(-c --css)'{-c,--css=}'[Choose CSS processor]:css processor:(tailwind bootstrap bulma postcss sass)' \ + '(-B --skip-bundle)'{-B,--skip-bundle}"[Don't run bundle install]" \ + --skip-decrypted-diffs"[Don't configure git to show decrypted diffs of encrypted credentials]" \ + ':app path:_directories' && ret=0 + + return ret +} + +# rails generate +(( $+functions[_rails_generate] )) || +_rails_generate() { + local ret=1 + + _arguments -C \ + '(- *)'{-h,--help}"[Print generator's options and usage]" \ + $runtime_options \ + '1:generator:_rails_generate_generator' \ + '*:: :->generate' && ret=0 + + case "$state" in + (generate) + local -a opts + opts=( + '(- *)'{-h,--help}'[Show this help message and quit]' + $runtime_options + '--skip-namespace[Skip namespace]' + '--skip-collision-check[Skip collision check]' + ) + + case $words[1] in + (application_record|migration|model|resource|scaffold|scaffold_controller) + opts+=( + '(-o --orm)'{-o,--orm=}'[ORM to be invoked]:orm:(active_record)' + ) + ;| + (channel) + opts+=( + '--no-assets[Not generate assets]' + ) + ;| + (controller|resource|scaffold|scaffold_controller) + opts+=( + '--skip-routes[Do not add routes to config/routes.rb]' + '--no-helper[Not generate helper]' + ) + ;| + (controller|job|model|resource|scaffold) + opts+=( + '--parent=[The parent class for the generated controler]:parent class' + ) + ;| + (controler|mailer|resource|scaffold|scaffold_controller) + opts+=( + '(-e --template-engine)'{-e,--template-engine=}'[Template engine to be invoked]:engine:(erb)' + ) + ;| + (channel|controller|generator|helper|job|mailbox|mailer|model|scaffold|scaffold_controller) + opts+=( + '(-t --test-framework)'{-t,--test-framework=}'[Test framework to be invoked]:test_framework:(test_unit)' + ) + ;| + (generator|test_unit:channel) + opts+=( + '--no-namespace[Not generate namespace generate]' + ) + ;| + (integration_test) + opts+=( + '--integration-tool=[Integration tool to be invoked]:tool:(test_unit)' + ) + ;| + (jbuilder|resource|scaffold|scaffold_controller) + opts+=( + '--model-name=[ModelName to be used]:name' + ) + ;| + (jbuilder|model|resource|scaffold|scaffold_controller) + opts+=( + '--force-plural[Do not singularize the model name]' + ) + ;| + (jbuilder|migration|model|resource|scaffold_controller) + opts+=( + '--no-timestamps[Not generate timestamps]' + ) + ;| + (job) + opts+=( + '--queue=[The queue name for the generated job]:name' + ) + ;| + (migration|model|resource|scaffold) + opts+=( + '--primary-key-type=[The type for primary key]' + '(--db --database)'{--db,--database=}'[The database for your migration]:db' + ) + ;| + (model|resource|scaffold) + opts+=( + '--no-migration[Not generate migration]' + '--no-indexes[Not add indexes for references and belongs_to columns]' + '--no-fixture[Not generate fixture]' + '(-r --fixture-replacement)'{-r,--fixture-replacement=}'[Fixture replacement to be invoked]:fixture' + ) + ;| + (resource) + opts+=( + '(-c --resource-controller)'{-c,--resource-controller=}'[Resource controller to be invoked]:controller:(controller)' + '(-a --actions)'{-a,--actions=}'[Actions for the source controller]:action' + ) + ;| + (resource|scaffold|scaffold_controller) + opts+=( + '--no-resource-route[Not generate resource route]' + ) + ;| + (scaffold) + opts+=( + '(-c --scaffold-controller)'{-c,--scaffold-controller=}'[Scaffold controller to be invoked]:controller:(scaffold_controller)' + + ) + ;| + (scaffold|scaffold_controller) + opts+=( + '--api[Generate API-only controller and tests, with no view templates]' + '--no-jbuilder[Not generate jbuilder]' + ) + ;| + (scaffold|scaffold_controller|system_test) + opts+=( + '--system-tests=[System test framework to be invoked]:framework:(test_unit)' + ) + ;| + (stimulus) + opts+=( + '--skip-manifest[Do not update the stimulus manifest]' + ) + ;| + (jbuilder|migration|resource|scaffold) + opts+=( + '*:field:_rails_migration_fields' + ) + ;| + esac + + _arguments $opts && ret=0 + ;; + esac + + return ret +} + +(( $+functions[_rails_generate_generator] )) || +_rails_generate_generator() { + local -a generators=( + # rails + application_record benchmark channel controller generator helper integration_test + jbuilder job mailbox mailer migration model resource scaffold scaffold_controller + system_test task + + # active record + "active_record\\:application_record" + "active_record\\:multi_db" + + # Stimulus + stimulus + + # TestUnit + "test_unit\\:channel" "test_unit\\:generator" "test_unit\\:install" + "test_unit\\:mailbox" "test_unit\\:plugin" + ) + + _values 'generators' $generators +} + +# Utilities +(( $+functions[_rails_is_in_app] )) || +_rails_is_in_app() { + local dir="$PWD" + while [ -n "$dir" ]; do + if [[ -f "${dir}/bin/rails" ]]; then + return 0 + fi + dir="${dir/*}" + done + + return 1 +} + +(( $+functions[_rails_path_or_url] )) || +_rails_path_or_url() { + _alternative \ + 'files:path:_files -g "*.rb"' \ + 'url:url:_urls' +} + +(( $+functions[_rails_migration_fields] )) || +_rails_migration_fields() { + if compset -P '*:*:'; then + _values 'index' 'index' 'uniq' + else + if compset -P '*:'; then + _values -s ':' 'type' 'string' 'text' 'integer' 'float' 'decimal' 'datetime' 'timestamp' 'time' 'date' 'binary' 'boolean' 'references' + else + _guard '[[:alnum:]_]#' 'field' + fi + fi +} + +_rails "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ralio b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ralio new file mode 100644 index 00000000..0a422707 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ralio @@ -0,0 +1,146 @@ +#compdef ralio +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for ralio (https://github.com/oesmith/ralio), a +# Rally client +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Peter Yates +# +# ------------------------------------------------------------------------------ + +_ralio () +{ + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments -C \ + ':command:->command' \ + '*::options:->options' \ + + case $state in + (command) + + local -a subcommands + subcommands=( + "backlog:Show the product backlog" + "sprint:Show the current team iteration" + "show:Show related information for an individual story, defect or task" + "open:Open a story, defect or task in a web browser" + "start:Set a task, defect or story state to in-progress and assign it to you" + "finish:Set a task, defect or story state to completed and assign it to you" + "abandon:Set a task, defect or story state to defined and clear the owner" + "block:Set a task, defect or story state to blocked" + "unblock:Set a task, defect or story state to unblocked" + "current:Show your current tasks and stories" + "point:Set the points for a story or defect" + "task:Allow you to create and delete story tasks." + "configure:Set your Rally configurations." + ) + _describe -t commands 'ralio commands' subcommands + + _arguments -C \ + {-V,--version}"[display version information]" \ + {-h,--help}"[output usage information]" + ;; + + (options) + case $line[1] in + + + (sprint) + _arguments \ + "-t[Show tasks]" \ + "-p[Project name]" \ + "-f[Filter results]" + ;; + + (start | finish) + _arguments \ + '--pair[Pair programming partner]' \ + "--resolution[Resolution status]" \ + "--rootcause[Root cause]" + ;; + + (task) + __ralio-task + ;; + + esac + ;; + esac +} + +__ralio-task () +{ + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments -C \ + ':command:->command' \ + '*::options:->options' + + case $state in + (command) + + local -a subcommands + subcommands=( + "create:Create a new task" + "delete:Delete a task" + ) + _describe -t commands 'ralio task' subcommands + ;; + + (options) + case $line[1] in + + (create|delete) + _arguments \ + -n"[Name of the new task]" \ + -t"[Name of the parent task]" + ;; + + esac + ;; + esac +} + +_ralio "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_redis-cli b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_redis-cli new file mode 100644 index 00000000..0320f9c9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_redis-cli @@ -0,0 +1,184 @@ +#compdef redis-cli rec +# ------------------------------------------------------------------------------ +# Copyright (c) 2009-2015 Robby Russell and contributors (see +# https://github.com/ohmyzsh/ohmyzsh/graphs/contributors) +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Redis (https://redis.io/). +# +# Source: https://github.com/ohmyzsh/ohmyzsh/tree/master/plugins/redis-cli +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Alexandru Totolici (https://github.com/totolici) +# +# ------------------------------------------------------------------------------ + + +local -a _1st_arguments +_1st_arguments=( + 'append:append a value to a key' + 'auth:authenticate to the server' + 'bgrewriteeaof:asynchronously rewrite the append-only file' + 'bgsave:asynchornously save the dataset to disk' + 'blpop:remove and get the first element in a list, or block until one is available' + 'brpop:remove and get the last element in a list, or block until one is available' + 'brpoplpush:pop a value from a list, push it to another list and return it; or block until one is available' + # 'config get:get the value of a configuration parameter' + # 'config set:set a configuration parameter to the given value' + # 'config resetstat: reset the stats returned by INFO' + 'dbsize:return the number of keys in the selected database' + # 'debug object:get debugging information about a key' + # 'debug setgfault:make the server crash' + 'decr:decrement the integer value of a key by one' + 'decrby:decrement the integer value of a key by the given number' + 'del:delete a key' + 'discard:discard all commands issued after MULTI' + 'echo:echo the given string' + 'exec:execute all commands issued after a MULTI' + 'exists:determine if a key exists' + 'expire:set the time to live for a key, in seconds' + 'expireat:set the expiration for a key as a UNIX timestamp' + 'flushall:remove all keys from all databases' + 'flushdb:remove all keys from the current database' + 'get:get the value of a key' + 'getbit:returns the bit value at offset in the string value stored at key' + 'getrange:get a substring of the string stored at a key' + 'getset:set the string value of a key and return its old value' + 'hdel:delete a hash field' + 'hexists:determine if a hash field exists' + 'hget:get the value of a hash field' + 'hgetall:get all the fields and values in a hash' + 'hincrby:increment the integer value of a hash field by the given number' + 'hkeys:get all the fields in a hash' + 'hlen:get the number of fields in a hash' + 'hmget:get the values of all the given hash fields' + 'hmset:set multiple hash fields to multiple values' + 'hset:set the string value of a hash field' + 'hsetnx:set the value of a hash field, only if the field does not exist' + 'hvals:get all the values in a hash' + 'incr:increment the integer value of a key by one' + 'incrby:increment the integer value of a key by the given number' + 'info:get information and statistics about the server' + 'keys:find all keys matching the given pattern' + 'lastsave:get the UNIX timestamp of the last successful save to disk' + 'lindex:get an element from a list by its index' + 'linsert:insert an element before or after another element in a list' + 'llen:get the length of a list' + 'lpop:remove and get the first element in a list' + 'lpush:prepend a value to a list' + 'lpushx:prepend a value to a list, only if the list exists' + 'lrange:get a range of elements from a list' + 'lrem:remove elements from a list' + 'lset:set the value of an element in a list by its index' + 'ltrim:trim a list to the specified range' + 'mget:get the values of all the given keys' + 'monitor:listen for all requests received by the server in real time' + 'move:move a key to another database' + 'mset:set multiple keys to multiple values' + 'msetnx:set multiple keys to multiple values, only if none of the keys exist' + 'multi:mark the start of a transaction block' + 'object:inspect the internals of Redis objects' + 'persist:remove the expiration from a key' + 'ping:ping the server' + 'psubscribe:listen for messages published to channels matching the given patterns' + 'publish:post a message to a channel' + 'punsubscribe:stop listening for messages posted to channels matching the given patterns' + 'quit:close the connection' + 'randomkey:return a random key from the keyspace' + 'rename:rename a key' + 'renamenx:rename a key, only if the new key does not exist' + 'rpop:remove and get the last element in a list' + 'rpoplpush:remove the last element in a list, append it to another list and return it' + 'rpush:append a value to a list' + 'rpushx:append a value to a list, only if the list exists' + 'sadd:add a member to a set' + 'save:synchronously save the dataset to disk' + 'scard:get the number of members in a set' + 'sdiff:subtract multiple sets' + 'sdiffstore:subtract multiple sets and store the resulting set in a key' + 'select:change the selected database for the current connection' + 'set:set the string value of a key' + 'setbit:sets or clears the bit at offset in the string value stored at key' + 'setex:set the value and expiration of a key' + 'setnx:set the value of a key, only if the key does not exist' + 'setrange:overwrite part of a string at key starting at the specified offset' + 'shutdown:synchronously save the dataset to disk and then shut down the server' + 'sinter:intersect multiple sets' + 'sinterstore:intersect multiple sets and store the resulting set in a key' + 'sismember:determine if a given value is a member of a set' + 'slaveof:make the server a slave of another instance, or promote it as master' + 'smembers:get all the members in a set' + 'smove:move a member from one set to another' + 'sort:sort the elements in a list, set or sorted set' + 'spop:remove and return a random member from a set' + 'srandmember:get a random member from a set' + 'srem:remove a member from a set' + 'strlen:get the length of the value stored in a key' + 'subscribe:listen for messages published to the given channels' + 'sunion:add multiple sets' + 'sunionstore:add multiple sets and store the resulting set in a key' + 'ttl:get the time to live for a key' + 'type:determine the type stored at key' + 'unsubscribe:stop listening for messages posted to the given channels' + 'unwatch:forget about all watched keys' + 'watch:watch the given keys to determine execution of the MULTI/EXEC block' + 'zadd:add a member to a sorted set, or update its score if it already exists' + 'zcard:get the number of members in a sorted set' + 'zcount:count the members in a sorted set with scores within the given values' + 'zincrby:increment the score of a member in a sorted set' + 'zinterstore:intersect multiple sorted sets and store the resulting sorted set in a new key' + 'zrange:return a range of members in a sorted set, by index' + 'zrangebyscore:return a range of members in a sorted set, by score' + 'zrank:determine the index of a member in a sorted set' + 'zrem:remove a member from a sorted set' + 'zremrangebyrank:remove all members in a sorted set within the given indexes' + 'zremrangebyscore:remove all members in a sorted set within the given scores' + 'zrevrange:return a range of members in a sorted set, by index, with scores ordered from high to low' + 'zrevrangebyscore:return a range of members in a sorted set, by score, with scores ordered from high to low' + 'zrevrank:determine the index of a member in a sorted set, with scores ordered from high to low' + 'zscore:get the score associated with the given member in a sorted set' + 'zunionstore:add multiple sorted sets and store the resulting sorted set in a new key' +) + +local expl + +_arguments \ + '(-v --version)'{-v,--version}'[show version]' \ + '(-h --help)'{-h,--help}'[show help]' \ + '*:: :->subcmds' && return 0 + +if (( CURRENT == 1 )); then + _describe -t commands "redis-cli subcommand" _1st_arguments + return +fi + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rfkill b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rfkill new file mode 100644 index 00000000..55b6cd6d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rfkill @@ -0,0 +1,111 @@ +#compdef rfkill +# ------------------------------------------------------------------------------ +# Copyright (c) 2014 Vincent Bernat +# Copyright (c) 2014 Github zsh-users - https://github.com/zsh-users +# +# Permission to use, copy, modify, and/or distribute this software for any +# purpose with or without fee is hereby granted, provided that the above +# copyright notice and this permission notice appear in all copies. +# +# THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES +# WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF +# MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR +# ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES +# WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN +# ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF +# OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for rfkill 2.38.1 (https://wireless.wiki.kernel.org/en/users/Documentation/rfkill) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Vincent Bernat +# * Shohei YOSHIDA +# +# ------------------------------------------------------------------------------ + +_rfkill_types() { + local -a devicetypes=(all + "wifi:Wireless LAN" "wlan:Wireless LAN" + "bluetooth:Bluetooth" + "uwb:Ultrawide Band" + "ultrawideband:Ultrawide Band" + "wimax:Wimax" + "wwan:3G" + "gps:GPS" + "fm:FM Radio" + "nfc:NFC") + _describe -t device-types "device types" devicetypes +} + +_rfkill_devices() { + local -a devices=(${(M)${(f)"$(rfkill list)"}:#[0-9]*}) + _rfkill_types + _describe -t devices "devices" devices +} + +_rfkill_columns() { + local -a columns=(DEVICE ID TYPE TYPE-DESC SOFT HARD) + _values -s ',' 'column' $columns +} + +_rfkill_command() { + local -a commands=( + 'help:display help text and exit' + 'event:listen for rfkill events and display them on stdout' + 'list:list the current state of all available devices' + 'block:disable the corresponding device' + 'unblock:enable the corresponding device' + 'toggle:enable or disable the corresponding device' + ) + _describe -t commands 'command' commands "$@" +} + +_rfkill_subcommand() { + case "$words[1]" in + (list) + _arguments ':types:_rfkill_types' + ;; + (block|unblock|toggle) + _arguments ':device:_rfkill_devices' + ;; + esac +} + +_rfkill () { + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments -C \ + '(* -)'{-h,--help}'[display help]' \ + '(* -)'{-V,--version}'[get version]' \ + '(-J --json -r --raw)'{-J,--json}'[use JSON output format]' \ + '(-n --noheadings)'{-n,--noheadings}"[don't print headings]" \ + '(-o --output --output-all)'{-o,--output}'[define which output columns to use]:column_list:_rfkill_columns' \ + '(-o --output --output-all)--output-all[output all columns]' \ + '(-J --json -r --raw)'{-r,--raw}'[use the raw output format]' \ + '(-): :_rfkill_command' \ + '(-)*:: :->arguments' + + case $state in + (arguments) + curcontext=${curcontext%:*:*}:rfkill-$words[1]: + _rfkill_subcommand + ;; + esac +} + +_rfkill "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rkt b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rkt new file mode 100644 index 00000000..d4ce0216 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rkt @@ -0,0 +1,369 @@ +#compdef rkt +# ------------------------------------------------------------------------------ +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for rkt (https://coreos.com/rkt/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Massimiliano Torromeo +# +# ------------------------------------------------------------------------------ + +typeset -A opt_args +autoload -U regexp-replace + +_rkt() { + _arguments \ + '--debug[print out more debug information to stderr]' \ + '--dir=[rkt data directory]:data directory:_files -/' \ + '--insecure-options=[comma-separated list of security features to disable]:option:{_values -s , none image tls ondisk http all}' \ + '--local-config=[local configuration directory]:configuration directory:_files -/' \ + '--system-config=[system configuration directory]:configuration directory:_files -/' \ + '--trust-keys-from-https[automatically trust gpg keys fetched from https]' \ + '--user-config=[user configuration directory]:configuration directory:_files -/' \ + '--help' \ + '1: :_rkt_cmds' \ + '*:: :->rkt_cmd_args' + + case $state in + rkt_cmd_args) + case $words[1] in + help) + _arguments \ + '1: :_rkt_cmds' \ + '*:: :->rkt_help_args' \ + ;; + + api-service) + _arguments \ + '--listen=[address to listen for client API requests]:address' \ + ;; + + cat-manifest) + _arguments \ + '--pretty-print[apply indent to format the output]' \ + '--uuid-file=[read pod UUID from file instead of argument]:uuid file:_files' \ + '1:POD:_rkt_pods' \ + ;; + + config) + _arguments \ + '--pretty-print[apply indent to format the output]' \ + ;; + + enter) + _arguments \ + '--app=:appname' \ + '1:POD:_rkt_pods' \ + ;; + + export) + _arguments \ + '--app=:appname' \ + '--overwrite[overwrite output ACI]' \ + '1:POD:_rkt_pods' \ + '2:OUTPUT_ACI_FILE:_files' \ + ;; + + fetch) + _arguments \ + '--full[print the full image hash after fetching]' \ + '--no-store[fetch images ignoring the local store]' \ + '--signature=[local signature file to use in validating the preceding image]:signature:_files' \ + '--store-only[use only available images in the store]' \ + ;; + + gc) + _arguments \ + '--grace-period=[duration to wait before discarding inactive pods from garbage]:duration' \ + '--expire-prepared=[duration to wait before expiring prepared pods]:duration' \ + '--mark-only[move to the garbage directories without actually deleting]' \ + ;; + + image) + _arguments \ + '1: :_rkt_image_cmds' \ + '*:: :->rkt_image_args' + ;; + + list) + _arguments \ + '--full[use long output format]' \ + '--no-legend[suppress a legend with the list]' \ + ;; + + metadata-service) + _arguments \ + '--listen-port=[listen port]:port' \ + ;; + + prepare) + # TODO: autocomplete stage1 images + _arguments \ + '--caps-remove=[capability to remove]:capability' \ + '--caps-retain=[capability to retain]:capability' \ + '--cpu=[cpu limit for the preceding image]:cpu limit' \ + '--cpu-shares=[assign the specified CPU time share weight]:weight' \ + "--environment=[set the app's environment variables]:variable key=value" \ + '--exec=[override the exec command for the preceding image]:command' \ + '--group=[group override for the preceding image]:group' \ + '--inherit-env[inherit all environment variables not set by apps]' \ + '--memory=[memory limit for the preceding image]:memory' \ + '--mount=[mount point binding a volume to a path within an app]:mount point' \ + '--name=[set the name of the app]:name' \ + '--no-overlay[disable overlay filesystem]' \ + '--oom-score-adj=[oom-score-adj isolator override]:oom-score-adj' \ + '--pod-manifest=[the path to the pod manifest]:manifest:_files' \ + '--port=[ports to expose on the host]:NAME\:HOSTPORT' \ + '--private-users[run within user namespaces]' \ + '--quiet[suppress superfluous output on stdout, print only the UUID on success]' \ + '--readonly-rootfs=[mount rootfs read-only]:fs' \ + '--set-env=[an environment variable to set for apps]:NAME=VALUE' \ + '--set-env-file=[the path to an environment variables file]:file:_files' \ + '--signature=[local signature file to use in validating the preceding image]:signature:_files' \ + '--stage1-from-dir=[a filename of an image in stage1 images directory to use as stage1]:image' \ + '--stage1-hash=[a hash of an image to use as stage1]:image hash' \ + '--stage1-name=[a name of an image to use as stage1]:image name' \ + '--stage1-path=[a path to an image to use as stage1]:image path:_files' \ + '--stage1-url=[a URL to an image to use as stage1]:image url' \ + '--supplementary-gids=[supplementary group IDs override for the preceding image]:group IDs' \ + '--user=[user override for the preceding image]:user' \ + "--user-annotation=[set the app's annotations]:annotation key=value" \ + "--user-label=[set the app's labels]:label key=value" \ + '--volume=[volumes to make available in the pod]:volume' \ + '--working-dir=[override the working directory of the preceding image]:working directory:_files -/' \ + '1:IMAGE:_rkt_images' \ + ;; + + rm) + _arguments \ + '--uuid-file=[read pod UUID from file instead of argument]:uuid file:_files' \ + '1:POD:_rkt_pods' \ + ;; + + run) + _arguments \ + '--caps-remove=[capability to remove]:capability' \ + '--caps-retain=[capability to retain]:capability' \ + '--cpu=[cpu limit for the preceding image]:cpu limit' \ + '--cpu-shares=[assign the specified CPU time share weight]:weight' \ + '--dns=[name servers to write in /etc/resolv.conf]:name servers' \ + '--dns-domain=[DNS domain to write in]:domain' \ + '--dns-opt=[DNS options to write in /etc/resolv.conf]:dns options' \ + '--dns-search=[DNS search domains to write in /etc/resolv.conf]:search domains' \ + "--environment=[set the app's environment variables]:variable key=value" \ + '--exec=[override the exec command for the preceding image]:command' \ + '--group=[group override for the preceding image]:group' \ + "--hostname=[pod's hostname]:hostname" \ + "--hosts-entry=[entries to add to the pod-wide /etc/hosts. Pass 'host' to use the host's /etc/hosts]:hosts entry" \ + '--inherit-env[inherit all environment variables not set by apps]' \ + '--interactive[run pod interactively]' \ + '--mds-register[register pod with metadata service]' \ + '--memory=[memory limit for the preceding image]:memory limit' \ + '--mount=[mount point binding a volume to a path within an app]:mount point' \ + '--name=[set the name of the app]:name' \ + "--net=[configure the pod's networking]:networks" \ + '--no-overlay[disable overlay filesystem]' \ + '--pod-manifest=[the path to the pod manifest]:manifest:_files' \ + '--port=[ports to expose on the host]:NAME\:HOSTPORT' \ + '--private-users[run within user namespaces]' \ + '--set-env=[an environment variable to set for apps]:NAME=VALUE' \ + '--set-env-file=[the path to an environment variables file]:file:_files' \ + '--signature=[local signature file to use in validating the preceding image]:signature:_files' \ + '--stage1-from-dir=[a filename of an image in stage1 images directory to use as stage1]:image' \ + '--stage1-hash=[a hash of an image to use as stage1]:image hash' \ + '--stage1-name=[a name of an image to use as stage1]:image name' \ + '--stage1-path=[a path to an image to use as stage1]:image path:_files' \ + '--stage1-url=[a URL to an image to use as stage1]:image url' \ + '--supplementary-gids=[supplementary group IDs override for the preceding image]:group IDs' \ + '--user=[user override for the preceding image]:user' \ + "--user-annotation=[set the app's annotations]:annotation key=value" \ + "--user-label=[set the app's labels]:label key=value" \ + '--uuid-file-save=[write out pod UUID to specified file]:uuid file:_files' \ + '--volume=[volumes to make available in the pod]:volume' \ + '--working-dir=[override the working directory of the preceding image]:working directory:_files -/' \ + '1:IMAGE:_rkt_images' \ + ;; + + run-prepared) + _arguments \ + '--dns=[name servers to write in /etc/resolv.conf]:name servers' \ + '--dns-domain=[DNS domain to write in]:domain' \ + '--dns-opt=[DNS options to write in /etc/resolv.conf]:dns options' \ + '--dns-search=[DNS search domains to write in /etc/resolv.conf]:search domains' \ + "--hostname=[pod's hostname]:hostname" \ + "--hosts-entry=[entries to add to the pod-wide /etc/hosts. Pass 'host' to use the host's /etc/hosts]:hosts entry" \ + '--interactive[run pod interactively]' \ + '--mds-register[register pod with metadata service]' \ + "--net=[configure the pod's networking]:networks" \ + '1:POD:_rkt_pods' \ + ;; + + status) + _arguments \ + '--format=[choose the output format]:format:(json json-pretty)' \ + '--wait[toggles waiting for the pod to exit]' \ + '--wait-ready[toggles waiting until the pod is ready]' \ + '1:POD:_rkt_pods' \ + ;; + + stop) + _arguments \ + '--force[forced stopping]' \ + '--uuid-file=[read pod UUID from file instead of argument]:uuid file:_files' \ + '1:POD:_rkt_pods' \ + ;; + + trust) + _arguments \ + '--insecure-allow-http[allow HTTP use for key discovery and/or retrieval]' \ + '--prefix=[prefix to limit trust to]:prefix' \ + '--root[add root key from filesystem without a prefix]' \ + '--skip-fingerprint-review[accept key without fingerprint confirmation]' \ + ;; + esac + ;; + esac + + case $state in + rkt_help_args) + case $words[1] in + image) + _arguments \ + '1: :_rkt_image_cmds' + ;; + esac + ;; + + rkt_image_args) + case $words[1] in + cat-manifest) + _arguments \ + '--pretty-print[apply indent to format the output]' \ + '1:IMAGE:_rkt_images' \ + ;; + + export) + _arguments \ + '--overwrite[overwrite output ACI]' \ + '1:IMAGE:_rkt_images' \ + '2:OUTPUT_ACI_FILE:_files' \ + ;; + + extract|render) + _arguments \ + '--overwrite[overwrite output ACI]' \ + '--rootfs-only[extract rootfs only]' \ + '1:IMAGE:_rkt_images' \ + '2:OUTPUT_DIR:_files -/' \ + ;; + + gc) + _arguments \ + '--grace-period=[duration to wait before discarding inactive pods from garbage]:duration' \ + ;; + + list) + _arguments \ + '--fields=[comma-separated list of fields to display]:fields:{_values -s , id name importtime lastused size latest}' \ + '--full[use long output format]' \ + '--no-legend[suppress a legend with the list]' \ + ;; + + rm) + _arguments \ + '*:IMAGE:_rkt_images' \ + ;; + esac + ;; + esac +} + +_rkt_cmds() { + local -a commands + commands=( + 'api-service:Run API service' + 'cat-manifest:Inspect and print the pod manifest' + 'config:Print configuration for each stage in JSON format' + 'enter:Enter the namespaces of an app within a rkt pod' + 'export:Export an app from an exited pod to an ACI file' + 'fetch:Fetch image(s) and store them in the local store' + 'gc:Garbage collect rkt pods no longer in use' + 'image:Operate on image(s) in the local store' + 'list:List pods' + 'metadata-service:Run metadata service' + 'prepare:Prepare to run image(s) in a pod in rkt' + 'rm:Remove all files and resources associated with an exited pod' + 'run:Run image(s) in a pod in rkt' + 'run-prepared:Run a prepared application pod in rkt' + 'status:Check the status of a rkt pod' + 'stop:Stop a pod' + 'trust:Trust a key for image verification' + 'version:Print the version and exit' + 'help:Help about any command' + ) + _describe 'command' commands +} + +_rkt_image_cmds() { + local -a commands + commands=( + 'cat-manifest:Inspect and print the image manifest' + 'export:Export a stored image to an ACI file' + 'extract:Extract a stored image to a directory' + 'gc:Garbage collect local store' + 'list:List images in the local store' + 'render:Render a stored image to a directory with all its dependencies' + 'rm:Remove image(s) with the given ID(s) or name(s) from the local store' + ) + _describe 'command' commands +} + +_rkt_images() { + local -a images + images=($(rkt image list --fields id,name --no-legend | sed 's/\t/\n/;s/:/\\:/g' | sort | uniq)) + _describe 'IMAGE' images +} + +_rkt_pods() { + local -a pods + IFS=$'\n' + pods=($(rkt list --full --no-legend | sed 's/:/\\:/g;s/\t/:/;s/\t/ /g')) + _describe 'POD' pods +} + +_rkt "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rmlint b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rmlint new file mode 100644 index 00000000..5730ac75 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rmlint @@ -0,0 +1,422 @@ +#compdef rmlint rmlint.sh -P rmlint.*.sh + +# Copyright (c) 2021 Github zsh-users - https://github.com/zsh-users +# +# Permission is hereby granted, without written agreement and without +# licence or royalty fees, to use, copy, modify, and distribute this +# software and to distribute modified versions of this software for any +# purpose, provided that the above copyright notice and the following +# two paragraphs appear in all copies of this software. +# +# In no event shall the Zsh Development Group be liable to any party for +# direct, indirect, special, incidental, or consequential damages arising out +# of the use of this software and its documentation, even if the Zsh +# Development Group have been advised of the possibility of such damage. +# +# The Zsh Development Group specifically disclaim any warranties, including, +# but not limited to, the implied warranties of merchantability and fitness +# for a particular purpose. The software provided hereunder is on an "as is" +# basis, and the Zsh Development Group have no obligation to provide +# maintenance, support, updates, enhancements, or modifications. +# +# Description +# ----------- +# +# Zsh completion for rmlint 2.10.1 (https://github.com/sahib/rmlint) +# +# Authors +# ------- +# +# * oxiedi (https://github.com/oxiedi) + +(( $+functions[_rmlint_types] )) || +_rmlint_types() { + compset -P '*[+-]' + # FIXME: all values before `-` are swallowed by `*`, which breaks deduplication of the swallowed values + # TODO: respect `prefix-needed` + _values -s ',' 'list [defaults]' \ + 'all[enables all lint types]' \ + 'defaults[enables all lint types, but nonstripped]' \ + 'minimal[defaults minus emptyfiles and emptydirs]' \ + 'minimaldirs[defaults minus emptyfiles, emptydirs and duplicates, but with duplicatedirs]' \ + 'none[disable all lint types]' \ + '(badids bi)'{badids,bi}'[find files with bad UID, GID or both]' \ + '(badlinks bl)'{badlinks,bl}'[find bad symlinks pointing nowhere valid]' \ + '(emptydirs ed)'{emptydirs,ed}'[find empty directories]' \ + '(emptyfiles ef)'{emptyfiles,ef}'[find empty files]' \ + '(nonstripped ns)'{nonstripped,ns}'[find nonstripped binaries]' \ + '(duplicates df)'{duplicates,df}'[find duplicate files]' \ + '(duplicatedirs dd)'{duplicatedirs,dd}'[find duplicate directories (This is the same -D!)]' +} + +(( $+functions[__rmlint_setup_formatter_descriptions] )) || +__rmlint_setup_formatter_descriptions() { + typeset -gA formatter_descriptions=( + csv 'output all found lint as comma-separated-value list' + sh 'output all found lint as shell script' + json 'print a JSON-formatted dump of all found reports' + py 'outputs a python script and a JSON document, just like the json formatter' + uniques 'outputs all unique paths found during the run, one path per line' + stamp 'outputs a timestamp of the time rmlint was run' + progressbar 'shows a progressbar' + pretty 'shows all found items in realtime nicely colored' + summary 'shows counts of files and their respective size after the run. Also list all written output files' + fdupes 'prints an output similar to the popular duplicate finder fdupes(1)' + ) +} + +(( $+functions[_rmlint_output] )) || +_rmlint_output() { + local -A formatter_descriptions + __rmlint_setup_formatter_descriptions + if compset -P "(${(kj:|:)formatter_descriptions}):"; then + _alternative \ + 'files:file:_files' \ + 'outputs:output:(stdout stderr)' + else + local -a outputs + local f d + for f d in ${(kv)formatter_descriptions}; do + outputs+=( "$f:$d" ) + done + _describe -t outputs 'output' outputs -S ':' -q + fi +} + +(( $+functions[_rmlint_config] )) || +_rmlint_config() { + local -A formatter_descriptions + __rmlint_setup_formatter_descriptions + unset 'formatter_descriptions['{py,pretty,summary}']' + local -a match mbegin mend + if compset -P "(#b)(${(kj:|:)formatter_descriptions}):"; then + case $match[1] in + (csv) + _values 'option' \ + 'no_header[do not write a first line describing the column headers]' \ + 'unique[include unique files in the output]' + ;; + (sh) + local context state state_descr line + _values 'option' \ + 'cmd[specify a user defined command to run on duplicates]: :_cmdstring' \ + 'handler[define a comma separated list of handlers to try on duplicate files in that given order until one handler succeeds]:handler:->handler' \ + 'link[shortcut for -c sh:handler=clone,reflink,hardlink,symlink]' \ + 'hardlink[shortcut for -c sh:handler=hardlink,symlink]' \ + 'symlink[shortcut for -c sh:handler=symlink]' + case $state in + (handler) + _values -s ',' $state_descr \ + 'clone[try to clone both files with the FIDEDUPERANGE ioctl(3p) (or BTRFS_IOC_FILE_EXTENT_SAME on older kernels)]' \ + 'reflink[try to reflink the duplicate file to the original]' \ + 'hardlink[replace the duplicate file with a hardlink to the original file]' \ + 'symlink[tries to replace the duplicate file with a symbolic link to the original]' \ + 'remove[remove the file using rm -rf]' \ + 'usercmd[use the provided user defined command (-c sh:cmd=something)]' + ;; + esac + ;; + (json) + _values 'option' \ + 'unique[include unique files in the output]' \ + 'no_header[print the header with metadata]:boolean [true]:(false true)' \ + 'no_footer[print the footer with statistics]:boolean [true]:(false true)' \ + 'oneline[print one json document per line]:boolean [false]:(true false)' + ;; + (uniques) + _values 'option' \ + 'print0[do not put newlines between paths but zero bytes]' + ;; + (stamp) + _values 'option' \ + 'iso8601[write an ISO8601 formatted timestamps or seconds since epoch]:boolean:(true false)' + ;; + (progressbar) + _values 'option' \ + 'update_interval[number of milliseconds to wait between updates (default: 50)]: :_guard "[0-9]#" "update interval (milliseconds) [50]"' \ + 'ascii[do not attempt to use unicode characters, which might not be supported by some terminals]' \ + 'fancy[use a more fancy style for the progressbar]' + ;; + (fdupes) + _values 'option' \ + 'omitfirst[omits the first line of each set of duplicates]' \ + 'sameline[does not print newlines between files, only a space]' + ;; + esac + else + local -a formatters + local f d + for f d in ${(kv)formatter_descriptions}; do + formatters+=( "$f:$d" ) + done + _describe -t formatters 'formatter' formatters -S ':' + fi +} + +(( $+functions[_rmlint_algorithm] )) || +_rmlint_algorithm() { + local -a tmp=( sha{1,256,512} sha3-{256,384,512} blake{2s,2b,2sp,2bp} highway{64,128,256} ) + _alternative \ + '512bit-algorithms:512-bit:(blake2b blake2bp sha3-512 sha512)' \ + '384bit-algorithms:384-bit:(sha3-384)' \ + '256bit-algorithms:256-bit:(blake2s blake2sp sha3-256 sha256 highway256 metro256 metrocrc256)' \ + '160bit-algorithms:160-bit:(sha1)' \ + '128bit-algorithms:128-bit:(md5 murmur metro metrocrc)' \ + '64bit-algorithms:64-bit:(highway64 xxhash)' \ + "cryptographic-algorithms:cryptographic:($tmp)" \ + 'non-cryptographic-algorithms:non-cryptographic:(metro metro256 xxhash murmur)' \ + 'not-useful-algorithms:not-useful:(cumulative paranoid ext)' +} + +(( $+functions[_rmlint_sort] )) || +_rmlint_sort() { + local -A letter_descriptions=( + s 'sort by size of group' + a 'sort alphabetically by the basename of the original' + m 'sort by mtime of the original' + p 'sort by path-index of the original' + o 'sort by natural found order (might be different on each run)' + n 'sort by number of files in the group' + ) + local -a letters + local l d + for l d in ${(kv)letter_descriptions}; do + letters+=( "${l}[$d]" "${(U)l}[$d (in reverse order)]" ) + done + _values -s '' 'order' $letters +} + +(( $+functions[__rmlint_describe_multipliers] )) || +__rmlint_describe_multipliers() { + local -a multipliers=( + 'C:1^1' + 'W:2^1' + 'B:512^1' + 'K:1000^1' + 'KB:1024^1' + 'M:1000^2' + 'MB:1024^2' + 'G:1000^3' + 'GB:1024^3' + 'T:1000^4' + 'TB:1024^4' + 'P:1000^5' + 'PB:1024^5' + 'E:1000^6' + 'EB:1024^6' + ) + _describe -t multiplier 'multiplier' multipliers "$@" +} + +(( $+functions[__rmlint_multipliers] )) || +__rmlint_multipliers() { + compset -P '[0-9]##' || return + __rmlint_describe_multipliers "$@" +} + +(( $+functions[_rmlint_size] )) || +_rmlint_size() { + ! __rmlint_multipliers && [[ -z $PREFIX ]] && _message -e "${1:-size}" +} + +(( $+functions[_rmlint_size_range] )) || +_rmlint_size_range() { + if compset -P '[0-9]##'; then + if compset -P '(C|W|B|K|KB|M|MB|G|GB|T|TB|P|PB|E|EB)-'; then + _rmlint_size 'max' + else + __rmlint_describe_multipliers -S '-' -q + fi + elif [[ -z $PREFIX ]]; then + _message -e 'min' + fi +} + +(( $+functions[_rmlint_iso8601_or_unix_timestamp] )) || +_rmlint_iso8601_or_unix_timestamp() { + _alternative \ + 'dates:iso8601_timestamp: _dates -f "%FT%T"' \ + 'seconds:unix_timestamp:_guard "[0-9]#" "seconds since epoch"' +} + +(( $+functions[_rmlint_rank] )) || +_rmlint_rank() { + # TODO: {r,R,x,X} + _values -s '' 'criteria [pOma]' \ + 'm[keep lowest mtime (oldest)]' 'M[keep highest mtime (newest)]' \ + 'a[keep first alphabetically]' 'A[keep last alphabetically]' \ + 'p[keep first named path]' 'P[keep last named path]' \ + 'd[keep path with lowest depth]' 'D[keep path with highest depth]' \ + 'l[keep path with shortest basename]' 'L[keep path with longest basename]' \ + 'r[keep paths matching regex]' 'R[keep path not matching regex]' \ + 'x[keep basenames matching regex]' 'X[keep basenames not matching regex]' \ + 'h[keep file with lowest hardlink count]' 'H[keep file with highest hardlink count]' \ + 'o[keep file with lowest number of hardlinks outside of the paths traversed by rmlint]' \ + 'O[keep file with highest number of hardlinks outside of the paths traversed by rmlint]' +} + +(( $+functions[_rmlint_percent] )) || +_rmlint_percent() { + if compset -P '(100|[1-9][0-9]|[1-9])'; then + compadd "$@" -- '%' + elif [[ -z $PREFIX ]]; then + _message -e 'percent%%' + fi +} + +(( $+functions[_rmlint_clamp] )) || +_rmlint_clamp() { + _alternative \ + "factor: :_guard '((|0)(|.[0-9]#)|1(|.0#))' 'fac.tor [$1]'" \ + 'percent:percent%%:_rmlint_percent' \ + 'multiplier:offset: _rmlint_size "offset"' +} + +(( $+functions[_rmlint_files_or_separator] )) || +_rmlint_files_or_separator() { + if (( $words[(i)-] < CURRENT )); then + [[ -z $words[CURRENT] ]] && compadd "$@" -S '' -- - + return + fi + local -a alts=( 'files:file:_files' ) + (( $line[(I)//] || $+opt_args[--equal] )) || alts+=( 'separator:separator:(//)' ) + _alternative $alts +} + +_rmlint() { + if [[ $service = *.sh ]]; then + _arguments -s : \ + '(-)-h[show help message]' \ + '-d[do not ask before running]' \ + '-x[keep rmlint.sh; do not autodelete it]' \ + '-p[recheck that files are still identical before removing duplicates]' \ + '-r[allow deduplication of files on read-only btrfs snapshots (requires sudo)]' \ + '(-d -x)-n[do not perform any modifications, just print what would be done (implies -d and -x)]' \ + '-c[clean up empty directories while deleting duplicates]' \ + '-q[do not show progress]' \ + '-k[keep the timestamp of directories when removing duplicates]' \ + '-i[ask before deleting each file]' + return + fi + + local curcontext="$curcontext" state state_descr + local -a line + local -i ret=1 + typeset -A opt_args + + _arguments -s -w -C : \ + '(-T --types)'{-T,--types}'=[configure the types of lint rmlint will look for]: :_rmlint_types' \ + '*'{-o,--output}'=[configure the way rmlint outputs its results]:spec:_rmlint_output' \ + '*'{-O,--add-output}'=[configure the way rmlint outputs its results (preserve defaults)]:spec:_rmlint_output' \ + '*'{-c,--config}'=[configure a format]:spec:_rmlint_config' \ + '(-z --perms)'{-z,--perms}'=[only look into file if it is readable, writable or executable by the current user]: :_values -s "" perms r w x' \ + '(-a --algorithm)'{-a,--algorithm}'=[choose the algorithm to use for finding duplicate files]:algo:_rmlint_algorithm' \ + '*'{-p,--paranoid}'[increase the paranoia of rmlint'\''s duplicate algorithm]' \ + '*'{-P,--less-paranoid}'[decrease the paranoia of rmlint'\''s duplicate algorithm]' \ + '*'{-v,--loud}'[increase the verbosity]' \ + '*'{-V,--quiet}'[decrease the verbosity]' \ + '(-g --progress)'{-g,--progress}'[show a progressbar with sane defaults]' \ + '(-G --no-progress)'{-G,--no-progress}'[do not show a progressbar with sane defaults (default)]' \ + '(-D --merge-directories)'{-D,--merge-directories}'[makes rmlint use a special mode where all found duplicates are collected and checked if whole directory trees are duplicates]' \ + '(-j --honour-dir-layout)'{-j,--honour-dir-layout}'[only recognize directories as duplicates that have the same path layout]' \ + '(-y --sort-by)'{-y,--sort-by}'=[during output, sort the found duplicate groups by criteria described by order]:order:_rmlint_sort' \ + '(-w --with-color)'{-w,--with-color}'[use color escapes for pretty output (default)]' \ + '(-W --no-with-color)'{-W,--no-with-color}'[disable color escapes for pretty output]' \ + '(- *)'{-h,--help}'[show a shorter reference help text]' \ + '(- *)--help-all[show all help options]' \ + '(- *)'{-H,--show-man}'[show the full man page]' \ + '(- *)--version[print the version of rmlint]' \ + '(-s --size)'{-s,--size}'=[only consider files as duplicates in a certain size range]:range:_rmlint_size_range' \ + '(-d --max-depth)'{-d,--max-depth}'=[only recurse up to this depth]: :_guard "[0-9]#" "depth"' \ + '(-l --hardlinked)'{-l,--hardlinked}'[hardlinked files are treated as duplicates (default)]' \ + '--keep-hardlinked[rmlint will not delete any files that are hardlinked to an original in their respective group]' \ + '(-L --no-hardlinked)'{-L,--no-hardlinked}'[only one file (of a set of hardlinked files) is considered, all the others are ignored]' \ + '(-f --followlinks)'{-f,--followlinks}'[follow symbolic links]' \ + '(-F --no-followlinks)'{-F,--no-followlinks}'[ignore symbolic links completely]' \ + '(-@ --see-symlinks)'{-@,--see-symlinks}'[see symlinks and treats them like small files with the path to their target in them (default)]' \ + '(-x --no-crossdev)'{-x,--no-crossdev}'[stay always on the same device]' \ + '(-X --crossdev)'{-X,--crossdev}'[allow crossing mountpoints (default)]' \ + '(-r --hidden)'{-r,--hidden}'[traverse hidden directories]' \ + '(-R --no-hidden)'{-R,--no-hidden}'[don'\''t traverse hidden directories (default)]' \ + '--partial-hidden[traverse duplicate hidden directories]' \ + '(-b --match-basename)'{-b,--match-basename}'[only consider those files as dupes that have the same basename]' \ + '(-B --unmatched-basename)'{-B,--unmatched-basename}'[only consider those files as dupes that do not share the same basename]' \ + '(-e --match-with-extension)'{-e,--match-with-extension}'[only consider those files as dupes that have the same file extension]' \ + '(-E --no-match-with-extension)'{-E,--no-match-with-extension}'[don'\'t' consider those files as dupes that have the same file extension (default)]' \ + '(-i --match-without-extension)'{-i,--match-without-extension}'[only consider those files as dupes that have the same basename minus the file extension]' \ + '(-I --no-match-without-extension)'{-I,--no-match-without-extension}'[don'\'t' consider those files as dupes that have the same basename minus the file extension (default)]' \ + '(-n --newer-than-stamp)'{-n,--newer-than-stamp}'=[only consider files (and their size siblings for duplicates) newer than a certain modification time (mtime)]:timestamp_filename:_files' \ + '(-N --newer-than)'{-N,--newer-than}'=[don'\'t' consider files (and their size siblings for duplicates) newer than a certain modification time (mtime)]: :_rmlint_iso8601_or_unix_timestamp' \ + '(-k --keep-all-tagged)'{-k,--keep-all-tagged}'[don'\''t delete any duplicates that are in tagged paths]' \ + '(-K --keep-all-untagged)'{-K,--keep-all-untagged}'[don'\''t delete any duplicates that are in non-tagged paths]' \ + '(-m --must-match-tagged)'{-m,--must-match-tagged}'[only look for duplicates of which at least one is in one of the tagged paths]' \ + '(-M --must-match-untagged)'{-M,--must-match-untagged}'[only look for duplicates of which at least one is in one of the non-tagged paths]' \ + '(-S --rank-by)'{-S,--rank-by}'=[sort the files in a group of duplicates into originals and duplicates by one or more criteria]: :_rmlint_rank' \ + '--replay[read an existing json file and re-output it]' \ + '(-C --xattr)'{-C,--xattr}'[shortcut for --xattr-read, --xattr-write, --write-unfinished]' \ + '--xattr-read[read cached checksums from the extended file attributes]' \ + '--xattr-write[write cached checksums from the extended file attributes]' \ + '--xattr-clear[clear cached checksums from the extended file attributes]' \ + '(-U --write-unfinished)'{-U,--write-unfinished}'[include files in output that have not been hashed fully, i.e. files that do not appear to have a duplicate]' \ + '(-t --threads)'{-t,--threads}'=[the number of threads to use during file tree traversal and hashing (default: 16)]: :_guard "[0-9]#" "threads [16]"' \ + '(-u --limit-mem)'{-u,--limit-mem}'=[apply a maximum number of memory to use for hashing and --paranoid]:size: _rmlint_size' \ + '(-q --clamp-low)'{-q,--clamp-low}'=[only look at the content of files in the range of from low to (including) high (default: 0)]: : _rmlint_clamp 0' \ + '(-Q --clamp-top)'{-Q,--clamp-top}'=[only look at the content of files in the range of from low to (including) high (default: 1.0)]: : _rmlint_clamp 1.0' \ + '(-Z --mtime-window)'{-Z,--mtime-window}'=[only consider those files as duplicates that have the same content and the same modification time (mtime) within a certain window of T seconds (default: -1)]: :_guard "[0-9]#" "mtime window (seconds) [-1]"' \ + '--with-fiemap[enable reading the file extents on rotational disk in order to optimize disk access patterns (default)]' \ + '--without-fiemap[disable reading the file extents on rotational disk in order to optimize disk access patterns]' \ + '--gui[start the optional graphical frontend to rmlint called Shredder]:*: :->gui' \ + '--hash[make rmlint work as a multi-threaded file hash utility]:*: :->hash' \ + '--equal[check if the paths given on the commandline all have equal content]: :_rmlint_files_or_separator' \ + '(-0 --stdin0)'{-0,--stdin0}'[read null-separated file list from stdin]' \ + '--backup[do create backups of previous result files]' \ + '--no-backup[do not create backups of previous result files]' \ + '--dedupe[dedupe matching extents from source to dest (if filesystem supports)]:*:: := ->dedupe' \ + '--dedupe-xattr[check extended attributes to see if the file is already deduplicated]' \ + '--dedupe-readonly[(--dedupe option) even dedupe read-only snapshots (needs root)]' \ + '--is-reflink[test if two files are reflinks (share same data extents)]:*:: := ->reflink' \ + '*: :_rmlint_files_or_separator' && return + + case $state in + (gui) + _arguments -s -w : \ + '(- *)'{-h,--help}'[show help options]' \ + {-a,--add-location}'[add locations to locations view]' \ + {-s,--scan}'[add location to scan (as untagged path)]' \ + {-S,--scan-tagged}'[add location to scan (as tagged path)]' \ + {-l,--load-script}'[show `script` in editor view]' \ + '*'{-v,--verbose}'[be more verbose]' \ + '*'{-V,--less-verbose}'[be less verbose]' \ + {-c,--show-settings}'[show the settings view]' \ + '(- *)--version[show the version of Shredder]' && ret=0 + ;; + (hash) + _arguments -s -w : \ + '(- *)'{-h,--help}'[show help options]' \ + {-a,--algorithm}'[digest type \[bLAKE2B\]]:type:_rmlint_algorithm' \ + {-t,--num-threads}'[number of hashing threads \[8\]]: :_guard "[0-9]#" "threads [8]"' \ + {-b,--buffer-mbytes}'[megabytes read buffer \[256 MB\]]: :_guard "[0-9]#" "buffer (MB) [256]"' \ + {-i,--ignore-order}'[print hashes in order completed, not in order entered (reduces memory usage)]' \ + '*:file:_files' && ret=0 + ;; + (dedupe) + _arguments -s -w : \ + '-r[enable deduplication of read-only \[btrfs\] snapshots (requires root)]' \ + '(-V)*-v' \ + '(-v)*-V' \ + ':src:_files' \ + ':dst:_files' && ret=0 + ;; + (reflink) + _arguments -s -w : \ + '(-V)*-v' \ + '(-v)*-V' \ + ':file1:_files' \ + ':file2:_files' && ret=0 + ;; + esac + + return ret +} + +_rmlint "$@" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rslsync b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rslsync new file mode 100644 index 00000000..c72fb75d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rslsync @@ -0,0 +1,72 @@ +#compdef rslsync +# ------------------------------------------------------------------------------ +# Copyright (c) 2017 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for resilio sync 2.7.3 (https://www.resilio.com/individuals/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Fabian Klötzl (https://github.com/kloetzl) +# +# ------------------------------------------------------------------------------ + +_rslsync(){ + integer ret=1 + local -a args + args+=( + '(- *)--help[Print help]' + '--config[Use a configuration file]:file:_files' + '--storage[Storage path for identity and license]:path:_files -/' + '--identity[Creates user identity]:name:' + '--license[Apply owner license]:file:_files' + '--decrypt[Decrypt encrypted folder]:' + '--upgradedb[Upgrade databases in specified storage or upgrade a single db]:db:_files' + '--nodaemon[Do not daemonize]' + '--dump-sample-config[Print a sample configuration file]' + '--log[Set log file]:file:_files' + '(--help)--webui.listen[Set the webui listening interface]:ip\:port:' + '--generate-secret[Generate a read/write key]::version:(2)' + '--get-ro-secret[Get the read-only key associated to a read/write key]:key:' + '--server[Set Management Console address]:ip\:port:' + ) + _arguments $args[@] && ret=0 + return ret +} + +_rslsync + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rspec b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rspec new file mode 100644 index 00000000..944b6ff7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rspec @@ -0,0 +1,111 @@ +#compdef rspec +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for RSpec 3.12.0 (https://rspec.info/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Kazuya Takeshima (https://github.com/mitukiii) +# +# ------------------------------------------------------------------------------ + + +_rspec() { + local context state line curcontext="$curcontext" + + _arguments -C \ + *'-I[Specify PATH to add to $LOAD_PATH (may be used more than once)]:PATH:_files -/' \ + '*'{-r,--require}'[Require a file]:PATH:_files' \ + '*'{-O,--options}'[Specify the path to a custom options file]:PATH:_files' \ + '--order[Run examples by the specified order type]: :->order' \ + '--seed[Equivalent of --order rand:SEED]: :_guard "[[\:digit\:]]#" "SEED"' \ + '--bisect[Repeatedly runs the suite in order to isolate the failures to the smallest reproducible case]' \ + '--only-failures[Filter to just the examples that failed the last time they ran]' \ + '(-n --next-failure)'{-n,--next-failure}'[Apply `--only-failures` and abort after one failure (equivalent to `--only-failures --fail-fast --order defined`)]' \ + '--fail-fast[Abort the run on first failure]' \ + '--no-fail-fast[Do not abort the run on first failure]' \ + '--failure-exit-code[Override the exit code used when there are failing specs]: :_guard "[[\:digit\:]]#" "CODE"' \ + '--error-exit-code[Override the exit code used when there are errors loading or running specs]:code' \ + '--dry-run[Print the formatter output of your suite without running any examples or hooks]' \ + '(-X --drb)'{-X,--drb}'[Run examples via DRb]' \ + '--drb-port[Port to connect to the DRb server]: :_guard "[[\:digit\:]]#" "PORT"' \ + '(-f --format)'{-f,--format}'[Choose a formatter]:FORMATTER:(progress documentation html json failures)' \ + '(-o --out)'{-o,--out}'[Write output to a file instead of $stdout]:FILE:_files' \ + '--deprecation-out[Write deprecation warnings to a file instead of $stderr]:FILE:_files' \ + '(-b --backtrace)'{-b,--backtrace}'[Enable full backtrace]' \ + '--force-color[Force the output to be in color, even if the output is not a TTY]' \ + '--no-color[Force the output to not be in color, even if the output is a TTY]' \ + '(-p --profile)'{-p,--profile}'[Enable profiling of examples and list the slowest examples (default: 10)]: :_guard "[[\:digit\:]]#" "COUNT"' \ + '--no-profile[Disable profiling of examples]' \ + '(-w --warnings)'{-w,--warnings}'[Enable ruby warnings]' \ + '(-P --pattern)'{-P,--pattern}'[Load files matching pattern (default: "spec/**/*_spec.rb")]:PATTERN:' \ + '--exclude-pattern[Load files except those matching pattern]:PATTERN:' \ + '(-e --example)'{-e,--example}'[Run examples whose full nested names include STRING (may be used more than once)]:STRING:' \ + '(-E --example-matches)'{-E,--example-matches}'[Run examples whose full nested names match REGEX]:regex' \ + '(-t --tag)'{-t,--tag}'[Run examples with the specified tag, or exclude examples by adding ~ before the tag]: :->tag' \ + '--default-path[Set the default path where RSpec looks for examples (can be a path to a file or a directory)]:PATH:_files' \ + '(- *)--init[Initialize your project with RSpec]' \ + '(- *)'{-h,--help}"[You're looking at it]" \ + '(- *)'{-v,--version}'[Display the version]' \ + '*:files or directories:_files' + + case "$state" in + order) + if compset -P '*:'; then + _guard '[[:digit:]]#' 'SEED' + else + _values 'TYPE[:SEED]' \ + 'defined[examples and groups are run in the order they are defined]' \ + 'rand[randomize the order of groups and examples]' \ + 'random[alias for rand]' \ + 'recently-modified[run the most recently modified files first]' + fi + ;; + tag) + if compset -P '*:'; then + _message 'VALUE' + else + _message 'TAG[:VALUE]' + fi + ;; + esac +} + +_rspec "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rsvm b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rsvm new file mode 100644 index 00000000..3840eb26 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rsvm @@ -0,0 +1,88 @@ +#compdef rsvm +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for rsvm (https://github.com/sdepold/rsvm). +# Adapted from Docker Machine completion by hhatto (https://github.com/ilkka) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * michaelmior (https://github.com/michaelmior) +# +# ------------------------------------------------------------------------------ + +# helper function for completing available rusts +__rusts() { + declare -a rusts_cmd + rusts_cmd=($(ls "$HOME/.rsvm/versions")) + _describe 'rusts' rusts_cmd +} + +# subcommands +local -a _rsvm_cmds + +_rsvm_cmds=( + 'help:Show a help message' \ + 'install:Download and install a version' \ + 'uninstall:Uninstall a version' \ + 'use:Activate a version for now and the future' \ + 'ls:List all installed versions of rust' \ + 'ls-remote:List remote versions available for install' \ + 'ls-channel:Print a channel version available for install' \ +) + +# subcommand completion functions +__uninstall() { + __rusts +} + +__use() { + __rusts +} + +# common args +_arguments \ + '--help[show help]' \ + '--version[print the version]' \ + '*:: :->command' + +# start rusts! +if (( CURRENT == 1 )); then + _describe -t commands 'rsvm command' _rsvm_cmds +fi + +local -a _command_args +case "$words[1]" in + uninstall) + __uninstall ;; + use) + __use ;; +esac diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rubocop b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rubocop new file mode 100644 index 00000000..deca57d6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_rubocop @@ -0,0 +1,128 @@ +#compdef rubocop +# ------------------------------------------------------------------------------ +# Copyright (c) 2015 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for rubocop 1.55 (https://github.com/rubocop/rubocop) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Akira Maeda +# * Shohei Yoshida +# +# ------------------------------------------------------------------------------ + +local curcontext="$curcontext" state line ret=1 +typeset -A opt_args + +_rubocop_format_params() { + local -a formatter=( + "autogenconf" "clang" "emacs" "files" "fuubar" "github" "html" "json" "junit" + "markdown" "offenses" "pacman" "progress" "quiet" "simple" "tap" "worst" + ) + + _values 'formatter' $formatter +} + +_arguments \ + '(-l --lint)'{-l,--lint}'[Run only lint cops]' \ + '(-x --fix-layout)'{-x,--fix-layout}'[Run only layout cops, with autocorrect on]' \ + '--safe[Run only safe cops]' \ + '*--except[Exclude the given cops]:cops' \ + '*--only[Run only the given cops]:cops' \ + '--only-guide-cops[Run only cops for rules that link to a style guide]' \ + '(-F --fail-fast)'{-f,--fail-fast}'[Inspect files in order of modification time and stop after the first file containing offenses]' \ + '--disable-pending-cops[Run without pending cops]' \ + '--enable-pending-cops[Run with pending cops]' \ + '--ignore-disable-comments[Run cops even when they are disabled locally by a `rubocop:disable` directive]' \ + '--force-exclusion[Any files excluded by `Exclude` in configuration files will be excluded, even if given explicitly as arguments]' \ + '--only-recognized-file-types[Inspect files given on the command line only if they are listed in configuration]' \ + '--ignore-parent-exclusion[Prevent from inheriting "AllCops/Exclude" from parent folders]' \ + '--ignore-unrecognized-cops[Ignore unrecognized cops or departments in the config]' \ + '(-s --stdin)'{-s,--stdin}'[Pipe source from STDIN, using FILE in offense reports]: :_files' \ + '(-P --parallel --no-parallel)'{-p,--parallel}'[Use available CPUs to execute inspection in parallel]' \ + '(-P --parallel --no-parallel)--no-parallel[Execute not parallel]' \ + '--raise-cop-error[Raise cop-related errors with cause and location]' \ + '--fail-level[Minimum severity for exit with error code]:severity:(autocorrect info refactor convention warning error fatal)' \ + '(-C --cache)'{-C,--cache}'[Use result caching or not]: :(TRUE FALSE)' \ + '--cache-root[Set the cache root directory]: :_files -/' \ + '--lsp[Start a language server listening on STDIN]' \ + '--server[If a server process has not been started yet start the server process and execute inspection with server]' \ + '--restart-server[Restart server process]' \ + '--start-server[Start server process]' \ + '--stop-server[Stop server process]' \ + '--server-status[Show server status]' \ + '--no-detach[Run the server process in the foreground]' \ + '(-f --format)'{-f,--format}'[Choose an output formatter]:FORMATTER:_rubocop_format_params' \ + '(-D --display-cop-names)'{-D,--display-cop-names}'[Display cop names in offense messages]' \ + '(-E --extra-details)'{-E,--extra-details}'[Display extra details in offense messages]' \ + '(-S --display-style-guide)'{-S,--display-style-guide}'[Display style guide URLs in offense messages]' \ + '(-o --out)'{-o,--out}'[Write output to a file instead of STDOUT]: :_files' \ + '--stderr[Write all output to stderr except for the autocorrected source]' \ + '--display-time[Display elapsed time in seconds]' \ + '--display-only-failed[Only output offense messages]' \ + '--display-only-fail-level-offenses[Only output offense messages at the specified --fail-level or above]' \ + '--display-only-correctable[Only output correctable offense messages]' \ + '--display-only-safe-correctable[Only output safe-correctable offense messages with combined with --display-only-correctable]' \ + '(-a --autocorrect)'{-a,--autocorrect}"[Auto-correct offenses(only when it's safe)]" \ + '(-A --autocorrect-all)'{-A,--autocorrect-all}'[Autocorrect offenses(safe and unsafe)]' \ + '--auto-gen-config[Generate a configuration file acting as a TODO list]' \ + '--regenerate-todo[Regenerate the TODO configuration file using the last configuration]' \ + '(--no-exclude-limit)--exclude-limit[Set the limit for how many files to explicitly exclude]:count' \ + '(--exclude-limit)--no-exclude-limit[Do not set the limit for how many files to exclude]' \ + '--offense-counts[Include offense counts in configuration file generated by --auto-gen-config]' \ + '--auto-gen-only-exclude[Generate only Exclude parameters and not Max when running --auto-gen-config]' \ + '--auto-gen-timestamp[Include the data and time when the --auto-gen-config was run in the file it generates]' \ + '--auto-gen-enforced-style[Add a setting to the TODO configuration file to enforce the style used]' \ + '(-L --list-target-files)'{-L,--list-target-files}'[List all files RuboCop will inspect]' \ + '*--show-cops[Show the given cops or all cops]::cops' \ + '--show-docs-url[Display url to documentation for the given cops or base url by default]::cops' \ + '--init[Generate a .rubocop.yml file in the current directory]' \ + '(-c --config)'{-c,--config}'[Specify configuration file]: :_files' \ + '(-d --debug)'{-d,--debug}'[Display debug info]' \ + '(-r --require)'{-r,--require}'[Require Ruby file]: :_files' \ + '(--no-color --color)--color[Force color output on]' \ + '(--no-color --color)--no-color[Force color output off]' \ + '(-v --version -V --verbose-version)'{-v,--version}'[Display version]' \ + '(-V --verbose-version -v --version)'{-V,--verbose-version}'[Display verbose version]' \ + '--profile[Profile rubocop]' \ + '--memory[Profile rubocop memory usage]' \ + '(- *)'{-h,--help}'[Show help]' \ + '*: :_files' && ret=0 + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_sbt b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_sbt new file mode 100644 index 00000000..86daa5b4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_sbt @@ -0,0 +1,146 @@ +#compdef sbt +# ------------------------------------------------------------------------------ +# Copyright (c) 2013 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for sbt 1.8.0 (https://www.scala-sbt.org). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Tony Sloane +# * Mirko Caserta +# * Shohei Yoshida +# +# ------------------------------------------------------------------------------ + +_sbt() { + typeset -A opt_args + local context state line + local curcontext="$curcontext" + local ret=1 + + _arguments \ + '(- *)'{-h,--help}'[print help message]' \ + '(-v --verbose)'{-v,--verbose}'[this runner is chattier]' \ + '(- *)'{-V,--version}'[print sbt version information]' \ + '--numeric-version[print the version of sbt script]' \ + '(-d --debug)'{-d,--debug}'[set sbt log level to debug]' \ + '--no-colors[disable ANSI color codes]' \ + '--color=[enable or disable ANSI color codes]: :(auto always true false never)' \ + '--supershell=[enable or disable super shell]: :(auto always true false never)' \ + '--traces[generate Trace Event report on shutdown]' \ + '--timings[display task timings report on shutdown]' \ + '--sbt-create[start sbt even if current directory contains no sbt project]' \ + '--sbt-dir[path to global settings/plugins directory]: :_files -/' \ + '--sbt-boot[path to shared boot directory]: :_files -/' \ + '--sbt-cache[path to global cache directory]: :_files -/' \ + '--ivy[path to local Ivy repository]: :_files -/' \ + '--mem[set memory options]:memory' \ + '--no-share[use all local caches; no sharing]' \ + '--no-global[uses global caches, but does not use global directory]' \ + '--jvm-debug[Turn on JVM debugging, open at the given port]:port' \ + '--batch[disable interactive mode]' \ + '--sbt-version[use the specified version of sbt]:version' \ + '--sbt-jar[use the specified jar as the sbt launcher]: :_files' \ + '--java-home[alternate JAVA_HOME]: :_files -/' \ + '1: :_sbt_commands' \ + '*:: :->args' && ret=0 + + case "$state" in + (args) + case $words[1] in + (new) + local -a g8_templates=( + foundweekends/giter8.g8 + scala/scala-seed.g8 + scala/scala3.g8 + scala/hello-world.g8 + scala/scalatest-example.g8 + playframework/play-scala-seed.g8 + playframework/play-java-seed.g8 + lagom/lagom-scala.g8 + lagom/lagom-java.g8 + scala-native/scala-native.g8 + scala-native/sbt-crossproject.g8 + http4s/http4s.g8 + unfiltered/unfiltered.g8 + scalatra/scalatra-sbt.g8 + ) + _values 'g8_templates' $g8_templates + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_sbt_commands] )) || +_sbt_commands() { + local -a commands=( + 'about:Displays basic information about sbt and the build' + 'clean:delete files produced by the build' + 'compile:compile sources' + 'console:start the Scala REPL with project classes on the classpath' + 'console-quick:start the Scala REPL with project deps on the classpath' + 'console-project:start the Scala REPL w/sbt+build-def on the classpath' + 'dist:generate distribution artifacts' + 'dist\:clean:clean distribution artifacts' + 'doc:generate API documentation' + 'new:Creates a new sbt build' + 'package:produce the main artifact, such as a binary jar' + 'package-doc:produce a doc artifact, such as a jar containing API docs' + 'package-src:produce a source artifact, such as a jar containing sources' + 'projects:Lists the names of available projects' + 'publish:publish artifacts to a repository' + 'publish-local:publish artifacts to the local repository' + 'run:run a main class' + 'run-main:run the main class selected by the first argument' + 'settings:Lists the settings defined for the current project' + 'shutdownall:shutdown all running sbt-launch processes' + 'tasks:Lists the tasks defined for the current project' + 'test:execute all tests' + 'test-only:execute the tests provided as arguments' + 'test-quick:execute previously failed tests' + 'update:resolve and optionally retrieve dependencies' + ) + + _describe -t subcommands 'subcommand' commands +} + +_sbt "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_scala b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_scala new file mode 100644 index 00000000..0de54ab2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_scala @@ -0,0 +1,350 @@ +#compdef scala scalac +# ------------------------------------------------------------------------------ +# Copyright (c) 2012 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for scala and scalac 3.2.1 (https://www.scala-lang.org/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Tony Sloane +# * Shohei Yoshida +# +# ------------------------------------------------------------------------------ + +_scala() { + local ret=1 + + local -a common_options=( + "-Dproperty=[Pass -Dproperty=value directly to the runtime system]:value" + "-J-[Pass directly to the runtime system]:flag" + "-P\:-[Pass an option to a plugin, e.g. -P::]" + "-V[Print a synopsis of verbose options]" + "-W[Print a synopsis of warning options]" + "-Wconf[Configure compiler warnings]" + "-Werror[Fail the compilation if there are any warnings]" + "-X[Print a synopsis of advanced options]" + "-Y[Print a synopsis of private options]" + "-bootclasspath+[Override location of bootstrap class files]: :_files -/" + "-classpath+[Specify where to find user class files]: :_files -/" + "-color\:-[Colored output]: :(always never)" + "-coverage-out\:-[Destination for coverage classfiles and instrumentation data]: :_files -/" + "-d+[Destination for generated classfiles]: directory or jar file:_files" + "-deprecation[Emit warning and location for usages of deprecated APIs]" + "-encoding+[Specify character encoding used by source files]:encoding" + "-explain[Explain errors in more detail]" + "-explain-types[Explain type errors in more detail (deprecated, use -explain instead)]" + "-extdirs\:-[Override location of installed extensions]: :_files -/" + "-feature[Emit warning and location for usages of features that should be imported explicitly]" + "-from-tasty[Compile classes from tasty files. The arguments are .tasty or .jar files]" + "(* -)-help[Print a synopsis of standard options]" + "-indent[Together with -rewrite, remove {...} syntax when possible due to significant indentation]" + "-java-output-version[Compile code with classes specific to the given version of the Java platform]" + "-javabootclasspath+[Override java boot classpath]: :_files -/" + "-javaextdirs+[Override java extdirs classpath]: :_files -/" + "-language\:-[Enable one or more language features]: :_scala_features" + "-new-syntax[Require 'then' and 'do' in control expressions]" + "-no-indent[Require classical {...} syntax, indentation is not significant]" + "-nowarn[Silence all warnings]" + "-old-syntax[Require '(...)' around conditions]" + "-pagewidth:-[Set page width]:width" + "-print-lines[Show source code line numbers]" + "-print-tasty[Prints the raw tasty]" + "-project-url\:-[The source repository of your project]:url" + "-rewrite[When used in conjunction with a '...-migration' source version, rewrites sources to migrate to new]" + "-scalajs[Compile in Scala.js mode (requires scalajs-library.jar on the classpath)]" + "-scalajs-genStaticForwardersForNonTopLevelObjects[Generate static forwarders even for non-top-level objects (Scala.js only)]" + "-scalajs-mapSourceURI[rebases source URIs from uri1 to uri2 (or to a relative URI) for source maps (Scala.js only)]" + "-semanticdb-target[Specify an alternative output directory for SemanticDB files]" + "-source\:-[source version]:version" + "-sourcepath+[Specify location(s) of source files]:source file directory:_files -/" + "-sourceroot+[Specify workspace root directory]: :_files -/" + "-unchecked[Enable additional warnings where generated code depends on assumptions]" + "-uniqid[Uniquely tag all identifiers in debugging output]" + "-usejavacp[Utilize the java.class.path in classpath resolution]" + "-verbose[Output messages about what the compiler is doing]" + "(- *)-version[Print product version and exit]" + ) + + local -a advanced_options=( + "-Xcheck-macros[Check some invariants of macro generated code while expanding macros]" + "-Xignore-scala2-macros[Ignore errors when compiling code that calls Scala2 macros, these will fail at runtime]" + "-Ximplicit-search-limit\:-[Maximal number of expressions to be generated in an implicit search]" + "-Ximport-suggestion-timeout\:-[Timeout (in ms) for searching for import suggestions when errors are reported]" + "-Xmacro-settings[List of settings which exposed to the macros]" + "-Xmain-class[Class for manifest's Main-Class entry (only useful with -d )]" + "-Xmax-inlined-trees\:-[Maximal number of inlined trees]" + "-Xmax-inlines\:-[Maximal number of successive inlines]" + "-Xmigration[Warn about constructs whose behavior may have changed since version]" + "-Xmixin-force-forwarders\:-[Generate forwarder methods in classes inhering concrete methods from traits]: :(true junit false)" + "-Xno-forwarders[Do not generate static forwarders in mirror classes]" + "-Xplugin[Load a plugin from each classpath]" + "-Xplugin-disable[Disable plugins by name]" + "-Xplugin-list[Print a synopsis of loaded plugins]" + "-Xplugin-require[Abort if a named plugin is not loaded]" + "-Xpluginsdir\:-[Path to search for plugin archives]: :_files -/" + "-Xprint-diff[Print changed parts of the tree since last print]" + "-Xprint-diff-del[Print changed parts of the tree since last print including deleted parts]" + "-Xprint-inline[Show where inlined code comes from]" + "-Xprint-suspension[Show when code is suspended until macros are compiled]" + "-Xprint-types[Print tree types (debugging option)]" + "-Xprompt[Display a prompt after each error (debugging option)]" + "-Xrepl-disable-display[Do not display definitions in REPL]" + "-Xsemanticdb[Store information in SemanticDB]" + "-Xunchecked-java-output-version[Emit bytecode for the specified version of the Java platform]:java_version" + "-Xverify-signatures[Verify generic signatures in generated bytecode]" + "-Xwiki-syntax[Retains the Scala2 behavior of using Wiki Syntax in Scaladoc]" + ) + + local -a private_options=( + "-Ycc[Check captured references (warning: extremely experimental and unstable)]" + "-Ycc-debug[Used in conjunction with -Ycc, debug info for captured references]" + "-Ycc-no-abbrev[Used in conjunction with -Ycc, suppress type abbreviations]" + "-Ycheck[Check the tree at the end of]" + "-Ycheck-all-patmat[Check exhaustivity and redundancy of all pattern matching (used for testing the algorithm)]" + "-Ycheck-mods[Check that symbols and their defining trees have modifiers in sync]" + "-Ycheck-reentrant[Check that compiled program does not contain vars that can be accessed from a global root]" + "-Ycook-docs[Cook the documentation (type check '@usecase', etc.)]" + "-Ydebug[Increase the quantity of debugging output]" + "-Ydebug-error[Print the stack trace when any error is caught]" + "-Ydebug-flags[Print all flags of definitions]" + "-Ydebug-missing-refs[Print a stacktrace when a required symbol is missing]" + "-Ydebug-names[Show internal representation of names]" + "-Ydebug-pos[Show full source positions including spans]" + "-Ydebug-trace[Trace core operations]" + "-Ydebug-tree-with-id[Print the stack trace when the tree with the given id is created]" + "-Ydebug-type-error[Print the stack trace when a TypeError is caught]" + "-Ydebug-unpickling[Print the stack trace when an error occurs when reading Tasty]" + "-Ydetailed-stats[Show detailed internal compiler stats (needs Stats.enabled to be set to true)]" + "-YdisableFlatCpCaching[Do not cache flat classpath representation of classpath elements from jars across compiler]" + "-Ydrop-docs[Drop documentation when scanning source files]" + "-Ydump-classes[Dump the generated bytecode to .class files (useful for reflective compilation that utilizes]" + "-Ydump-sbt-inc[For every compiled foo.scala, output the API representation and dependencies used for sbt]" + "-Yexplain-lowlevel[When explaining type errors, show types at a lower level]" + "-Yexplicit-nulls[Make reference types non-nullable. Nullable types can be expressed with unions: e.g]" + "-Yforce-sbt-phases[Run the phases used by sbt for incremental compilation (ExtractDependencies and ExtractAPI)]" + "-Yfrom-tasty-ignore-list[List of 'tasty' files in jar files that will not be loaded when using -from-tasty]" + "-Yindent-colons[(disabled: use -language:experimental.fewerBraces instead)]" + "-Yinstrument[Add instrumentation code that counts allocations and closure creations]" + "-Yinstrument-defs[Add instrumentation code that counts method calls; needs -Yinstrument to be set, too]" + "-Ykind-projector\:-[Allow '*' as type lambda placeholder to be compatible with kind projector. When invoked as]: :(disable underscores)" + "-Ylog[Log operations during]" + "-Ylog-classpath[Output information about what classpath is being applied]" + "-Yno-decode-stacktraces[Show raw StackOverflow stacktraces, instead of decoding them into triggering operations]" + "-Yno-deep-subtypes[Throw an exception on deep subtyping call stacks]" + "-Yno-double-bindings[Assert no namedtype is bound twice (should be enabled only if program is error-free)]" + "-Yno-experimental[Disable experimental language features]" + "-Yno-generic-signatures[Suppress generation of generic signatures for Java]" + "-Yno-imports[Compile without importing scala.*, java.lang.*, or Predef]" + "-Yno-kind-polymorphism[Disable kind polymorphism]" + "-Yno-patmat-opt[Disable all pattern matching optimizations]" + "-Yno-predef[Compile without importing Predef]" + "-Yplain-printer[Pretty-print using a plain printer]" + "-Yprint-debug[When printing trees, print some extra information useful for debugging]" + "-Yprint-debug-owners[When printing trees, print owners of definitions]" + "-Yprint-level[print nesting levels of symbols and type variables]" + "-Yprint-pos[Show tree positions]" + "-Yprint-pos-syms[Show symbol definitions positions]" + "-Yprint-syms[When printing trees print info in symbols instead of corresponding info in trees]" + "-Yprofile-destination[Where to send profiling output - specify a file, default is to the console]" + "-Yprofile-enabled[Enable profiling]" + "-Yprofile-external-tool[Enable profiling for a phase using an external tool hook. Generally only useful for a single]" + "-Yprofile-run-gc[Run a GC between phases - this allows heap size to be accurate at the expense of more time]" + "-Yread-docs[Read documentation from tasty]" + "-Yrecheck-test[Run basic rechecking (internal test only)]" + "-Yrequire-targetName[Warn if an operator is defined without a @targetName annotation]" + "-Yresolve-term-conflict\:-[Resolve term conflicts]: :(package object error)" + "-Yretain-trees[Retain trees for top-level classes, accessible from ClassSymbol#tree]" + "-Ysafe-init[Ensure safe initialization of objects]" + "-Yscala2-unpickler\:-[Control where we may get Scala 2 symbols from]: :(always never)" + "-Yshow-print-errors[Don't suppress exceptions thrown during tree printing]" + "-Yshow-suppressed-errors[Also show follow-on errors and warnings that are normally suppressed]" + "-Yshow-tree-ids[Uniquely tag all tree nodes in debugging output]" + "-Yshow-var-bounds[Print type variables with their bounds]" + "-Yskip[Skip]" + "-Ystop-after[Stop after]" + "-Ystop-before[Stop before]" + "-Ytest-pickler[Self-test for pickling functionality; should be used with -Ystop-after:pickler]" + ) + + local -a scala_options=( + "-e+[execute as if entered in the repl]:string" + "-save[save the compiled script in a jar for future use]" + ) + + case $words[$CURRENT] in + (-X*) + _arguments $advanced_options && ret=0 + ;; + (-Y*) + _arguments $private_options && ret=0 + ;; + (*) + case $service in + (scala) + _arguments $scala_options $common_options "*::filename:_files" && ret=0 + ;; + (scalac) + _arguments $common_options "*::filename:_files" && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_scala_features] )) || +_scala_features() { + local -a features=( + "adhocExtensions" "before" "dynamics" "experimental.captureChecking" + "experimental.dependent" "experimental.erasedDefinitions" "experimental.macros" + "implicitConversions" "noAutoTupling" "noob" "postfixOps" "strictEquality" + "unsafeNulls" + ) + _values 'features' $features +} + +(( $+functions[_scala_phases] )) || +_scala_phases() { + local -a phases=( + "parser:scan and parse sources" + "typer:type the trees" + "inlinedPositions:check inlined positions" + "sbt-deps:sends information on classes' dependencies to sbt" + "extractSemanticDB:extract info into .semanticdb files" + "posttyper:additional checks and cleanups after type checking" + "prepjsinterop:additional checks and transformations for Scala.js" + "sbt-api:sends a representation of the API of classes to sbt" + "SetRootTree:set the rootTreeOrProvider on class symbols" + "pickler:generates TASTy info" + "inlining:inline and execute macros" + "postInlining:add mirror support for inlined code" + "staging:check staging levels and heal staged types" + "splicing:splicing" + "pickleQuotes:turn quoted trees into explicit run-time data structures" + "instrumentCoverage:instrument code for coverage checking" + "firstTransform:some transformations to put trees into a canonical form" + "checkReentrant:check no data races involving global vars" + "elimPackagePrefixes:eliminate references to package prefixes in Select nodes" + "cookComments:cook the comments: expand variables, doc, etc." + "checkStatic:check restrictions that apply to @static members" + "checkLoopingImplicits:check that implicit defs do not call themselves in an infinite loop" + "betaReduce:reduce closure applications" + "inlineVals:check right hand-sides of an 'inline val's" + "expandSAMs:expand SAM closures to anonymous classes" + "elimRepeated:rewrite vararg parameters and arguments" + "refchecks:checks related to abstract members and overriding" + "initChecker:check initialization of objects" + "crossVersionChecks:check issues related to deprecated and experimental" + "protectedAccessors:add accessors for protected members" + "extmethods:expand methods of value classes with extension methods" + "uncacheGivenAliases:avoid caching RHS of simple parameterless given aliases" + "elimByName:map by-name parameters to functions" + "hoistSuperArgs:hoist complex arguments of supercalls to enclosing scope" + "forwardDepChecks:ensure no forward references to local vals" + "specializeApplyMethods:adds specialized methods to FunctionN" + "tryCatchPatterns:compile cases in try/catch" + "patternMatcher:compile pattern matches" + "preRecheck:preRecheck" + "recheck:recheck" + "preRecheck:preRecheck" + "cc:cc" + "elimOpaque:turn opaque into normal aliases" + "explicitJSClasses:make all JS classes explicit" + "explicitOuter:add accessors to outer classes from nested ones" + "explicitSelf:make references to non-trivial self types explicit as casts" + "interpolators:optimize s, f, and raw string interpolators" + "pruneErasedDefs:drop erased definitions and simplify erased expressions" + "uninitialized:eliminates 'compiletime.uninitialized'" + "inlinePatterns:remove placeholders of inlined patterns" + "vcInlineMethods:inlines calls to value class methods" + "seqLiterals:express vararg arguments as arrays" + "intercepted:rewrite universal '!=', '##' methods" + "getters:replace non-private vals and vars with getter defs" + "specializeFunctions:specialize Function{0,1,2} by replacing super with specialized super" + "specializeTuples:replaces tuple construction and selection trees" + "liftTry:lift any try that might be executed on a non-empty expression stack" + "collectNullableFields:collect fields that can be nulled out after use in lazy initialization" + "elimOuterSelect:expand outer selections" + "resolveSuper:implement super accessors" + "functionXXLForwarders:add forwarders for FunctionXXL apply methods" + "paramForwarding:add forwarders for aliases of superclass parameters" + "genericTuples:optimize generic operations on tuples" + "letOverApply:lift blocks from receivers of applications" + "arrayConstructors:intercept creation of (non-generic) arrays and intrinsify" + "erasure:rewrite types to JVM model" + "elimErasedValueType:expand erased value types to their underlying implmementation types" + "pureStats:remove pure statements in blocks" + "vcElideAllocations:peep-hole optimization to eliminate unnecessary value class allocations" + "etaReduce:reduce eta expansions of pure paths" + "arrayApply:optimize 'scala.Array.apply'" + "addLocalJSFakeNews:adds fake new invocations to local JS classes in calls to 'createLocalJSClass'" + "elimPolyFunction:rewrite PolyFunction subclasses to FunctionN subclasses" + "tailrec:rewrite tail recursion to loops" + "completeJavaEnums:fill in constructors for Java enums" + "mixin:expand trait fields and trait initializers" + "lazyVals:expand lazy vals" + "memoize:add private fields to getters and setters" + "nonLocalReturns:expand non-local returns" + "capturedVars:represent vars captured by closures as heap objects" + "constructors:collect initialization code in primary constructors" + "instrumentation:count calls and allocations under -Yinstrument" + "lambdaLift:lifts out nested functions to class scope" + "elimStaticThis:replace This references to static objects by global identifiers" + "countOuterAccesses:identify outer accessors that can be dropped" + "dropOuterAccessors:drop unused outer accessors" + "checkNoSuperThis:check that supercalls don't contain references to This" + "flatten:lift all inner classes to package scope" + "transformWildcards:replace wildcards with default values" + "moveStatic:move static methods from companion to the class itself" + "expandPrivate:widen private definitions accessed from nested classes" + "restoreScopes:repair rendered invalid scopes" + "selectStatic:get rid of selects that would be compiled into GetStatic" + "junitBootstrappers:generate JUnit-specific bootstrapper classes for Scala.js" + "Collect:entry points collect all entry points and save them in the context" + "collectSuperCalls:find classes that are called with super" + "repeatableAnnotations:aggregate repeatable annotations" + "genSJSIR:generate .sjsir files for Scala.js" + "genBCode:generate JVM bytecode" + ) + + _describe -t phases 'phases' phases +} + +_scala "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_screencapture b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_screencapture new file mode 100644 index 00000000..766d19c0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_screencapture @@ -0,0 +1,78 @@ +#compdef screencapture +# ------------------------------------------------------------------------------ +# Copyright (c) 2023 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for screencapture command +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_arguments \ + '-c[force screen capture to go to the clipboard]' \ + '(-i -J -s -w -W)-b[capture touch bar only non interactive modes]' \ + '(-b -i -J -s -w -W)-C[capture the cursor as well as the screen only in non interactive modes]' \ + '-d[display errors to the user graphically]' \ + '(-b -C)-i[capture screen interactively. ctrl clipboard, space toggle mode, escape cancel]' \ + '-m[only capture the main monitor]' \ + '-D[screen capture or record from the display specified]:display_number:' \ + '(-b -s)-o[in window capture mode, do not capture the shadow of the window]' \ + '-p[screen capture will use the default settings for capture]' \ + '-M[screen capture output will go to a new Mail message]' \ + '-P[screen capture output will open in Preview or QuickTime Player]' \ + '-I[screen capture output will open in Messages]' \ + '-B[screen capture output will open in app with bundle ID]:bundle_id:' \ + '(-b -i -w -W)-s[only allow mouse selection mode]' \ + '-S[in window capture mode, capture the screen not the window]' \ + '-J+[sets the starting of interactive capture]:style:(selection window video)' \ + '(-p)-t[image format to create default is png]:format:(png pdf jpg tiff gif)' \ + '-T+[take the picture after a delay of seconds]:seconds:' \ + '(-b -i -s -W)-w[only allow window selection mode]' \ + '(-b -i -s -w)-W[start interaction in window selection mode]' \ + '-x[do not play sounds]' \ + '-a[do not include windows attached to selected windows]' \ + '-r[do not add dpi meta data to image]' \ + '-l[capture this windows ID]:window_id:' \ + '(-b -i -s -w -W)-R[capture screen rect]:rect:' \ + '(-b)-v[capture video recording of the screen]::->video' \ + '-V+[limits video capture to specified seconds]:seconds:' \ + '-g[captures audio during a video recording using default input]' \ + '-G[captures audio during a video recording using audio ID specified]' \ + '-k[show clicks in video recording mode]' \ + '-U[Show interactive toolbar in interactive mode]' \ + '-u[present UI after screencapture is complete]' \ + '*:files:_files' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_scrub b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_scrub new file mode 100644 index 00000000..7b24fef2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_scrub @@ -0,0 +1,93 @@ +#compdef scrub +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for scrub 2.6.1 (https://linux.die.net/man/1/scrub). +# +# A utility which iteratively writes patterns on files or disk devices +# to make retrieving the data more difficult. +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Jindřich Pilař (https://github.com/JindrichPilar) +# +# ------------------------------------------------------------------------------ + +_scrub_patterns() { + local patterns=( + 'nnsa:4-pass NNSA Policy Letter NAP-14.1-C (XVI-8)' + 'dod:4-pass DoD 5220.22-M section 8-306 procedure' + 'bsi:9-pass method recommended by the German Center of Security in Information Technologies' + "gutmann:The canonical 35-pass sequence described in Gutmann's paper cited below" + 'schneier:7-pass method described by Bruce Schneier in "Applied Cryptography"' + "pfitzner7:Roy Pfitzner's 7-random-pass method" + "pfitzner33:Roy Pfitzner's 33-random-pass method" + "usarmy:US Army AR380-19 method" + "fillzero:1-pass pattern\: 0x00" + "fillff:1-pass pattern\: 0xff" + "random:1-pass pattern\: random(x1)" + "random2:2-pass pattern: random(x2)" + "old:6-pass pre-version 1.7 scrub method" + "fastold:5-pass pattern\: 0x00, 0xff, 0xaa, 0x55, verify" + 'custom=:1-pass custom pattern' + ) + + _describe 'pattern' patterns +} + +_scrub() { + _arguments -s -S \ + "(- 1 *)"{-v,--version}"[Print scrub version and exit]" \ + {-r,--remove}"[Remove the file after scrubbing]" \ + {-p,--pattern}"[Select the patterns to write]:pattern:_scrub_patterns" \ + {-b,--blocksize}"[Perform read and write calls using the specified blocksize (in bytes)]:block size:" \ + {-f,--force}"[Scrub even if target contains signature indicating it has already been scrubbed]" \ + {-S,--no-signature}"[Do not write scrub signature]" \ + {-X,--freespace}"[Create specified directory and fill it with files until write returns ENOSPC (file sys‐tem full), then scrub the files as us]:directory name:" \ + {-D,--dirent}"[After scrubbing the file, scrub its name in the directory entry, then rename it to the new name]:new name:" \ + {-s,--device-size}"[Override the device size (in bytes)]:size:" \ + {-L,--no-link}"[If file is a symbolic link, do not scrub the link target]" \ + {-R,--no-hwrand}"[Don't use a hardware random number generator even if one is available]" \ + {-t,--no-threads}"[Don't generate random data in parallel with I/O]" \ + {-n,--dry-run}"[Do everything but write to targets]" \ + {-h,--help}"[Print a summary of command line options on stderr]" \ + '*:files:_files' +} + +_scrub + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_sdd b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_sdd new file mode 100644 index 00000000..c722095d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_sdd @@ -0,0 +1,66 @@ +#compdef sdd +# ------------------------------------------------------------------------------ +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for sdd (http://freshmeat.net/projects/sdd/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Massimiliano Torromeo +# +# ------------------------------------------------------------------------------ + +_values -w 'option' \ + 'if[specify input file]:input file:_tilde_files' \ + 'of[specify output file]:output file:_tilde_files' \ + '(bs)ibs[input block size]:block size (bytes)' \ + '(bs)obs[output block size]:block size (bytes)' \ + '(ibs obs)bs[block size]:block size (bytes)' \ + 'cbs[conversion buffer size]:buffer size (bytes)' \ + 'skip[input/output initially skipped]:bytes' \ + 'seek[input/output initially skipped]:bytes' \ + 'count[number of input blocks to copy]:blocks' \ + '-notrunc[do not truncate existing output file]' \ + '-pg[print a dot on each write to indicate progress]' \ + '-noerror[do not stop on error]' \ + '-noerrwrite[do not write blocks not read correctly]' \ + "-noseek[don't seek]" \ + 'try[error retry count]:number' \ + '-debug[print debugging messages]' \ + '-fill[fill each record with zeros up to obs]' \ + '-swab' '-block' '-unblock' '-lcase' '-ucase' '-ascii' '-ebcdic' '-ibm' \ + '-help[show help]' \ + '-version[show version]' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_sdkmanager b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_sdkmanager new file mode 100644 index 00000000..fbd168a9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_sdkmanager @@ -0,0 +1,61 @@ +#compdef sdkmanager +# ------------------------------------------------------------------------------ +# Copyright (c) 2023 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for sdkmanager(https://developer.android.com/studio/command-line/sdkmanager) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_arguments \ + '(- *)--help[show help message]' \ + '(- *)--version[print the current version of sdkmanager]' \ + '--install[install or update package]' \ + '--uninstall[uninstall the listed packages]' \ + '--update[all installed packages are updated to the latest version]' \ + '--list_installed[all installed packages are printed out]' \ + '--licenses[show and offer the option to accept licenses for all available packages]' \ + '--sdk_root=[use the specified SDK root instead of the SDK containing this tool]: :_files -/' \ + '--channel=[include packages in channels up to channel ID]: :((0\:Stable 1\:Beta 2\:Dev 3\:Canary))' \ + '--include_obsolete[show/update obsolete packages in the package listing]' \ + '--newer[show only new and/or updatable packages]' \ + '--no_https[force all connections to use http rather than https]' \ + '--proxy=[connect via a proxy of the given type]: :(http socks)' \ + '--proxy_host=[IP or DNS address of the proxy to use]:address' \ + '--proxy_port=[proxy port to connect to]:port' \ + '--verbose[enable verbose output]' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_setcap b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_setcap new file mode 100644 index 00000000..2de84e0b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_setcap @@ -0,0 +1,126 @@ +#compdef setcap +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# +# ------------------------------------------------------------------------------ +# Description +# ------------------------------------------------------------------------------ +# Completion script for libcap's setcap: +# - https://people.redhat.com/sgrubb/libcap-ng/ +# +# ZSH provides the `zsh/cap` module that does not work on most modern systems, +# in lieu of this I have written this zsh-completion modules. +# +# Written by +# - Zephyr Pellerin (https://github.com/zv) +# ------------------------------------------------------------------------------ + +_setcap() { + local curcontext=$curcontext state line expl ret=1 + + _arguments -C -s \ + '-v[verify that the specified capabilities are currently associated with the file]' \ + '-n[set the file capability for use only in a user namespace with this root user ID owner]:rootuid' \ + '-q[make the program less verbose in its output]' \ + '1:capability:->capability' \ + '*:file:_files' \ + && ret=0 + + case "$state" in + (capability) + if compset -P '*?[=+-]'; then + local -a operators=("e:effective" "i:inheritable" "p:permitted") + _describe -t operators "operator" operators && ret=0 + else + _setcap_capabilities && ret=0 + fi + ;; + esac + + return 0 +} + +(( $+functions[_setcap_capabilities] )) || +_setcap_capabilities() { + local ret=1 + local -a capabilities=( + 'cap_audit_control:Enable and disable kernel auditing' + 'cap_audit_read:Allow reading the audit log' + 'cap_audit_write:Write records to kernel auditing log' + 'cap_block_suspend:Employ features that can block system suspend' + 'cap_bpf:Employ privileged BPF operations' + 'cap_checkpoint_restore:Facilitate checkpoint/restore' + 'cap_chown:Make arbitrary changes to file UIDs and GIDs' + 'cap_dac_override:Bypass file read, write, and execute permission checks' + 'cap_dac_read_search:Bypass file read permission checks' + 'cap_fowner:Bypass filesystem UID checks, set extended attrs' + "cap_fsetid:Don't clear set-user-ID and set-group-ID permission bits when a file is modified" + 'cap_ipc_lock:Lock memory' + 'cap_ipc_owner:Bypass checks on SySV IPC object operations' + 'cap_kill:Bypass permission checks for sending signals' + 'cap_lease:Establish leases on arbitrary files' + 'cap_linux_immutable:Set immutability or append only' + 'cap_mac_admin:Override Mandatory Access Control' + 'cap_mac_override:Allow MAC configuration or state changes' + 'cap_mknod:Create special files using mknod(2)' + 'cap_net_admin:Perform various network-related operations' + 'cap_net_bind_service:Bind a socket to a privileged ports' + 'cap_net_broadcast:Make socket broadcasts and listen to multicast' + 'cap_net_raw:Use raw sockets' + 'cap_perfmon:Employ various performance-monitoring mechanisms' + 'cap_setgid:Manipulate process GIDs' + 'cap_setfcap:Set file capabilities' + "cap_setpcap:Grant or remove any capability in the caller's permitted capability set to or from any other process" + 'cap_setuid:Manipulate or forge process UIDs' + 'cap_sys_admin:Perform numerous administrative tasks' + 'cap_sys_boot:Reboot' + 'cap_sys_chroot:Use chroot' + 'cap_sys_module:Load kernel module' + 'cap_sys_nice:Nice or renice processes' + 'cap_sys_pacct:Use acct(2)' + 'cap_sys_ptrace:Inspect processes with ptrace or use process_vm_writev' + 'cap_sys_rawio:Numerous device IO functions, including performing raw IO and access x86 MSRs' + 'cap_sys_resource:Set numerous resource limits' + 'cap_sys_time:Set system clock' + 'cap_sys_tty_config:Use vhangup(2)' + 'cap_syslog:Perform privileged syslog(2) operations' + 'cap_wake_alarm:Trigger something that will wake up the system' + ) + + _values -s , capability $capabilities && ret=0 + return $ret + +} + +_setcap "$@" + +# Local variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# ex: sw=2 ts=2 et filetype=sh diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_setup.py b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_setup.py new file mode 100644 index 00000000..5b6baf4d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_setup.py @@ -0,0 +1,715 @@ +#compdef setup.py +# ------------------------------------------------------------------------------ +# Copyright (C) 2015 by Hideo Hattori +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for setup.py (https://docs.python.org/distutils/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Hideo Hattori (https://github.com/hhatto) +# +# ------------------------------------------------------------------------------ + +_setup.py() { + typeset -A opt_args + local context state line + + _arguments -s -S \ + "--verbose[run verbosely (default)]" \ + "-v[run verbosely (default)]" \ + "--quiet[run quietly (turns verbosity off)]" \ + "-q[run quietly (turns verbosity off)]" \ + "--dry-run[don't actually do anything]" \ + "-n[don't actually do anything]" \ + "--help[show detailed help message]" \ + "-h[show detailed help message]" \ + "--no-user-cfg[ignore pydistutils.cfg in your home directory]" \ + "--command-packages=[list of packages that provide distutils commands]" \ + "--help-commands[list all available commands]" \ + "--name[print package name]" \ + "--version[print package version]" \ + "-V[print package version]" \ + "--fullname[print -]" \ + "--author[print the author's name]" \ + "--author-email[print the author's email address]" \ + "--maintainer[print the maintainer's name]" \ + "--maintainer-email[print the maintainer's email address]" \ + "--contact[print the maintainer's name if known, else the author's]" \ + "--contact-email[print the maintainer's email address if known, else the author's]" \ + "--url[print the URL for this package]" \ + "--license[print the license of the package]" \ + "--licence[alias for --license]" \ + "--description[print the package description]" \ + "--long-description[print the long package description]" \ + "--platforms[print the list of platforms]" \ + "--classifiers[print the list of classifiers]" \ + "--keywords[print the list of keywords]" \ + "--provides[print the list of packages/modules provided]" \ + "--requires[print the list of packages/modules required]" \ + "--obsoletes[print the list of packages/modules made obsolete]" \ + "*::setup.py commands:_setuppy_command" +} + +(( $+functions[_setuppy_command] )) || +_setuppy_command() { + local cmd ret=1 + + (( $+setuppy_cmds )) || _setuppy_cmds=( + "build:build everything needed to install" \ + "build_py:\"build\" pure Python modules (copy to build directory)" \ + "build_ext:build C/C++ extensions (compile/link to build directory)" \ + "build_clib:build C/C++ libraries used by Python extensions" \ + "build_scripts:\"build\" scripts (copy and fixup #! line)" \ + "clean:clean up temporary files from 'build' command" \ + "install:install everything from build directory" \ + "install_lib:install all Python modules (extensions and pure Python)" \ + "install_headers:install C/C++ header files" \ + "install_scripts:install scripts (Python or otherwise)" \ + "install_data:install data files" \ + "sdist:create a source distribution (tarball, zip file, etc.)" \ + "register:register the distribution with the Python package index" \ + "bdist:create a built (binary) distribution" \ + "bdist_dumb:create a \"dumb\" built distribution" \ + "bdist_rpm:create an RPM distribution" \ + "bdist_wininst:create an executable installer for MS Windows" \ + "upload:upload binary package to PyPI" \ + "check:perform some checks on the package" \ + "alias:define a shortcut to invoke one or more commands" \ + "bdist_egg:create an \"egg\" distribution" \ + "develop:install package in 'development mode'" \ + "easy_install:Find/get/install Python packages" \ + "egg_info:create a distribution's .egg-info directory" \ + "rotate:delete older distributions, keeping N newest files" \ + "saveopts:save supplied options to setup.cfg or other config file" \ + "setopt:set an option in setup.cfg or another config file" \ + "test:run unit tests after in-place build" \ + "install_egg_info:Install an .egg-info directory for the package" \ + "upload_docs:Upload documentation to PyPI" \ + ) + + if (( CURRENT == 1 )); then + _describe -t commands 'setup.py subcommand' _setuppy_cmds || compadd "$@" - ${(s.:.)${(j.:.)_setuppy_syns}} + else + local curcontext="$curcontext" + + cmd="${${_setuppy_cmds[(r)$words[1]:*]%%:*}:-${(k)_setuppy_syns[(r)(*:|)$words[1](:*|)]}}" + if (( $#cmd )); then + curcontext="${curcontext%:*:*}:setuppy-${cmd}:" + _call_function ret _setuppy_$cmd || _message 'no more arguments' + else + _message "unknown setup.py command: $words[1]" + fi + return ret + fi +} + +(( $+functions[_setuppy_build] )) || +_setuppy_build() { + _arguments -s \ + "--build-base=[base directory for build library]" \ + "-b[base directory for build library]" \ + "--build-purelib=[build directory for platform-neutral distributions]" \ + "--build-platlib=[build directory for platform-specific distributions]" \ + "--build-lib=[build directory for all distribution (defaults to either build-purelib or build-platlib]" \ + "--build-scripts=[build directory for scripts]" \ + "--build-temp=[temporary build directory]" \ + "-t[temporary build directory]" \ + "--plat-name=[platform name to build for, if supported (default: linux-i686)]" \ + "-p[platform name to build for, if supported (default: linux-i686)]" \ + "--compiler=[specify the compiler type]" \ + "-c[specify the compiler type]" \ + "--debug[compile extensions and libraries with debugging information]" \ + "-g[compile extensions and libraries with debugging information]" \ + "--force[forcibly build everything (ignore file timestamps)]" \ + "-f[forcibly build everything (ignore file timestamps)]" \ + "--executable=[specify final destination interpreter path (build.py)]" \ + "-e[specify final destination interpreter path (build.py)]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_build_py] )) || +_setuppy_build_py() { + _arguments -s \ + "--build-lib=[directory to \"build\" (copy) to]" \ + "-d[directory to \"build\" (copy) to]" \ + "--compile[compile .py to .pyc]" \ + "-c[compile .py to .pyc]" \ + "--no-compile[don't compile .py files \[default\]]" \ + "--optimize=[also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable \[default: -O0\]]" \ + "-O[also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable \[default: -O0\]]" \ + "--force[forcibly build everything (ignore file timestamps)]" \ + "-f[forcibly build everything (ignore file timestamps)]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_build_ext] )) || +_setuppy_build_ext() { + _arguments -s \ + "--build-lib=[directory for compiled extension modules]" \ + "-b[directory for compiled extension modules]" \ + "--build-temp=[directory for temporary files (build by-products)]" \ + "-t[directory for temporary files (build by-products)]" \ + "--plat-name=[platform name to cross-compile for, if supported (default: linux-i686)]" \ + "-p[platform name to cross-compile for, if supported (default: linux-i686)]" \ + "--inplace[ignore build-lib and put compiled extensions into the source directory alongside your pure Python modules]" \ + "-i[ignore build-lib and put compiled extensions into the source directory alongside your pure Python modules]" \ + "--include-dirs=[list of directories to search for header files (separated by ':')]" \ + "-I[list of directories to search for header files (separated by ':')]" \ + "--define=[C preprocessor macros to define]" \ + "-D[C preprocessor macros to define]" \ + "--undef=[C preprocessor macros to undefine]" \ + "-U[C preprocessor macros to undefine]" \ + "--libraries=[external C libraries to link with]" \ + "-l[external C libraries to link with]" \ + "--library-dirs=[directories to search for external C libraries (separated by ':')]" \ + "-L[directories to search for external C libraries (separated by ':')]" \ + "--rpath=[directories to search for shared C libraries at runtime]" \ + "-R[directories to search for shared C libraries at runtime]" \ + "--link-objects=[extra explicit link objects to include in the link]" \ + "-O[extra explicit link objects to include in the link]" \ + "--debug[compile/link with debugging information]" \ + "-g[compile/link with debugging information]" \ + "--force[forcibly build everything (ignore file timestamps)]" \ + "-f[forcibly build everything (ignore file timestamps)]" \ + "--compiler=[specify the compiler type]" \ + "-c[specify the compiler type]" \ + "--swig-cpp[make SWIG create C++ files (default is C)]" \ + "--swig-opts=[list of SWIG command line options]" \ + "--swig=[path to the SWIG executable]" \ + "--user[add user include, library and rpath]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_build_clib] )) || +_setuppy_build_clib() { + _arguments -s \ + "--build-clib=[directory to build C/C++ libraries to]" \ + "-b[directory to build C/C++ libraries to]" \ + "--build-temp=[directory to put temporary build by-products]" \ + "-t[directory to put temporary build by-products]" \ + "--debug[compile with debugging information]" \ + "-g[compile with debugging information]" \ + "--force[forcibly build everything (ignore file timestamps)]" \ + "-f[forcibly build everything (ignore file timestamps)]" \ + "--compiler=[specify the compiler type]" \ + "-c[specify the compiler type]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_build_scripts] )) || +_setuppy_build_scripts() { + _arguments -s \ + "--build-dir=[directory to \"build\" (copy) to]" \ + "-d[directory to \"build\" (copy) to]" \ + "--force[forcibly build everything (ignore file timestamps]" \ + "-f[forcibly build everything (ignore file timestamps]" \ + "--executable=[specify final destination interpreter path]" \ + "-e[specify final destination interpreter path]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_clean] )) || +_setuppy_clean() { + _arguments -s \ + "--build-base=[base build directory (default: 'build.build-base')]" \ + "-b[base build directory (default: 'build.build-base')]" \ + "--build-lib=[build directory for all modules (default: 'build.build-lib')]" \ + "--build-temp=[temporary build directory (default: 'build.build-temp')]" \ + "-t[temporary build directory (default: 'build.build-temp')]" \ + "--build-scripts=[build directory for scripts (default: 'build.build-scripts')]" \ + "--bdist-base=[temporary directory for built distributions]" \ + "--all[remove all build output, not just temporary by-products]" \ + "-a[remove all build output, not just temporary by-products]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_install] )) || +_setuppy_install() { + _arguments -s \ + "--prefix=[installation prefix]" \ + "--exec-prefix=[(Unix only) prefix for platform-specific files]" \ + "--home=[(Unix only) home directory to install under]" \ + "--user[install in user site-package]" \ + "--install-base=[base installation directory (instead of --prefix or --home)]" \ + "--install-platbase=[base installation directory for platform-specific files (instead of --exec-prefix or --home)]" \ + "--root=[install everything relative to this alternate root directory]" \ + "--install-purelib=[installation directory for pure Python module distributions]" \ + "--install-platlib=[installation directory for non-pure module distributions]" \ + "--install-lib=[installation directory for all module distributions (overrides --install-purelib and --install-platlib)]" \ + "--install-headers=[installation directory for C/C++ headers]" \ + "--install-scripts=[installation directory for Python scripts]" \ + "--install-data=[installation directory for data files]" \ + "--compile[compile .py to .pyc \[default\]]" \ + "-c[compile .py to .pyc \[default\]]" \ + "--no-compile[don't compile .py files]" \ + "--optimize=[also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable \[default: -O0\]]" \ + "-O[also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable \[default: -O0\]]" \ + "--force[force installation (overwrite any existing files)]" \ + "-f[force installation (overwrite any existing files)]" \ + "--skip-build[skip rebuilding everything (for testing/debugging)]" \ + "--record=[filename in which to record list of installed files]" \ + "--old-and-unmanageable[Try not to use this!]" \ + "--single-version-externally-managed[used by system package builders to create 'flat' eggs]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_install_lib] )) || +_setuppy_install_lib() { + _arguments -s \ + "--install-dir=[directory to install to]" \ + "-d[directory to install to]" \ + "--build-dir=[build directory (where to install from)]" \ + "-b[build directory (where to install from)]" \ + "--force[force installation (overwrite existing files)]" \ + "-f[force installation (overwrite existing files)]" \ + "--compile[compile .py to .pyc \[default\]]" \ + "-c[compile .py to .pyc \[default\]]" \ + "--no-compile[don't compile .py files]" \ + "--optimize=[also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable \[default: -O0\]]" \ + "-O[also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable \[default: -O0\]]" \ + "--skip-build[skip the build steps]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_install_headers] )) || +_setuppy_install_headers() { + _arguments -s \ + "--install-dir=[directory to install header files to]" \ + "-d[directory to install header files to]" \ + "--force[force installation (overwrite existing files)]" \ + "-f[force installation (overwrite existing files)]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_install_scripts] )) || +_setuppy_install_scripts() { + _arguments -s \ + "--install-dir=[directory to install scripts to]" \ + "-d[directory to install scripts to]" \ + "--build-dir=[build directory (where to install from)]" \ + "-b[build directory (where to install from)]" \ + "--force[force installation (overwrite existing files)]" \ + "-f[force installation (overwrite existing files)]" \ + "--skip-build[skip the build steps]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_install_data] )) || +_setuppy_install_data() { + _arguments -s \ + "--install-dir=[base directory for installing data files (default: installation base dir)]" \ + "-d[base directory for installing data files (default: installation base dir)]" \ + "--root=[install everything relative to this alternate root directory]" \ + "--force[force installation (overwrite existing files)]" \ + "-f[force installation (overwrite existing files)]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_sdist] )) || +_setuppy_sdist() { + _arguments -s \ + "--formats=[formats for source distribution (comma-separated list)]" \ + "--keep-temp[keep the distribution tree around after creating archive file(s)]" \ + "-k[keep the distribution tree around after creating archive file(s)]" \ + "--dist-dir=[directory to put the source distribution archive(s) in \[default: dist\]]" \ + "-d[directory to put the source distribution archive(s) in \[default: dist\]]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_register] )) || +_setuppy_register() { + _arguments -s \ + "--repository=[url of repository \[default: https://pypi.python.org/pypi\]]" \ + "-r[url of repository \[default: https://pypi.python.org/pypi\]]" \ + "--show-response[display full response text from server]" \ + "--list-classifiers[list the valid Trove classifiers]" \ + "--strict[Will stop the registering if the meta-data are not fully compliant]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_bdist] )) || +_setuppy_bdist() { + _arguments -s \ + "--bdist-base=[temporary directory for creating built distributions]" \ + "-b[temporary directory for creating built distributions]" \ + "--plat-name=[platform name to embed in generated filenames (default: linux-i686)]" \ + "-p[platform name to embed in generated filenames (default: linux-i686)]" \ + "--formats=[formats for distribution (comma-separated list)]" \ + "--dist-dir=[directory to put final built distributions in \[default: dist\]]" \ + "-d[directory to put final built distributions in \[default: dist\]]" \ + "--skip-build[skip rebuilding everything (for testing/debugging)]" \ + "--owner=[Owner name used when creating a tar file \[default: current user\]]" \ + "-u[Owner name used when creating a tar file \[default: current user\]]" \ + "--group=[Group name used when creating a tar file \[default: current group\]]" \ + "-g[Group name used when creating a tar file \[default: current group\]]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_bdist_dumb] )) || +_setuppy_bdist_dumb() { + _arguments -s \ + "--bdist-dir=[temporary directory for creating the distribution]" \ + "-d[temporary directory for creating the distribution]" \ + "--plat-name=[platform name to embed in generated filenames (default: linux-i686)]" \ + "-p[platform name to embed in generated filenames (default: linux-i686)]" \ + "--format=[archive format to create (tar, ztar, gztar, zip)]" \ + "-f[archive format to create (tar, ztar, gztar, zip)]" \ + "--keep-temp[keep the pseudo-installation tree around after creating the distribution archive]" \ + "-k[keep the pseudo-installation tree around after creating the distribution archive]" \ + "--dist-dir=[directory to put final built distributions in]" \ + "-d[directory to put final built distributions in]" \ + "--skip-build[skip rebuilding everything (for testing/debugging)]" \ + "--relative[build the archive using relative paths(default: false)]" \ + "--owner=[Owner name used when creating a tar file \[default: current user\]]" \ + "-u[Owner name used when creating a tar file \[default: current user\]]" \ + "--group=[Group name used when creating a tar file \[default: current group\]]" \ + "-g[Group name used when creating a tar file \[default: current group\]]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_bdist_rpm] )) || +_setuppy_bdist_rpm() { + _arguments -s \ + "--bdist-base=[base directory for creating built distributions]" \ + "--rpm-base=[base directory for creating RPMs (defaults to \"rpm\" under --bdist-base; must be specified for RPM 2)]" \ + "--dist-dir=[directory to put final RPM files in (and .spec files if --spec-only)]" \ + "-d[directory to put final RPM files in (and .spec files if --spec-only)]" \ + "--python=[path to Python interpreter to hard-code in the .spec file (default: \"python\")]" \ + "--fix-python[hard-code the exact path to the current Python interpreter in the .spec file]" \ + "--spec-only[only regenerate spec file]" \ + "--source-only[only generate source RPM]" \ + "--binary-only[only generate binary RPM]" \ + "--use-bzip2[use bzip2 instead of gzip to create source distribution]" \ + "--distribution-name=[name of the (Linux) distribution to which this RPM applies (*not* the name of the module distribution!)]" \ + "--group=[package classification \[default: \"Development/Libraries\"\]]" \ + "--release=[RPM release number]" \ + "--serial=[RPM serial number]" \ + "--vendor=[RPM \"vendor\" (eg. \"Joe Blow \") \[default: maintainer or author from setup script\]]" \ + "--packager=[RPM packager (eg. \"Jane Doe \")\[default: vendor\]]" \ + "--doc-files=[list of documentation files (space or comma-separated)]" \ + "--changelog=[RPM changelog]" \ + "--icon=[name of icon file]" \ + "--provides=[capabilities provided by this package]" \ + "--requires=[capabilities required by this package]" \ + "--conflicts=[capabilities which conflict with this package]" \ + "--build-requires=[capabilities required to build this package]" \ + "--obsoletes=[capabilities made obsolete by this package]" \ + "--no-autoreq[do not automatically calculate dependencies]" \ + "--keep-temp[don't clean up RPM build directory]" \ + "-k[don't clean up RPM build directory]" \ + "--no-keep-temp[clean up RPM build directory \[default\]]" \ + "--use-rpm-opt-flags[compile with RPM_OPT_FLAGS when building from source RPM]" \ + "--no-rpm-opt-flags[do not pass any RPM CFLAGS to compiler]" \ + "--rpm3-mode[RPM 3 compatibility mode (default)]" \ + "--rpm2-mode[RPM 2 compatibility mode]" \ + "--prep-script=[Specify a script for the PREP phase of RPM building]" \ + "--build-script=[Specify a script for the BUILD phase of RPM building]" \ + "--pre-install=[Specify a script for the pre-INSTALL phase of RPM building]" \ + "--install-script=[Specify a script for the INSTALL phase of RPM building]" \ + "--post-install=[Specify a script for the post-INSTALL phase of RPM building]" \ + "--pre-uninstall=[Specify a script for the pre-UNINSTALL phase of RPM building]" \ + "--post-uninstall=[Specify a script for the post-UNINSTALL phase of RPM building]" \ + "--clean-script=[Specify a script for the CLEAN phase of RPM building]" \ + "--verify-script=[Specify a script for the VERIFY phase of the RPM build]" \ + "--force-arch=[Force an architecture onto the RPM build process]" \ + "--quiet[Run the INSTALL phase of RPM building in quiet mode]" \ + "-q[Run the INSTALL phase of RPM building in quiet mode]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_bdist_wininst] )) || +_setuppy_bdist_wininst() { + _arguments -s \ + "--bdist-dir=[temporary directory for creating the distribution]" \ + "--plat-name=[platform name to embed in generated filenames (default: linux-i686)]" \ + "-p[platform name to embed in generated filenames (default: linux-i686)]" \ + "--keep-temp[keep the pseudo-installation tree around after creating the distribution archive]" \ + "-k[keep the pseudo-installation tree around after creating the distribution archive]" \ + "--target-version=[require a specific python version on the target system]" \ + "--no-target-compile[do not compile .py to .pyc on the target system]" \ + "-c[do not compile .py to .pyc on the target system]" \ + "--no-target-optimize[do not compile .py to .pyo (optimized)on the target system]" \ + "-o[do not compile .py to .pyo (optimized)on the target system]" \ + "--dist-dir=[directory to put final built distributions in]" \ + "-d[directory to put final built distributions in]" \ + "--bitmap=[bitmap to use for the installer instead of python-powered logo]" \ + "-b[bitmap to use for the installer instead of python-powered logo]" \ + "--title=[title to display on the installer background instead of default]" \ + "-t[title to display on the installer background instead of default]" \ + "--skip-build[skip rebuilding everything (for testing/debugging)]" \ + "--install-script=[basename of installation script to be run after installation or before uninstallation]" \ + "--pre-install-script=[Fully qualified filename of a script to be run before any files are installed. This script need not be in the distribution]" \ + "--user-access-control=[specify Vista's UAC handling - 'none'/default=no handling, 'auto'=use UAC if target Python installed for all users, 'force'=always use UAC]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_upload] )) || +_setuppy_upload() { + _arguments -s \ + "--repository=[url of repository \[default: https://pypi.python.org/pypi\]]" \ + "-r[url of repository \[default: https://pypi.python.org/pypi\]]" \ + "--show-response[display full response text from server]" \ + "--sign[sign files to upload using gpg]" \ + "-s[sign files to upload using gpg]" \ + "--identity=[GPG identity used to sign files]" \ + "-i[GPG identity used to sign files]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_check] )) || +_setuppy_check() { + _arguments -s \ + "--metadata[Verify meta-data]" \ + "-m[Verify meta-data]" \ + "--restructuredtext[Checks if long string meta-data syntax are reStructuredText-compliant]" \ + "-r[Checks if long string meta-data syntax are reStructuredText-compliant]" \ + "--strict[Will exit with an error if a check fails]" \ + "-s[Will exit with an error if a check fails]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_alias] )) || +_setuppy_alias() { + _arguments -s \ + "--remove[remove (unset) the alias]" \ + "-r[remove (unset) the alias]" \ + "--global-config[save options to the site-wide distutils.cfg file]" \ + "-g[save options to the site-wide distutils.cfg file]" \ + "--user-config[save options to the current user's pydistutils.cfg file]" \ + "-u[save options to the current user's pydistutils.cfg file]" \ + "--filename=[configuration file to use (default=setup.cfg)]" \ + "-f[configuration file to use (default=setup.cfg)]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_bdist_egg] )) || +_setuppy_bdist_egg() { + _arguments -s \ + "--bdist-dir=[temporary directory for creating the distribution]" \ + "-b[temporary directory for creating the distribution]" \ + "--plat-name=[platform name to embed in generated filenames (default: linux-i686)]" \ + "-p[platform name to embed in generated filenames (default: linux-i686)]" \ + "--exclude-source-files[remove all .py files from the generated egg]" \ + "--keep-temp[keep the pseudo-installation tree around after creating the distribution archive]" \ + "-k[keep the pseudo-installation tree around after creating the distribution archive]" \ + "--dist-dir=[directory to put final built distributions in]" \ + "-d[directory to put final built distributions in]" \ + "--skip-build[skip rebuilding everything (for testing/debugging)]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_develop] )) || +_setuppy_develop() { + _arguments -s \ + "--prefix=[installation prefix]" \ + "--zip-ok[install package as a zipfile]" \ + "-z[install package as a zipfile]" \ + "--multi-version[make apps have to require() a version]" \ + "-m[make apps have to require() a version]" \ + "--upgrade[force upgrade (searches PyPI for latest versions)]" \ + "-U[force upgrade (searches PyPI for latest versions)]" \ + "--install-dir=[install package to DIR]" \ + "-d[install package to DIR]" \ + "--script-dir=[install scripts to DIR]" \ + "-s[install scripts to DIR]" \ + "--exclude-scripts[Don't install scripts]" \ + "-x[Don't install scripts]" \ + "--always-copy[Copy all needed packages to install dir]" \ + "-a[Copy all needed packages to install dir]" \ + "--index-url=[base URL of Python Package Index]" \ + "-i[base URL of Python Package Index]" \ + "--find-links=[additional URL(s) to search for packages]" \ + "-f[additional URL(s) to search for packages]" \ + "--build-directory=[download/extract/build in DIR; keep the results]" \ + "-b[download/extract/build in DIR; keep the results]" \ + "--optimize=[also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable \[default: -O0\]]" \ + "-O[also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable \[default: -O0\]]" \ + "--record=[filename in which to record list of installed files]" \ + "--always-unzip[don't install as a zipfile, no matter what]" \ + "-Z[don't install as a zipfile, no matter what]" \ + "--site-dirs=[list of directories where .pth files work]" \ + "-S[list of directories where .pth files work]" \ + "--editable[Install specified packages in editable form]" \ + "-e[Install specified packages in editable form]" \ + "--no-deps[don't install dependencies]" \ + "-N[don't install dependencies]" \ + "--allow-hosts=[pattern(s) that hostnames must match]" \ + "-H[pattern(s) that hostnames must match]" \ + "--local-snapshots-ok[allow building eggs from local checkouts]" \ + "-l[allow building eggs from local checkouts]" \ + "--version[print version information and exit]" \ + "--no-find-links[Don't load find-links defined in packages being installed]" \ + "--user[install in user site-package]" \ + "--uninstall[Uninstall this source package]" \ + "-u[Uninstall this source package]" \ + "--egg-path=[Set the path to be used in the .egg-link file]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_easy_install] )) || +_setuppy_easy_install() { + _arguments -s \ + "--prefix=[installation prefix]" \ + "--zip-ok[install package as a zipfile]" \ + "-z[install package as a zipfile]" \ + "--multi-version[make apps have to require() a version]" \ + "-m[make apps have to require() a version]" \ + "--upgrade[force upgrade (searches PyPI for latest versions)]" \ + "-U[force upgrade (searches PyPI for latest versions)]" \ + "--install-dir=[install package to DIR]" \ + "-d[install package to DIR]" \ + "--script-dir=[install scripts to DIR]" \ + "-s[install scripts to DIR]" \ + "--exclude-scripts[Don't install scripts]" \ + "-x[Don't install scripts]" \ + "--always-copy[Copy all needed packages to install dir]" \ + "-a[Copy all needed packages to install dir]" \ + "--index-url=[base URL of Python Package Index]" \ + "-i[base URL of Python Package Index]" \ + "--find-links=[additional URL(s) to search for packages]" \ + "-f[additional URL(s) to search for packages]" \ + "--build-directory=[download/extract/build in DIR; keep the results]" \ + "-b[download/extract/build in DIR; keep the results]" \ + "--optimize=[also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable \[default: -O0\]]" \ + "-O[also compile with optimization: -O1 for \"python -O\", -O2 for \"python -OO\", and -O0 to disable \[default: -O0\]]" \ + "--record=[filename in which to record list of installed files]" \ + "--always-unzip[don't install as a zipfile, no matter what]" \ + "-Z[don't install as a zipfile, no matter what]" \ + "--site-dirs=[list of directories where .pth files work]" \ + "-S[list of directories where .pth files work]" \ + "--editable[Install specified packages in editable form]" \ + "-e[Install specified packages in editable form]" \ + "--no-deps[don't install dependencies]" \ + "-N[don't install dependencies]" \ + "--allow-hosts=[pattern(s) that hostnames must match]" \ + "-H[pattern(s) that hostnames must match]" \ + "--local-snapshots-ok[allow building eggs from local checkouts]" \ + "-l[allow building eggs from local checkouts]" \ + "--version[print version information and exit]" \ + "--no-find-links[Don't load find-links defined in packages being installed]" \ + "--user[install in user site-package]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_egg_info] )) || +_setuppy_egg_info() { + _arguments -s \ + "--egg-base=[directory containing .egg-info directories (default: top of the source tree)]" \ + "-e[directory containing .egg-info directories (default: top of the source tree)]" \ + "--tag-svn-revision[Add subversion revision ID to version number]" \ + "-r[Add subversion revision ID to version number]" \ + "--tag-date[Add date stamp (e.g. 20050528) to version number]" \ + "-d[Add date stamp (e.g. 20050528) to version number]" \ + "--tag-build=[Specify explicit tag to add to version number]" \ + "-b[Specify explicit tag to add to version number]" \ + "--no-svn-revision[Don't add subversion revision ID \[default\]]" \ + "-R[Don't add subversion revision ID \[default\]]" \ + "--no-date[Don't include date stamp \[default\]]" \ + "-D[Don't include date stamp \[default\]]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_rotate] )) || +_setuppy_rotate() { + _arguments -s \ + "--match=[patterns to match (required)]" \ + "-m[patterns to match (required)]" \ + "--dist-dir=[directory where the distributions are]" \ + "-d[directory where the distributions are]" \ + "--keep=[number of matching distributions to keep]" \ + "-k[number of matching distributions to keep]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_saveopts] )) || +_setuppy_saveopts() { + _arguments -s \ + "--global-config[save options to the site-wide distutils.cfg file]" \ + "-g[save options to the site-wide distutils.cfg file]" \ + "--user-config[save options to the current user's pydistutils.cfg file]" \ + "-u[save options to the current user's pydistutils.cfg file]" \ + "--filename=[configuration file to use (default=setup.cfg)]" \ + "-f[configuration file to use (default=setup.cfg)]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_setopt] )) || +_setuppy_setopt() { + _arguments -s \ + "--command=[command to set an option for]" \ + "-c[command to set an option for]" \ + "--option=[option to set]" \ + "-o[option to set]" \ + "--set-value=[value of the option]" \ + "-s[value of the option]" \ + "--remove[remove (unset) the value]" \ + "-r[remove (unset) the value]" \ + "--global-config[save options to the site-wide distutils.cfg file]" \ + "-g[save options to the site-wide distutils.cfg file]" \ + "--user-config[save options to the current user's pydistutils.cfg file]" \ + "-u[save options to the current user's pydistutils.cfg file]" \ + "--filename=[configuration file to use (default=setup.cfg)]" \ + "-f[configuration file to use (default=setup.cfg)]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_test] )) || +_setuppy_test() { + _arguments -s \ + "--test-module=[Run 'test_suite' in specified module]" \ + "-m[Run 'test_suite' in specified module]" \ + "--test-suite=[Test suite to run (e.g. 'some_module.test_suite')]" \ + "-s[Test suite to run (e.g. 'some_module.test_suite')]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_install_egg_info] )) || +_setuppy_install_egg_info() { + _arguments -s \ + "--install-dir=[directory to install to]" \ + "-d[directory to install to]" \ + "*::setup.py commands:_setup.py" +} + +(( $+functions[_setuppy_upload_docs] )) || +_setuppy_upload_docs() { + _arguments -s \ + "--repository=[url of repository \[default: https://pypi.python.org/pypi\]]" \ + "-r[url of repository \[default: https://pypi.python.org/pypi\]]" \ + "--show-response[display full response text from server]" \ + "--upload-dir=[directory to upload]" \ + "*::setup.py commands:_setup.py" +} + +_setup.py "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_sfdx b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_sfdx new file mode 100644 index 00000000..8332fc05 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_sfdx @@ -0,0 +1,935 @@ +#compdef sfdx + +# DESCRIPTION: Zsh completion script for the Salesforce CLI +# AUTHOR: Wade Wegner (@WadeWegner) +# REPO: https://github.com/wadewegner/salesforce-cli-zsh-completion +# LICENSE: https://github.com/wadewegner/salesforce-cli-zsh-completion/blob/master/LICENSE + +local -a _1st_arguments + +_1st_arguments=( + "force\:alias\:list":"list username aliases for the Salesforce CLI" + "force\:alias\:set":"set username aliases for the Salesforce CLI" + "force\:apex\:class\:create":"create an Apex class" + "force\:apex\:execute":"execute anonymous Apex code" + "force\:apex\:log\:get":"fetch a debug log" + "force\:apex\:log\:list":"list debug logs" + "force\:apex\:test\:report":"display test results" + "force\:apex\:test\:run":"invoke Apex tests" + "force\:apex\:trigger\:create":"create an Apex trigger" + "force\:auth\:jwt\:grant":"authorize an org using the JWT flow" + "force\:auth\:sfdxurl\:store":"authorize an org using an SFDX auth URL" + "force\:auth\:web\:login":"authorize an org using the web login flow" + "force\:config\:get":"get config var values for given names" + "force\:config\:list":"list config vars for the Salesforce CLI" + "force\:config\:set":"set config vars for the Salesforce CLI" + "force\:data\:bulk\:delete":"bulk delete records from a csv file" + "force\:data\:bulk\:status":"view the status of a bulk data load job or batch" + "force\:data\:bulk\:upsert":"bulk upsert records from a CSV file" + "force\:data\:record\:create":"create a record" + "force\:data\:record\:delete":"delete a record" + "force\:data\:record\:get":"view a record" + "force\:data\:record\:update":"update a record" + "force\:data\:soql\:query":"execute a SOQL query" + "force\:data\:tree\:export":"export data from an org into sObject tree format for force:data:tree:import consumption" + "force\:data\:tree\:import":"import data into an org using SObject Tree Save API" + "force\:doc\:commands\:display":"display help for force commands" + "force\:doc\:commands\:list":"list the force commands" + "force\:lightning\:app\:create":"create a Lightning app" + "force\:lightning\:component\:create":"create a Lightning component" + "force\:lightning\:event\:create":"create a Lightning event" + "force\:lightning\:interface\:create":"create a Lightning interface" + "force\:lightning\:lint":"analyse (lint) Lightning component code" + "force\:lightning\:test\:create":"create a Lightning test" + "force\:lightning\:test\:install":"install Lightning Testing Service unmanaged package in your org" + "force\:lightning\:test\:run":"invoke Lightning component tests" + "force\:limits\:api\:display":"display current org’s limits" + "force\:mdapi\:convert":"convert Metadata API source into the Salesforce DX source format" + "force\:mdapi\:deploy":"deploy metadata to an org using Metadata API" + "force\:mdapi\:deploy\:report":"check the status of a metadata deployment" + "force\:mdapi\:retrieve":"retrieve metadata from an org using Metadata API" + "force\:mdapi\:retrieve\:report":"check the status of a metadata retrieval" + "force\:org\:create":"create a scratch org" + "force\:org\:delete":"mark a scratch org for deletion" + "force\:org\:display":"get org description" + "force\:org\:list":"list all orgs you’ve created or authenticated to" + "force\:org\:open":"open an org in your browser" + "force\:org\:shape\:create":"create a snapshot of org edition, features, and licenses" + "force\:org\:shape\:delete":"delete all org shapes for a target org" + "force\:org\:shape\:list":"list all org shapes you’ve created" + "force\:package1\:version\:create":"create a first-generation package version in the release org" + "force\:package1\:version\:create\:get":"retrieve the status of a package version creation request" + "force\:package1\:version\:display":"display details about a first-generation package version" + "force\:package1\:version\:list":"list package versions for the specified first-generation package or for the org" + "force\:package2\:create":"create a second-generation package" + "force\:package2\:list":"list all second-generation packages in the Dev Hub org" + "force\:package2\:update":"update a second-generation package" + "force\:package2\:version\:create":"create a second-generation package version" + "force\:package2\:version\:create\:get":"retrieve a package version creation request" + "force\:package2\:version\:create\:list":"list package version creation requests" + "force\:package2\:version\:get":"retrieve a package version in the Dev Hub org" + "force\:package2\:version\:list":"list all package versions in the Dev Hub org" + "force\:package2\:version\:update":"update a second-generation package version" + "force\:package\:install":"install a package in the target org" + "force\:package\:install\:get":"retrieve the status of a package installation request" + "force\:package\:installed\:list":"list the org’s installed packages" + "force\:package\:uninstall":"uninstall a second-generation package from the target org" + "force\:package\:uninstall\:get":"retrieve status of package uninstall request" + "force\:project\:create":"create a new SFDX project" + "force\:project\:upgrade":"update project config files to the latest format" + "force\:schema\:sobject\:describe":"describe an object" + "force\:schema\:sobject\:list":"list all objects of a specified category" + "force\:source\:convert":"convert Salesforce DX source into the Metadata API source format" + "force\:source\:open":"edit a Lightning Page with Lightning App Builder" + "force\:source\:pull":"pull source from the scratch org to the project" + "force\:source\:push":"push source to an org from the project" + "force\:source\:status":"list local changes and/or changes in a scratch org" + "force\:user\:create":"create a user for a scratch org" + "force\:user\:display":"displays information about a user of a scratch org" + "force\:user\:list":"lists all users of a scratch org" + "force\:user\:password\:generate":"generate a password for scratch org users" + "force\:user\:permset\:assign":"assign a permission set to one or more users of an org" + "force\:visualforce\:component\:create":"create a Visualforce component" + "force\:visualforce\:page\:create":"create a Visualforce page" +) + +_arguments '*:: :->command' + +if (( CURRENT == 1 )); then + _describe -t commands "sfdx command" _1st_arguments + return +fi + +local -a _command_args +case "$words[1]" in + force:limits:api:display) + _command_args=( + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:lightning:app:create) + _command_args=( + '(-n|--appname)'{-n,--appname}'[name of the generated Lightning app]' \ + '(-t|--template)'{-t,--template}'[template to use for file creation (DefaultLightningApp*)]' \ + '(-d|--outputdir)'{-d,--outputdir}'[folder for saving the created files]' \ + '(-r|--reflect)'{-r,--reflect}'[switch to return flag detailed information]' \ + '(-a|--apiversion)'{-a,--apiversion}'[API version number (41.0*,40.0)]' \ + '(--json)--json[JSON output]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:data:bulk:delete) + _command_args=( + '(-s|--sobjecttype)'{-s,--sobjecttype}'[the sObject type of the records you’re deleting]' \ + '(-f|--csvfile)'{-f,--csvfile}'[the path to the CSV file containing the ids of the records to delete]:file:_files' \ + '(-w|--wait)'{-w,--wait}'[the number of minutes to wait for the command to complete before displaying the results]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:data:bulk:status) + _command_args=( + '(-i|--jobid)'{-i,--jobid}'[the ID of the job you want to view or of the job whose batch you want to view]' \ + '(-b|--batchid)'{-b,--batchid}'[the ID of the batch whose status you want to view]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:data:bulk:upsert) + _command_args=( + '(-s|--sobjecttype)'{-s,--sobjecttype}'[the sObject type of the records you want to upsert]' \ + '(-f|--csvfile)'{-f,--csvfile}'[the path to the CSV file that defines the records to upsert]:file:_files' \ + '(-i|--externalid)'{-i,--externalid}'[the column name of the external ID; if not provided, an arbitrary ID is used]' \ + '(-w|--wait)'{-w,--wait}'[the number of minutes to wait for the command to complete before displaying the results]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:apex:class:create) + _command_args=( + '(-n|--classname)'{-n,--classname}'[name of the generated Apex class]' \ + '(-t|--template)'{-t,--template}'[template to use for file creation (DefaultApexClass*,ApexException,ApexUnitTest,InboundEmailService)]' \ + '(-d|--outputdir)'{-d,--outputdir}'[folder for saving the created files]' \ + '(-r|--reflect)'{-r,--reflect}'[switch to return flag detailed information]' \ + '(-a|--apiversion)'{-a,--apiversion}'[API version number (41.0*,40.0)]' \ + '(--json)--json[JSON output]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:doc:commands:display) + _command_args=( + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:doc:commands:list) + _command_args=( + '(-u|--usage)'{-u,--usage}'[list only docopts usage strings]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:visualforce:component:create) + _command_args=( + '(-t|--template)'{-t,--template}'[template to use for file creation (DefaultVFComponent*)]' \ + '(-d|--outputdir)'{-d,--outputdir}'[folder for saving the created files]' \ + '(-r|--reflect)'{-r,--reflect}'[switch to return flag detailed information]' \ + '(-n|--componentname)'{-n,--componentname}'[name of the generated Visualforce component]' \ + '(-a|--apiversion)'{-a,--apiversion}'[API version number (41.0*,40.0)]' \ + '(-l|--label)'{-l,--label}'[Visualforce component label]' \ + '(--json)--json[JSON output]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:lightning:component:create) + _command_args=( + '(-n|--componentname)'{-n,--componentname}'[name of the generated Lightning component]' \ + '(-t|--template)'{-t,--template}'[template to use for file creation (DefaultLightningCmp*)]' \ + '(-d|--outputdir)'{-d,--outputdir}'[folder for saving the created files]' \ + '(-r|--reflect)'{-r,--reflect}'[switch to return flag detailed information]' \ + '(-a|--apiversion)'{-a,--apiversion}'[API version number (41.0*,40.0)]' \ + '(--json)--json[JSON output]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:mdapi:convert) + _command_args=( + '(-r|--rootdir)'{-r,--rootdir}'[the root directory containing the Metadata API source]:file:_files' \ + '(-d|--outputdir)'{-d,--outputdir}'[the output directory to store the sfdx source]:file:_files' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:source:convert) + _command_args=( + '(-r|--rootdir)'{-r,--rootdir}'[the source directory for the source to be converted]:file:_files' \ + '(-d|--outputdir)'{-d,--outputdir}'[the output directory to export the Metadata API source to]:file:_files' \ + '(-n|--packagename)'{-n,--packagename}'[the name of the package to associate with the Metadata API source]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:org:create) + _command_args=( + '(-f|--definitionfile)'{-f,--definitionfile}'[path to a scratch org definition file]:file:_files' \ + '(-j|--definitionjson)'{-j,--definitionjson}'[scratch org definition in json format ]' \ + '(-n|--nonamespace)'{-n,--nonamespace}'[creates the scratch org with no namespace]' \ + '(-c|--noancestors)'{-c,--noancestors}'[do not include second-generation package ancestors in the scratch org]' \ + '(-i|--clientid)'{-i,--clientid}'[connected app consumer key]' \ + '(-s|--setdefaultusername)'{-s,--setdefaultusername}'[set the created org as the default username]' \ + '(-a|--setalias)'{-a,--setalias}'[set an alias for the created scratch org]' \ + '(-e|--env)'{-e,--env}'[environment where the scratch org is created: \[sandbox*,virtual,prototype\] (sandbox*,virtual,prototype)]' \ + '(-w|--wait)'{-w,--wait}'[the streaming client socket timeout (in minutes) (default:6, min:2)]' \ + '(-d|--durationdays)'{-d,--durationdays}'[duration of the scratch org (in days) (default:7, min:1, max:30)]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package2:create) + _command_args=( + '(-n|--name)'{-n,--name}'[package name]' \ + '(-o|--containeroptions)'{-o,--containeroptions}'[\[*Managed | Unlocked | Locked\] container options for the package (Managed=DeveloperManagedSubscriberManaged, Unlocked=DeveloperControlledSubscriberEditable, Locked=DeveloperControlledSubscriberLocked)]' \ + '(-d|--description)'{-d,--description}'[package description]' \ + '(-e|--nonamespace)'{-e,--nonamespace}'[creates the package with no namespace; available only for developer-controlled packages.]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:user:create) + _command_args=( + '(-f|--definitionfile)'{-f,--definitionfile}'[file path to a user definition]:file:_files' \ + '(-a|--setalias)'{-a,--setalias}'[set an alias for the created username to reference within the CLI]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:project:create) + _command_args=( + '(-n|--projectname)'{-n,--projectname}'[name of the generated project]' \ + '(-t|--template)'{-t,--template}'[template to use for file creation (Defaultsfdx-project.json*)]' \ + '(-d|--outputdir)'{-d,--outputdir}'[folder for saving the created files]' \ + '(-r|--reflect)'{-r,--reflect}'[switch to return flag detailed information]' \ + '(-l|--loginurl)'{-l,--loginurl}'[Salesforce instance login URL (https://login.salesforce.com*)]' \ + '(-x|--sourceapiversion)'{-x,--sourceapiversion}'[source API version number (41.0*)]' \ + '(-s|--namespace)'{-s,--namespace}'[project associated namespace]' \ + '(-p|--defaultpackagedir)'{-p,--defaultpackagedir}'[default package directory name (force-app*)]:file:_files' \ + '(--json)--json[JSON output]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:org:delete) + _command_args=( + '(-p|--noprompt)'{-p,--noprompt}'[no prompt to confirm deletion]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:mdapi:deploy) + _command_args=( + '(-c|--checkonly)'{-c,--checkonly}'[validate deploy but don’t save to the org (default:false)]' \ + '(-d|--deploydir)'{-d,--deploydir}'[root of directory tree of files to deploy]:file:_files' \ + '(-w|--wait)'{-w,--wait}'[wait time for command to finish in minutes (default: 0)]' \ + '(-i|--jobid)'{-i,--jobid}'[WARNING: The flag "jobid" has been deprecated and will be removed in v41.01.0 or later. Instead, use "sfdx force:mdapi:deploy:report -i ".]' \ + '(-l|--testlevel)'{-l,--testlevel}'[deployment testing level (NoTestRun,RunSpecifiedTests,RunLocalTests,RunAllTestsInOrg)]' \ + '(-r|--runtests)'{-r,--runtests}'[tests to run if --testlevel RunSpecifiedTests]' \ + '(-e|--rollbackonerror)'{-e,--rollbackonerror}'[WARNING: The flag "rollbackonerror" has been deprecated and will be removed in v41.01.0 or later. Instead, use "ignoreerrors".]' \ + '(-o|--ignoreerrors)'{-o,--ignoreerrors}'[ignore any errors and do not roll back deployment (default:false)]' \ + '(-g|--ignorewarnings)'{-g,--ignorewarnings}'[whether a warning will allow a deployment to complete successfully (default:false)]' \ + '(-f|--zipfile)'{-f,--zipfile}'[path to .zip file of metadata to deploy]:file:_files' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + '(--verbose)--verbose[verbose output of deploy results]' \ + ) + ;; + force:mdapi:deploy:report) + _command_args=( + '(-w|--wait)'{-w,--wait}'[wait time for command to finish in minutes (default: 0)]' \ + '(-i|--jobid)'{-i,--jobid}'[job ID of the deployment you want to check]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + '(--verbose)--verbose[verbose output of deploy results]' \ + ) + ;; + force:org:display) + _command_args=( + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + '(--verbose)--verbose[emit additional command output to stdout]' \ + ) + ;; + force:user:display) + _command_args=( + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:lightning:event:create) + _command_args=( + '(-n|--eventname)'{-n,--eventname}'[name of the generated Lightning event]' \ + '(-t|--template)'{-t,--template}'[template to use for file creation (DefaultLightningEvt*)]' \ + '(-d|--outputdir)'{-d,--outputdir}'[folder for saving the created files]' \ + '(-r|--reflect)'{-r,--reflect}'[switch to return flag detailed information]' \ + '(-a|--apiversion)'{-a,--apiversion}'[API version number (41.0*,40.0)]' \ + '(--json)--json[JSON output]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:apex:execute) + _command_args=( + '(-f|--apexcodefile)'{-f,--apexcodefile}'[path to a local file containing Apex code]:file:_files' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:config:get) + _command_args=( + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + '(--verbose)--verbose[emit additional command output to stdout]' \ + ) + ;; + force:package:install) + _command_args=( + '(-i|--id)'{-i,--id}'[ID of the package version to install (starts with 04t)]' \ + '(-w|--wait)'{-w,--wait}'[number of minutes to wait for installation status]' \ + '(-k|--installationkey)'{-k,--installationkey}'[installation key for key-protected package (default: null)]' \ + '(-p|--publishwait)'{-p,--publishwait}'[number of minutes to wait for subscriber package version ID to become available in the target org]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package:install:get) + _command_args=( + '(-i|--requestid)'{-i,--requestid}'[ID of the package install request you want to check]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package:installed:list) + _command_args=( + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:lightning:interface:create) + _command_args=( + '(-n|--interfacename)'{-n,--interfacename}'[name of the generated Lightning interface]' \ + '(-t|--template)'{-t,--template}'[template to use for file creation (DefaultLightningIntf*)]' \ + '(-d|--outputdir)'{-d,--outputdir}'[folder for saving the created files]' \ + '(-r|--reflect)'{-r,--reflect}'[switch to return flag detailed information]' \ + '(-a|--apiversion)'{-a,--apiversion}'[API version number (41.0*,40.0)]' \ + '(--json)--json[JSON output]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:auth:jwt:grant) + _command_args=( + '(-u|--username)'{-u,--username}'[authentication username]' \ + '(-f|--jwtkeyfile)'{-f,--jwtkeyfile}'[path to a file containing the private key]:file:_files' \ + '(-i|--clientid)'{-i,--clientid}'[OAuth client ID (sometimes called the consumer key)]' \ + '(-r|--instanceurl)'{-r,--instanceurl}'[the login URL of the instance the org lives on]' \ + '(-d|--setdefaultdevhubusername)'{-d,--setdefaultdevhubusername}'[set the authenticated org as the default dev hub org for scratch org creation]' \ + '(-s|--setdefaultusername)'{-s,--setdefaultusername}'[set the authenticated org as the default username that all commands run against]' \ + '(-a|--setalias)'{-a,--setalias}'[set an alias for the authenticated org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:lightning:lint) + _command_args=( + '(-i|--ignore)'{-i,--ignore}'[pattern used to ignore some folders]' \ + '(--files)--files[pattern used to include specific files]:file:_files' \ + '(-j|--json)'{-j,--json}'[format output as JSON]' \ + '(--config)--config[path to a custom ESLint configuration file]:file:_files' \ + '(--verbose)--verbose[report warnings in addition to errors]' \ + '(--exit)--exit[exit with error code 1 if there are lint issues]' \ + ) + ;; + force:alias:list) + _command_args=( + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:config:list) + _command_args=( + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:org:list) + _command_args=( + '(--all)--all[include expired, deleted, and unknown-status scratch orgs]' \ + '(--clean)--clean[remove all local org authorizations for non-active orgs]' \ + '(-p|--noprompt)'{-p,--noprompt}'[do not prompt for confirmation]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + '(--verbose)--verbose[list more information about each org]' \ + ) + ;; + force:package2:list) + _command_args=( + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:user:list) + _command_args=( + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:apex:log:get) + _command_args=( + '(-i|--logid)'{-i,--logid}'[ID of the log to display]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:apex:log:list) + _command_args=( + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:org:open) + _command_args=( + '(-p|--path)'{-p,--path}'[navigation URL path]:file:_files' \ + '(-r|--urlonly)'{-r,--urlonly}'[display navigation URL, but don’t launch browser]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:source:open) + _command_args=( + '(-f|--sourcefile)'{-f,--sourcefile}'[file to edit]:file:_files' \ + '(-r|--urlonly)'{-r,--urlonly}'[generate a navigation URL; don’t launch the editor]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:visualforce:page:create) + _command_args=( + '(-t|--template)'{-t,--template}'[template to use for file creation (DefaultVFPage*)]' \ + '(-d|--outputdir)'{-d,--outputdir}'[folder for saving the created files]' \ + '(-r|--reflect)'{-r,--reflect}'[switch to return flag detailed information]' \ + '(-n|--pagename)'{-n,--pagename}'[name of the generated Visualforce page]' \ + '(-a|--apiversion)'{-a,--apiversion}'[API version number (41.0*,40.0)]' \ + '(-l|--label)'{-l,--label}'[Visualforce page label]' \ + '(--json)--json[JSON output]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:user:password:generate) + _command_args=( + '(-o|--onbehalfof)'{-o,--onbehalfof}'[comma-separated list of usernames for which to generate passwords]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:user:permset:assign) + _command_args=( + '(-n|--permsetname)'{-n,--permsetname}'[the name of the permission set to assign]' \ + '(-o|--onbehalfof)'{-o,--onbehalfof}'[comma-separated list of usernames or aliases to assign the permission set to]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:source:pull) + _command_args=( + '(-w|--wait)'{-w,--wait}'[wait time for command to finish in minutes (default: 33) (default:33, min:1)]' \ + '(-f|--forceoverwrite)'{-f,--forceoverwrite}'[ignore conflict warnings and overwrite changes to the project]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:source:push) + _command_args=( + '(-f|--forceoverwrite)'{-f,--forceoverwrite}'[ignore conflict warnings and overwrite changes to scratch org]' \ + '(-g|--ignorewarnings)'{-g,--ignorewarnings}'[deploy changes even if warnings are generated]' \ + '(-w|--wait)'{-w,--wait}'[wait time for command to finish in minutes (default: 33) (default:33, min:1)]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:data:record:create) + _command_args=( + '(-s|--sobjecttype)'{-s,--sobjecttype}'[the type of the record you’re creating]' \ + '(-v|--values)'{-v,--values}'[the = pairs you’re creating]' \ + '(-t|--usetoolingapi)'{-t,--usetoolingapi}'[create the record with tooling api]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:data:record:delete) + _command_args=( + '(-s|--sobjecttype)'{-s,--sobjecttype}'[the type of the record you’re deleting]' \ + '(-i|--sobjectid)'{-i,--sobjectid}'[the ID of the record you’re deleting]' \ + '(-w|--where)'{-w,--where}'[a list of = pairs to search for]' \ + '(-t|--usetoolingapi)'{-t,--usetoolingapi}'[delete the record with Tooling API]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:data:record:get) + _command_args=( + '(-s|--sobjecttype)'{-s,--sobjecttype}'[the type of the record you’re retrieving]' \ + '(-i|--sobjectid)'{-i,--sobjectid}'[the ID of the record you’re retrieving]' \ + '(-w|--where)'{-w,--where}'[a list of = pairs to search for]' \ + '(-t|--usetoolingapi)'{-t,--usetoolingapi}'[retrieve the record with Tooling API]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:data:record:update) + _command_args=( + '(-s|--sobjecttype)'{-s,--sobjecttype}'[the type of the record you’re updating]' \ + '(-i|--sobjectid)'{-i,--sobjectid}'[the ID of the record you’re updating]' \ + '(-w|--where)'{-w,--where}'[a list of = pairs to search for]' \ + '(-v|--values)'{-v,--values}'[the = pairs you’re updating]' \ + '(-t|--usetoolingapi)'{-t,--usetoolingapi}'[update the record with Tooling API]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:mdapi:retrieve) + _command_args=( + '(-a|--apiversion)'{-a,--apiversion}'[target API version for the retrieve (default 41.0)]' \ + '(-w|--wait)'{-w,--wait}'[wait time for command to finish in minutes (default: -1 (no limit))]' \ + '(-r|--retrievetargetdir)'{-r,--retrievetargetdir}'[directory root for the retrieved files]:file:_files' \ + '(-k|--unpackaged)'{-k,--unpackaged}'[file path of manifest of components to retrieve]:file:_files' \ + '(-d|--sourcedir)'{-d,--sourcedir}'[source dir to use instead of default manifest sfdx-project.xml]' \ + '(-p|--packagenames)'{-p,--packagenames}'[a comma-separated list of packages to retrieve]' \ + '(-s|--singlepackage)'{-s,--singlepackage}'[a single-package retrieve (default: false)]' \ + '(-i|--jobid)'{-i,--jobid}'[WARNING: The flag "jobid" has been deprecated and will be removed in v41.01.0 or later. Instead, use "sfdx force:mdapi:retrieve:report -i -r ".]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + '(--verbose)--verbose[verbose output of retrieve result]' \ + ) + ;; + force:mdapi:retrieve:report) + _command_args=( + '(-w|--wait)'{-w,--wait}'[wait time for command to finish in minutes (default: -1 (no limit))]' \ + '(-r|--retrievetargetdir)'{-r,--retrievetargetdir}'[directory root for the retrieved files]:file:_files' \ + '(-i|--jobid)'{-i,--jobid}'[job ID of the retrieve you want to check]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + '(--verbose)--verbose[verbose output of retrieve result]' \ + ) + ;; + force:alias:set) + _command_args=( + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:config:set) + _command_args=( + '(-g|--global)'{-g,--global}'[set config var globally (to be used from any directory)]:file:_files' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:auth:sfdxurl:store) + _command_args=( + '(-f|--sfdxurlfile)'{-f,--sfdxurlfile}'[path to a file containing the sfdx url]:file:_files' \ + '(-d|--setdefaultdevhubusername)'{-d,--setdefaultdevhubusername}'[set the authenticated org as the default dev hub org for scratch org creation]' \ + '(-s|--setdefaultusername)'{-s,--setdefaultusername}'[set the authenticated org as the default username that all commands run against]' \ + '(-a|--setalias)'{-a,--setalias}'[set an alias for the authenticated org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:org:shape:create) + _command_args=( + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:org:shape:delete) + _command_args=( + '(-p|--noprompt)'{-p,--noprompt}'[do not prompt for confirmation]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username for the target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:org:shape:list) + _command_args=( + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + '(--verbose)--verbose[list more information about each org shape]' \ + ) + ;; + force:schema:sobject:describe) + _command_args=( + '(-s|--sobjecttype)'{-s,--sobjecttype}'[the API name of the object to describe]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:schema:sobject:list) + _command_args=( + '(-c|--sobjecttypecategory)'{-c,--sobjecttypecategory}'[the type of objects to list (all|custom|standard)]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:data:soql:query) + _command_args=( + '(-q|--query)'{-q,--query}'[SOQL query to execute]' \ + '(-t|--usetoolingapi)'{-t,--usetoolingapi}'[execute query with Tooling API]' \ + '(-r|--resultformat)'{-r,--resultformat}'[query result format emitted to stdout; --json flag overrides this parameter (human*,csv,json)]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:source:status) + _command_args=( + '(-a|--all)'{-a,--all}'[list all the changes that have been made]' \ + '(-l|--local)'{-l,--local}'[list the changes that have been made locally]' \ + '(-r|--remote)'{-r,--remote}'[list the changes that have been made in the scratch org]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:lightning:test:create) + _command_args=( + '(-n|--testname)'{-n,--testname}'[name of the generated Lightning test]' \ + '(-t|--template)'{-t,--template}'[template to use for file creation (DefaultLightningTest*)]' \ + '(-d|--outputdir)'{-d,--outputdir}'[folder for saving the created files]' \ + '(-r|--reflect)'{-r,--reflect}'[switch to return flag detailed information]' \ + '(--json)--json[JSON output]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:lightning:test:install) + _command_args=( + '(-w|--wait)'{-w,--wait}'[number of minutes to wait for installation status (default:2)]' \ + '(-r|--releaseversion)'{-r,--releaseversion}'[release version of Lightning Testing Service (default:latest)]' \ + '(-t|--packagetype)'{-t,--packagetype}'[type of unmanaged package. 'full' option contains both jasmine and mocha, plus examples (full*,jasmine,mocha)]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:apex:test:report) + _command_args=( + '(-i|--testrunid)'{-i,--testrunid}'[ID of test run]' \ + '(-c|--codecoverage)'{-c,--codecoverage}'[retrieve code coverage results]' \ + '(-d|--outputdir)'{-d,--outputdir}'[directory to store test run files]:file:_files' \ + '(-r|--resultformat)'{-r,--resultformat}'[test result format emitted to stdout; --json flag overrides this parameter (human*,tap,junit,json)]' \ + '(-w|--wait)'{-w,--wait}'[the streaming client socket timeout (in minutes) (default:6, min:2)]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + '(--verbose)--verbose[display Apex test processing details]' \ + ) + ;; + force:apex:test:run) + _command_args=( + '(-n|--classnames)'{-n,--classnames}'[comma-separated list of Apex test class names to execute]' \ + '(-s|--suitenames)'{-s,--suitenames}'[comma-separated list of Apex test suite names to execute]' \ + '(-c|--codecoverage)'{-c,--codecoverage}'[retrieve code coverage results]' \ + '(-d|--outputdir)'{-d,--outputdir}'[directory to store test run files]:file:_files' \ + '(-l|--testlevel)'{-l,--testlevel}'[testlevel enum value (RunLocalTests,RunAllTestsInOrg,RunSpecifiedTests)]' \ + '(-r|--resultformat)'{-r,--resultformat}'[test result format emitted to stdout; --json flag overrides this parameter (human*,tap,junit,json)]' \ + '(-w|--wait)'{-w,--wait}'[the streaming client socket timeout (in minutes) (default:6, min:2)]' \ + '(--precompilewait)--precompilewait[how long to wait (in minutes) for Apex pre-compilation (default:3, min:3)]' \ + '(-y|--synchronous)'{-y,--synchronous}'[run tests from a single class synchronously]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + '(--verbose)--verbose[display Apex test processing details]' \ + ) + ;; + force:lightning:test:run) + _command_args=( + '(-a|--appname)'{-a,--appname}'[name of your Lightning test application]' \ + '(-d|--outputdir)'{-d,--outputdir}'[directory path to store test run artifacts: for example, log files and test results]:file:_files' \ + '(-r|--resultformat)'{-r,--resultformat}'[test result format emitted to stdout; --json flag overrides this parameter (human*,tap,junit,json)]' \ + '(-f|--configfile)'{-f,--configfile}'[path to config file for the test]:file:_files' \ + '(-o|--leavebrowseropen)'{-o,--leavebrowseropen}'[leave browser open]' \ + '(-t|--timeout)'{-t,--timeout}'[time (ms) to wait for results element in dom (default:60000)]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:data:tree:export) + _command_args=( + '(-q|--query)'{-q,--query}'[soql query, or filepath of file containing a soql query, to retrieve records]:file:_files' \ + '(-p|--plan)'{-p,--plan}'[generate multiple sObject tree files and a plan definition file for aggregated import]' \ + '(-x|--prefix)'{-x,--prefix}'[prefix of generated files]' \ + '(-d|--outputdir)'{-d,--outputdir}'[directory to store files]:file:_files' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:data:tree:import) + _command_args=( + '(-f|--sobjecttreefiles)'{-f,--sobjecttreefiles}'[comma-delimited, ordered paths of json files containing collection of record trees to insert]:file:_files' \ + '(-p|--plan)'{-p,--plan}'[path to plan to insert multiple data files that have master-detail relationships]:file:_files' \ + '(-c|--contenttype)'{-c,--contenttype}'[if data file extension is not .json, provide content type (applies to all files)]' \ + '(--confighelp)--confighelp[display schema information for the --plan configuration file to stdout; if you use this option, all other options except --json are ignored]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:apex:trigger:create) + _command_args=( + '(-n|--triggername)'{-n,--triggername}'[name of the generated Apex trigger]' \ + '(-t|--template)'{-t,--template}'[template to use for file creation (ApexTrigger*)]' \ + '(-d|--outputdir)'{-d,--outputdir}'[folder for saving the created files]' \ + '(-r|--reflect)'{-r,--reflect}'[switch to return flag detailed information]' \ + '(-a|--apiversion)'{-a,--apiversion}'[API version number (41.0*,40.0)]' \ + '(-s|--sobject)'{-s,--sobject}'[sObject to create a trigger on (SOBJECT*)]' \ + '(-e|--triggerevents)'{-e,--triggerevents}'[events that fire the trigger (before insert*,before upsert,before delete,after insert,after upsert,after delete,after undelete)]' \ + '(--json)--json[JSON output]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package:uninstall) + _command_args=( + '(-i|--id)'{-i,--id}'[ID of the package to uninstall (starts with 04t)]' \ + '(-w|--wait)'{-w,--wait}'[number of minutes to wait for uninstall status]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package:uninstall:get) + _command_args=( + '(-i|--requestid)'{-i,--requestid}'[ID of the package uninstall request you want to check]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package2:update) + _command_args=( + '(-i|--package2id)'{-i,--package2id}'[id of the package (starts with 0Ho)]' \ + '(-n|--name)'{-n,--name}'[package name]' \ + '(-d|--description)'{-d,--description}'[package description]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:project:upgrade) + _command_args=( + '(-f|--forceupgrade)'{-f,--forceupgrade}'[run all upgrades even if project has already been upgraded]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package1:version:create) + _command_args=( + '(-i|--packageid)'{-i,--packageid}'[ID of the metadata package (starts with 033) of which you’re creating a new version]' \ + '(-n|--name)'{-n,--name}'[package version name]' \ + '(-d|--description)'{-d,--description}'[package version description]' \ + '(-v|--version)'{-v,--version}'[package version in major.minor format, for example, 3.2]' \ + '(-m|--managedreleased)'{-m,--managedreleased}'[create a managed package version]' \ + '(-r|--releasenotesurl)'{-r,--releasenotesurl}'[release notes URL]' \ + '(-p|--postinstallurl)'{-p,--postinstallurl}'[post install URL]' \ + '(-k|--installationkey)'{-k,--installationkey}'[installation key for key-protected package (default: null)]' \ + '(-w|--wait)'{-w,--wait}'[minutes to wait for the package version to be created (default: 2 minutes)]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package2:version:create) + _command_args=( + '(-i|--package2id)'{-i,--package2id}'[ID of the parent package (starts with 0Ho)]' \ + '(-d|--directory)'{-d,--directory}'[path to directory that contains the contents of the package version]:file:_files' \ + '(-b|--branch)'{-b,--branch}'[the package version’s branch]' \ + '(-t|--tag)'{-t,--tag}'[the package version’s tag]' \ + '(-k|--installationkey)'{-k,--installationkey}'[installation key for key-protected package (default: null)]' \ + '(-p|--preserve)'{-p,--preserve}'[temp files are preserved that would otherwise be deleted]' \ + '(-j|--validateschema)'{-j,--validateschema}'[sfdx-project.json is validated against JSON schema]' \ + '(-w|--wait)'{-w,--wait}'[minutes to wait for the package version to be created (default:0)]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package1:version:create:get) + _command_args=( + '(-i|--requestid)'{-i,--requestid}'[PackageUploadRequest ID]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package2:version:create:get) + _command_args=( + '(-i|--package2createrequestid)'{-i,--package2createrequestid}'[package2 version creation request ID (starts with 08c)]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package2:version:create:list) + _command_args=( + '(-c|--createdlastdays)'{-c,--createdlastdays}'[created in the last specified number of days (starting at 00:00:00 of first day to now; 0 for today)]' \ + '(-s|--status)'{-s,--status}'[filter the list by version creation request status (Queued,InProgress,Success,Error)]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package1:version:display) + _command_args=( + '(-i|--packageversionid)'{-i,--packageversionid}'[metadata package version ID (starts with 04t)]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package2:version:get) + _command_args=( + '(-i|--package2versionid)'{-i,--package2versionid}'[the package version ID (starts wtih 05i)]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package1:version:list) + _command_args=( + '(-i|--packageid)'{-i,--packageid}'[metadata package ID (starts with 033)]' \ + '(-u|--targetusername)'{-u,--targetusername}'[username or alias for the target org; overrides default target org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:package2:version:list) + _command_args=( + '(-c|--createdlastdays)'{-c,--createdlastdays}'[created in the last specified number of days (starting at 00:00:00 of first day to now; 0 for today)]' \ + '(-m|--modifiedlastdays)'{-m,--modifiedlastdays}'[list items modified in the specified last number of days (starting at 00:00:00 of first day to now; 0 for today)]' \ + '(-i|--package2ids)'{-i,--package2ids}'[filter results on specified comma-delimited package2 ids (start with 0Ho)]' \ + '(-r|--released)'{-r,--released}'[display released versions only]' \ + '(-o|--orderby)'{-o,--orderby}'[order by the specified package2 version fields]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--concise)--concise[display limited package2 version details]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + '(--verbose)--verbose[display extended package2 versions detail]' \ + ) + ;; + force:package2:version:update) + _command_args=( + '(-i|--package2versionid)'{-i,--package2versionid}'[the package version ID (starts wtih 05i)]' \ + '(-n|--name)'{-n,--name}'[the package version name]' \ + '(-d|--description)'{-d,--description}'[the package version description]' \ + '(-b|--branch)'{-b,--branch}'[the package version branch]' \ + '(-t|--tag)'{-t,--tag}'[the package version tag]' \ + '(-k|--installationkey)'{-k,--installationkey}'[installation key for key-protected package (default: null)]' \ + '(-s|--setasreleased)'{-s,--setasreleased}'[set the package version as released (can’t be undone)]' \ + '(-v|--targetdevhubusername)'{-v,--targetdevhubusername}'[username or alias for the dev hub org; overrides default dev hub org]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + force:auth:web:login) + _command_args=( + '(-i|--clientid)'{-i,--clientid}'[OAuth client ID (sometimes called the consumer key)]' \ + '(-r|--instanceurl)'{-r,--instanceurl}'[the login URL of the instance the org lives on]' \ + '(-d|--setdefaultdevhubusername)'{-d,--setdefaultdevhubusername}'[set the authenticated org as the default dev hub org for scratch org creation]' \ + '(-s|--setdefaultusername)'{-s,--setdefaultusername}'[set the authenticated org as the default username that all commands run against]' \ + '(-a|--setalias)'{-a,--setalias}'[set an alias for the authenticated org]' \ + '(--disablemasking)--disablemasking[disable masking of user input (for use with problematic terminals)]' \ + '(--json)--json[format output as json]' \ + '(--loglevel)--loglevel[logging level for this command invocation (error*,trace,debug,info,warn,fatal)]' \ + ) + ;; + esac + +_arguments \ + $_command_args \ + && return 0 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_shellcheck b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_shellcheck new file mode 100644 index 00000000..20d023ef --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_shellcheck @@ -0,0 +1,65 @@ +#compdef shellcheck +# ------------------------------------------------------------------------------ +# Copyright (c) 2021 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for shellcheck (https://github.com/koalaman/shellcheck) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Khue Nguyen (https://github.com/Z5483) +# +# ------------------------------------------------------------------------------ + +_arguments \ + {-a,--check-sourced}'[include warnings from sourced file]' \ + {-C,--color=}'[specify color]:color:(auto always never)' \ + {-i,--include=}'[consider only given types of warnings]:error code' \ + {-e,--exclude=}'[exclude given types of warnings]:error code' \ + {-f,--format=}'[specify output format]:format:(checkstyle diff gcc json json1 quiet tty)' \ + '--list-optional[list checks disabled by default]' \ + "--norc[don't look for .shellcheckrc files]" \ + {-o,--enable=}"[give list of optional checks to enable (or 'all')]:error code" \ + {-P,--source-path=}'[specify path when looking for sourced files]:_files -/' \ + {-s,--shell=}'[specify dialect]:dialect:(sh bash dash ksh)' \ + {-S,--severity=}'[specify minimum severity of errors to consider]:severity:(error warning info style)' \ + {-V,--version}'[print version information]' \ + {-W,--wiki-link-count=}'[specify number of wiki links to show, when applicable]:number' \ + {-x,--external-sources}'[allow outside sources]' \ + '--help[show this usage summary and exit]' \ + '*: :_files' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_showoff b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_showoff new file mode 100644 index 00000000..05105fa2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_showoff @@ -0,0 +1,163 @@ +#compdef showoff +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Showoff 0.20.3 (https://github.com/puppetlabs/showoff). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Bruno Michel (https://github.com/nono) +# * Shoehi Yoshida (https://github.com/nono) +# +# ------------------------------------------------------------------------------ + +_showoff_subcommands() { + local -a commands=( + "add:Add a new slide at the end in a given dir" + "new:Add a new slide at the end in a given dir" + "create:Create new showoff presentation" + "init:Create new showoff presentation" + "github:Puts your showoff presentation into a gh-pages branch" + "help:Shows a list of commands or help for one command" + "heroku:Setup your presentation to serve on Heroku" + "info:Display information about a Showoff presentation" + "pdf:Generate PDF version of presentation" + "serve:Serves the showoff presentation in the specified (or current) directory" + "skeleton:Build a showoff presentation from a showoff.json outline" + "static:Generate static version of presentation" + "validate:Validate the consistency of your presentation" + ) + + _describe -t commands 'showoff command' commands +} + +_showoff_help() { + local -a commands=(${(@f)"$(showoff help -c 2>/dev/null)"}) + _values 'commands' $commands +} + +_showoff() { + local curcontext="$curcontext" state line ret=1 + + _arguments -C \ + '--debug[Show application backtraces on crash]' \ + '--dev[Use the next-gen development version of Showoff]' \ + '(- *)--help[Show help message]' \ + '(- *)--version[Display the program version]' \ + '1: :_showoff_subcommands' \ + '*:: :->args' \ + && ret=0 + + case $state in + (args) + case $line[1] in + (add|new) + _arguments \ + '(-d --dir)'{-d,--dir}='[Slide dir (where to put a new slide file)]:directory:_files -/' \ + '(-n --name)'{-n,--name}='[Slide name (name of the new slide file)]:basename' \ + {-s,--source}='[Include code from the given file as the slide body]:file:_files' \ + '(-t --style --type)'{-t,--style,--type}='[Slide Type/Style (default: title)]:style' \ + '(-u --nonumber)'{-u,--nonumber}"[Don't number the slide, use the given name verbatim]" \ + '1:title' && ret=0 + ;; + (create|init) + _arguments \ + '(-d --slidedir)'{-d,--slidedir}='[Sample slide directory name (default: one)]:arg' \ + '(-n --nosamples)'{-n,--nosamples}="[Don't create sample slides]" \ + '1:dir_name' && ret=0 + ;; + (help) + _arguments \ + '-c[List commands one per line, to assist with shell completion]' \ + '1: :_showoff_help' && ret=0 + ;; + (heroku) + _arguments \ + '(-f --force)'{-f,--force}'[force overwrite of existing Gemfile, .gems and config.ru files if they exist]' \ + '(-p --password)'{-p,--password}='[add password protection to your heroku site(default: none)]' \ + '1:heroku_name' && ret=0 + ;; + (info) + _arguments \ + '(-f --file)'{-f,--file}='[alternate json filename]: :_files -g "*.json"' \ + '(-j --json)'{-j,--json}'[render output as json]' \ + && ret=0 + ;; + (pdf|static) + _arguments \ + '(-f --file --pres_file)'{-f,--file,--pres_file}='[JSON file used to describe presentation(default: showoff.json)]: :_files -g "*.json"' \ + '(-l --lang --language --locale)'{-l,--lang,--language,--locale}'[Language code to generate(default: none)]' \ + '1:name' \ + && ret=0 + ;; + (serve) + _arguments \ + '(-S --standalone)'{-S,--standalone}'[Run in standalone mode with no audience interaction]' \ + '(-f --file --pres_file)'{-f,--file,--pres_file}='[JSON file used to describe presentation(default: showoff.json)]: :_files -g "*.json"' \ + '--git_branch=[Branch of git repository to use(default: none)]:branch' \ + '--git_path=[Path of the presentation within the git repository(default: none)]:path' \ + '(-h --host)'{-h,--host}='[Host or ip to run on(default: 0.0.0.0)]' \ + '--nocache[Disable content caching]'\ + '--nosleep[Prevent the computer from sleeping during your presentation]' \ + '(-p --port)'{-p,--port}='[Port on which to run(default: 9090)]' \ + '(-r --review)'{-r,--review}'[Enable code review]'\ + '(-s --ssl)'{-s,--ssl}'[Run via HTTPS]' \ + '--ssl_certificate=[Path to SSL certificate]: :_files' \ + '--ssl_private_key=[Path to SSL private key]: :_files' \ + '(-u --url --git_url)'{-u,--url,--git_url}='[GIT URL to a repository containing the presentation]:url' \ + '(-v --verbose)'{-v,--verbose}'[Show verbose messaging]' \ + '(-x --execute --executecode)'{-x,--execute,--executecode}'[Enable remote code execution]' \ + '1: :_files -/' && ret=0 + ;; + (skeleton|validate) + _arguments \ + '(-f --file)'{-f,--file}'=[alternate json filename(default: none)]: :_files -g "*.json"' \ + && ret=0 + ;; + *) + (( ret )) && _message 'no more arguments' + ;; + esac + ;; + esac + + return ret +} + +_showoff "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_srm b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_srm new file mode 100644 index 00000000..f997c9f6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_srm @@ -0,0 +1,109 @@ +#compdef srm +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for srm. +# +# It is based on the rm completion script from Zsh. +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Sorin Ionescu +# +# ------------------------------------------------------------------------------ + +local -a args +local variant + +args=( + '*::files:->file' +) + +_pick_variant -r variant gnu=gnu thc=THC unix --help + +if [[ $variant == "thc" ]]; then + args+=( + '-d[ignore the two special dot files . and .. on the commandline]' + '-f[fast (and insecure mode)]' + '*-l[lessens the security. -l for a second time lessons the security even more]' + '-r[recursive mode]' + '-v[verbose mode]' + '-z[wipes the last write with zeros instead of random data]' + ) +else + args+=( + '(-f --force)'{-f,--force}'[ignore nonexistent files, never prompt]' + '(-r --interactive)'{-i,--interactive}'[prompt before any removal]' + '(-r -R --recursive)'{-r,-R,--recursive}'[remove the contents of directories recursively]' + '(-s --simple)'{-s,--simple}'[only overwrite with a single pass of random data]' + '(-v --verbose)'{-v,--verbose}'[explain what is being done]' + '(- *)--help[display help message and exit]' + '(- *)--version[output version information and exit]' + ) + + if [[ $variant == "gnu" ]]; then + args+=( + '(-x --one-file-system)'{-x,--one-file-system}'[stay within filesystems of files given as arguments]' + '(-P --openbsd)'{-P,--openbsd}'[overwrite the file 3 times (0xff, 0x00, 0xff)]' + '(-D --dod)'{-D,--dod}'[overwrite the file with 7 US DoD compliant passes (0xF6, 0x00, 0xFF, random, 0x00, 0xFF, random)]' + '(-E --doe)'{-E,--doe}'[overwrite the file with 3 US DoE compliant passes (random, random, DoE)]' + ) + else + args+=( + '(-m --medium)'{-m,--medium}'[overwrite the file with 7 US DoD compliant passes (0xF6, 0x00, 0xFF, random, 0x00, 0xFF, random)]' + '(-z --zero)'{-z,--zero}'[after overwriting, zero blocks used by file]' + '(-n --nounlink)'{-n,--nounlink}'[overwrite file, but do not rename or unlink it]' + ) + fi +fi + +local curcontext=$curcontext state line ret=1 +local -A opt_args + +_arguments -s -S -C $args && ret=0 + +case $state in + (file) + local -a ignored + ignored=() + ((CURRENT > 1)) && + ignored+=(${line[1,CURRENT-1]//(#m)[\[\]()\\*?#<>~\^]/\\$MATCH}) + ((CURRENT < $#line)) && + ignored+=(${line[CURRENT+1,-1]//(#m)[\[\]()\\*?#<>~\^]/\\$MATCH}) + _files -F ignored && ret=0 + ;; +esac + +return $ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_stack b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_stack new file mode 100644 index 00000000..847328c7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_stack @@ -0,0 +1,134 @@ +#compdef stack +# ------------------------------------------------------------------------------ +# Copyright (c) 2015 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ------------------------------------------------------------------------------ +# +# Completion script for stack (https://github.com/commercialhaskell/stack). +# +# ------------------------------------------------------------------------------ +# Authors +# ------------------------------------------------------------------------------ +# +# * Toshiki Teramura +# * Nikita Ursol +# +# ------------------------------------------------------------------------------ + +_stack () { + _arguments \ + --help'[show usage information]' \ + --version'[show version]' \ + --numeric-version'[show only version number]' \ + --hpack-numeric-version"[show only hpack's version number]" \ + '--docker[enable using a Docker container, run "stack --docker-help" for details]' \ + '--no-docker[disable using a Docker container, run "stack --docker-help" for details]' \ + '--nix[enable use of a Nix-shell, run "stack --nix-help" for details]' \ + '--no-nix[disable use of a Nix-shell, run "stack --nix-help" for details]' \ + --verbosity'[verbosity: silent, error, warn, info, debug]' \ + {-v,--verbose}'[enable verbose mode: verbosity level "debug"]' \ + --silent'[enable silent mode: verbosity level "silent"]' \ + --time-in-log'[enable inclusion of timings in logs, to use diff with logs]' \ + --no-time-in-log'[disable inclusion of timings in logs, to use diff with logs]' \ + --stack-root'[absolute path to the global stack root directory]' \ + --work-dir'[relative path of work directory]' \ + --system-ghc'[enable using the system installed GHC if available and a matching version]' \ + --no-system-ghc'[disable using the system installed GHC if available and a matching version]' \ + --install-ghc'[enable downloading and installing GHC if necessary]' \ + --no-install-ghc'[disable downloading and installing GHC if necessary]' \ + --arch'[system architecture, e.g. i386, x86_64]' \ + --ghc-variant'[specialized GHC variant, e.g. integersimple (incompatible with --system-ghc)]' \ + --ghc-build'[specialized GHC build, e.g. "gmp4" or "standard" (usually auto-detected)]' \ + {-j,--jobs}'[number of concurrent jobs to run]' \ + --extra-include-dirs'[extra directories to check for C header files]' \ + --extra-lib-dirs'[extra directories to check for libraries]' \ + --with-gcc'[use custom path to gcc executable]' \ + --with-hpack'[use custom path to hpack executable]' \ + --skip-ghc-check'[enable skipping the GHC version and architecture check]' \ + --no-skip-ghc-check'[disable skipping the GHC version and architecture check]' \ + --skip-msys'[enable skipping the local MSYS installation (Windows only)]' \ + --no-skip-msys'[disable skipping the local MSYS installation (Windows only)]' \ + --local-bin-path'[install binaries to specified location]' \ + --setup-info-yaml'[alternate URL or relative / absolute path for stack dependencies]' \ + --modify-code-page'[enable setting the codepage to support UTF-8 (Windows only)]' \ + --no-modify-code-page'[disable setting the codepage to support UTF-8 (Windows only)]' \ + --allow-different-user'[enable permission for non-owners to use a stack installation (POSIX only)]' \ + --no-allow-different-user'[disable permission for non-owners to use a stack installation (POSIX only)]' \ + --dump-logs'[enable dump the build output logs for local packages to the console]' \ + --no-dump-logs'[disable dump the build output logs for local packages to the console]' \ + {--color,--colour}'[specify when to use color in output; accepts "always", "never", "auto"]' \ + --resolver'[override resolver in project file]' \ + --terminal'[enable overriding terminal detection in the case of running in a false terminal]' \ + --no-terminal'[disable overriding terminal detection in the case of running in a false terminal]' \ + {--stack-colors,--stack-colours}"[specify stack's output styles]" \ + --terminal-width'[specify the width of the terminal, used for pretty-print messages]' \ + --stack-yaml'[override project stack.yaml file]' \ + --lock-file'[specify how to interact with lock files.]' \ + '*: :__stack_modes' +} + +__stack_modes () { + _values \ + 'subcommand' \ + 'build[build the project(s) in this directory/configuration]' \ + 'install[build executables and install to a user path]' \ + 'test[build and test the project(s) in this directory/configuration]' \ + 'bench[build and benchmark the project(s) in this directory/configuration]' \ + 'haddock[generate haddocks for the project(s) in this directory/configuration]' \ + 'new[create a brand new project]' \ + 'templates[show how to find templates available for "stack new".]' \ + 'init[create stack project config from cabal or hpack package specifications]' \ + 'setup[get the appropriate ghc for your project]' \ + 'path[print out handy path information]' \ + "ls[list command. (supports snapshots, dependencies and stack's styles)]" \ + 'unpack[unpack one or more packages locally]' \ + 'update[update the package index]' \ + 'upgrade[upgrade to the latest stack]' \ + 'upload[upload a package to Hackage]' \ + 'sdist[create source distribution tarballs]' \ + 'dot[visualize your projects dependency graph using Graphviz dot]' \ + 'ghc[run ghc]' \ + 'hoogle[run hoogle, the Haskell API search engine.]' \ + 'exec[execute a command]' \ + 'run[build and run an executable.]' \ + 'ghci[run ghci in the context of package(s) (experimental)]' \ + "repl[run ghci in the context of package(s) (experimental) (alias for 'ghci')]" \ + 'runghc[run runghc]' \ + "runhaskell[run runghc (alias for 'runghc')]" \ + 'script[run a Stack Script]' \ + 'eval[evaluate some haskell code inline.]' \ + 'clean[delete build artefacts for the project packages.]' \ + 'purge[delete the project stack working directories.]' \ + 'query[query general build information (experimental)]' \ + 'ide[ide-specific commands]' \ + 'docker[subcommands specific to Docker use]' \ + 'config[subcommands for accessing and modifying configuration values]' \ + 'hpc[subcommands specific to Haskell Program Coverage]' + +} + +_stack "$@" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_subliminal b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_subliminal new file mode 100644 index 00000000..f70cf593 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_subliminal @@ -0,0 +1,81 @@ +#compdef subliminal +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Subliminal (https://github.com/Diaoul/subliminal). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# * Shohei Yoshida +# +# ------------------------------------------------------------------------------ + +_subliminal() { + typeset -A opt_args + local context state line + local curcontext="$curcontext" + local ret=1 + + _arguments -C \ + '--addic7ed[Addic7ed configuration]:user name:' \ + '--legendastv[LegendasTV configuration]:user name:' \ + '--opensubtitles[OpenSubtitles configuration]:user name:' \ + '--omdb[OMDB API key]:key' \ + '--cache-dir[Path to the cache directory]: :_files -/' \ + '--debug[Print useful information for debugging]' \ + '(- : *)--version[show version number and exit]' \ + '(- : *)--help[show help message and exit]' \ + '1: :(cache download)' \ + '*::arg:->command' \ + && ret=0 + + case "$state" in + (command) + case $words[1] in + (cache) + _arguments -C \ + '(- *)--help[Show help message and exit]' \ + "--clear-subliminal[Clear subliminal's cache]" \ + '*: :_files' \ + && ret=0 + ;; + (download) + _arguments -C \ + '(-l --language)'{-l,--language}'[Language as IETF code]:lang' \ + \*{-p,--provider}'[Provider to use]: :(argenteam legendastv opensubtitles opensubtitlesvip podnapisi shooter thesubdb tvsubtit)' \ + \*{-r,--refiner}'[Refiner to use]: :(hash metadata omdb tvdb)' \ + '(-a --age)'{-a,--age}'[Filter videos newer than AGE]:age' \ + '(-d --directory)'{-d,--directory}'[Directory where to save subtitles]: :_files -/' \ + '(-e --encoding)'{-e,--encoding}'[Subtitle file encoding]:encoding' \ + '(-s --single)'{-s,--single}'[Save subtitle without language code in the file name]' \ + '(-f --force)'{-f,--force}'[Force download even if a subtitle already exist]' \ + '(-hi,--hearing-impaired)'{-hi,--hearing-impaired}'[Prefer hearing impaired subtitles]' \ + '(-m --min-score)'{-m,--min-score}'[Minimum score for a subtitle to be downloaded]:integer range:' \ + '(-w --max-worked)'{-w,--max-workers}'[Maximum number of threads to use]:integer range:' \ + '(-z --archives -Z --no-archives)'{-z,--archives}'[Scan archives for videos]' \ + '(-z --archives -Z --no-archives)'{-Z,--no-archives}'[Scan archives for videos]' \ + '--verbose[Increase verbosity]' \ + '(- *)--help[Show help message and exit]' \ + '*: :_files' \ + && ret=0 + ;; + esac + ;; + esac + + return ret +} + +_subliminal "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_supervisorctl b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_supervisorctl new file mode 100644 index 00000000..f8edb4c2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_supervisorctl @@ -0,0 +1,237 @@ +#compdef supervisorctl +# ------------------------------------------------------------------------------ +# Copyright (c) 2015 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for supervisorctl 4.2.5 from Supervisord (https://github.com/Supervisor/supervisor) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Matt Black (https://github.com/mafrosis) +# * dongweiming (https://github.com/dongweiming) +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_supervisorctl() { + local -a procs + typeset -A opt_args + local context state line + local curcontext="$curcontext" + local ret=1 + + _arguments -C \ + {--configuration,-c}='[configuration file path (default /etc/supervisor.conf)]:filename:_files' \ + '(- *)'{--help,-h}'[print usage message and exit]:' \ + {--interactive,-i}'[start an interactive shell after executing commands]' \ + {--serverurl,-s}='[URL on which supervisord server is listening (default "http://localhost:9001")]:url:_urls' \ + {--username,-u}='[username to use for authentication with server]:username:_users' \ + {--password,-p}='[password to use for authentication with server]:password' \ + {--history-file,-r}'[keep a readline history (if readline is available)]:filename:_files' \ + '1: :_supervisorctl_subcommands' \ + '*:: :->subcmds' && ret=0 + + case $state in + (subcmds) + case "$words[1]" in + (help) + _arguments \ + '1: :_supervisorctl_subcommands' \ + && ret=0 + ;; + (add|remove) + _arguments \ + '1: :_supervisorctl_procs_groups' \ + && ret=0 + ;; + (fg) + _arguments \ + '1: :_supervisorctl_processes' \ + && ret=0 + ;; + (pid|clear) + _arguments \ + '*: :_supervisorctl_processes_all' \ + && ret=0 + ;; + (restart|status) + _arguments \ + '*:process_or_group:_supervisorctl_procs_and_group_prefixes' \ + && ret=0 + ;; + (update) + _arguments \ + '*: :_supervisorctl_groups' \ + && ret=0 + ;; + (stop) + _arguments \ + '*:running process or group:_supervisorctl_running_procs' \ + && ret=0 + ;; + (start) + _arguments \ + '*:stopped process or group:_supervisorctl_stopped_procs' \ + && ret=0 + ;; + (signal) + _arguments \ + '1:signal:_signals -s' \ + '*:running process or group:_supervisorctl_running_procs' \ + && ret=0 + ;; + (tail) + _arguments \ + '-f[Continuous tail of named process stdout]' \ + '-[last N *bytes* of process stdout]:number' \ + '1: :_supervisorctl_processes' \ + '2:output:(stdout stderr)' \ + && ret=0 + ;; + (maintail) + _arguments \ + '-f[Continuous tail of named process stdout]' \ + '-[last N *bytes* of process stdout]:number' \ + && ret=0 + ;; + esac + esac + + return 0 +} + +(( $+functions[_supervisorctl_subcommands] )) || +_supervisorctl_subcommands() { + local -a commands=( + 'add:Activates any updates in config for process/group' + 'avail:Display all configured processes' + 'clear:Clear single/multiple/all process log files' + 'exit:Exit the supervisor shell' + 'fg:Connect to a process in foreground mode' + 'maintail:tail of supervisor main log file' + 'open:Connect to a remote supervisord process. (for UNIX domain socket, use unix:///socket/path)' + 'pid:Get the PID of process/supervisord' + 'quit:Exit the supervisor shell' + 'reload:Restart the remote supervisord' + 'remove:Removes process/group from active config' + "reread:Reload the daemon's configuration files" + 'restart:Restart process, group or all' + 'signal:Send signal to a process' + 'shutdown:Shut the remote supervisord down' + 'start:Start process, group or all' + 'status:Get process/group status info' + 'stop:Stop process, group or all' + 'tail:tail of process stdout' + 'update:Reload config and add/remove as necessary' + 'version:Show the version of the remote supervisord process' + 'help:Show help' + ) + + _describe -t commands 'command' commands "$@" +} + +(( $+functions[_supervisorctl_processes] )) || +_supervisorctl_processes() { + local -a procs + procs=(${(f)"$(_call_program processes supervisorctl avail | awk '{gsub(":","\\:", $1); print $1 }')"}) + if [[ "$1" = 'all' ]]; then + procs+=(all) + fi + _describe 'processes' procs +} + +(( $+functions[_supervisorctl_processes_all] )) || +_supervisorctl_processes_all() { + _supervisorctl_processes all +} + +(( $+functions[_supervisorctl_procs_groups] )) || +_supervisorctl_procs_groups() { + local -a procs + procs=(${(f)"$(_call_program processes supervisorctl status \ + | awk '{n=$1;gsub(":","\\:",n); printf "%s\n%s\n",n,substr($1,1,index($1,":")-1)}' \ + | uniq)"}) + _describe 'process and groups' procs +} + +(( $+functions[_supervisorctl_procs_and_group_prefixes] )) || +_supervisorctl_procs_and_group_prefixes() { + _supervisorctl_collect_procs '.' +} + +(( $+functions[_supervisorctl_running_procs] )) || +_supervisorctl_running_procs() { + _supervisorctl_collect_procs 'RUNNING' +} + +(( $+functions[_supervisorctl_stoped_procs] )) || +_supervisorctl_stopped_procs() { + _supervisorctl_collect_procs 'STOPPED' +} + +(( $+functions[_supervisorctl_collect_procs] )) || +_supervisorctl_collect_procs() { + if (( $words[(I)all] )); then + return + fi + + local pattern=$1 + + local -a procs + procs=(${(f)"$(_call_program processes supervisorctl status \ + | awk "/$pattern/"'{n=$1;gsub(":","\\:",n); printf "%s\n%s\\:\n",n,substr($1,1,index($1,":")-1)}' \ + | uniq)"}) + procs+=(all) + _describe 'stooped processes or groups' procs +} + +(( $+functions[_supervisorctl_groups] )) || +_supervisorctl_groups() { + if (( $words[(I)all] )); then + return + fi + + local -a groups + groups=(${(f)"$(_call_program processes supervisorctl status \ + | awk '{printf "%s\n",substr($1,1,index($1,":")-1)}' \ + | uniq)"}) + groups+=(all) + _describe 'groups' groups +} + +_supervisorctl "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_supervisord b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_supervisord new file mode 100644 index 00000000..98210a0b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_supervisord @@ -0,0 +1,65 @@ +#compdef supervisord +# ------------------------------------------------------------------------------ +# Copyright (c) 2023 Github zsh-users - https://github.com/zsh-users +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for supervisord. (https://github.com/Supervisor/supervisor) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei YOSHIDA (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_arguments \ + '(-c --configuration)'{-c,--configuration}'[configuration file path]:config file:_files' \ + '(-n --nodaemon)'{-n,--nodaemon}'[run in the foreground]' \ + '(-s --silent)'{-s,--silent}'[no longs to stdout]' \ + '(- *)'{-h,--help}'[print this usage message and exit]' \ + '(- *)'{-v,--version}'[print supervisord version number and exit]' \ + '(-u --user)'{-u,--user}'[run supervisord as given user]:user:_users' \ + '(-m --umask)'{-m,--umask}'[use given umask for daemon subprocess]:umask' \ + '(-d --directory)'{-d,--directory}'[directory to chdir to when daemonized]:directory:_files -/' \ + '(-l --logfile)'{-l,--logfile}'[logfile path]:logfile:_files' \ + '(-y --logfile_maxbytes)'{-y,--logfile_maxbytes}'[limit the max size of logfile]:max bytes' \ + '(-z --logfile_backups)'{-z,--logfile_backups}'[number of backups to keep when max bytes reached]:number of backups' \ + '(-e --loglevel)'{-e,--loglevel}'[log level]:level:(debug info warn error critical)' \ + '(-j --pidfile)'{-j,--pidfile}'[pid file path]:pid file:_files' \ + '(-i --identifier)'{-i,--identifier}'[identifier used for this instance of supervisord]:id' \ + '(-q --childlogdir)'{-q,--childlogdir}'[the log directory for child process logs]:log dir:_files -/' \ + '(-k --nocleanup)'{-k,--nocleanup}'[prevent the process from performing cleanup]' \ + '(-a --minfds)'{-m,--minfds}'[the minimum number of file descriptors for start success]:min fds' \ + '(-t --strip_ansi)'{-t,--strip_ansi}'[strip ansi escape codes from process output]' \ + '--profile_options[profile options]:profile option:_values -s , "field" cumulative calls callers' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_svm b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_svm new file mode 100644 index 00000000..77823979 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_svm @@ -0,0 +1,172 @@ +#compdef svm +# ------------------------------------------------------------------------------ +# Copyright (c) 2011 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for svm (https://github.com/yuroyoro/svm) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Hideaki Miyake (https://github.com/mollifier) +# +# ------------------------------------------------------------------------------ + +local context curcontext="$curcontext" state line ret=1 +typeset -A opt_args + + +local -a _1st_arguments +_1st_arguments=( + 'help:show this usage information' + 'current:show the currently use scala version' + "list:show the scala version installed in svm_path(default is ${HOME}/.svm)" + "versions:show the available scala version not installed" + 'install:install specific scala version' + 'remove:uninstall specific scala version and remove their sources' + 'switch:setup to use a specific scala version' + 'update-latest:install or update nightly build scala version' + 'latest:setup to use nightly build scala version' + 'stable:setup to use stable(x.x.x.final) scala version' + 'self-update:update svm itself' +) + +_arguments -C \ + '(-)-h[show this usage information]' \ + '-c[show the currently use scala version]' \ + "-l[show the scala version installed in svm_path(default is ${HOME}/.svm)]" \ + '-v[show the available scala version not installed]' \ + '-i[install specific scala version]: :_svm_completion_not_installed_scala_versions' \ + '-r[uninstall specific scala version and remove their sources]: :_svm_completion_installed_scala_versions' \ + '(-s -u)'{-s,-u}'[setup to use a specific scala version]: :_svm_completion_not_selected_scala_versions' \ + '1: :->cmds' \ + '*:: :->args' && ret=0 + + +# installed scala versions +(( $+functions[_svm_completion_installed_scala_versions] )) || +_svm_completion_installed_scala_versions() { + local -a _installed_versions + _current_version="${$(_call_program installed svm current)#currently version is[[:space:]]*}" + + # collect lines starts with digit + _installed_versions=( ${(M)${(@f)"$(_call_program installed svm list)"}:#[[:digit:]]*} ) + + _describe -t installed "installed versions" _installed_versions +} + +# installed and not selected scala versions +(( $+functions[_svm_completion_not_selected_scala_versions] )) || +_svm_completion_not_selected_scala_versions() { + local _current_version + local -a _not_selected_versions + + _current_version="${$(_call_program installed svm current)#currently version is[[:space:]]*}" + + # collect lines starts with digit + _not_selected_versions=( ${(M)${(@f)"$(_call_program installed svm list)"}:#[[:digit:]]*} ) + + # remove current version + _not_selected_versions=( ${_not_selected_versions:#$_current_version}) + _describe -t installed "not selected versions" _not_selected_versions +} + +# not installed scala versions +(( $+functions[_svm_completion_not_installed_scala_versions] )) || +_svm_completion_not_installed_scala_versions() { + local -a _not_installed_versions + # collect lines starts with digit + _not_installed_versions=( ${(M)${(@f)"$(_call_program installed svm versions)"}:#[[:digit:]]*} ) + + _describe -t notinstalled "not installed versions" _not_installed_versions +} + + +case $state in + cmds) + # action + case $PREFIX in + u*) + # complete command synonyms + local -a _synonym_arguments + _synonym_arguments=( + 'uninstall:uninstall specific scala version and remove their sources' + 'use:setup to use a specific scala version' + 'update-latest:install or update nightly build scala version' + ) + _describe -t actions 'svm actions' _synonym_arguments && ret=0 + ;; + + *) + _describe -t actions 'svm actions' _1st_arguments + _svm_completion_not_selected_scala_versions && ret=0 + ;; + esac + ;; # end action + + args) + # scala version number + case $words[1] in + (install) + # install not installed version + _arguments \ + '1: :_svm_completion_not_installed_scala_versions' \ + '--docs[download scala-devel-docs]' \ + '--sources[download scala-sources]' && ret=0 + ;; + (update-latest) + # update nightly build scala version + _arguments \ + '--docs[download scala-devel-docs]' \ + '--sources[download scala-sources]' && ret=0 + ;; + (remove|uninstall) + # remove installed version + _arguments \ + '1: :_svm_completion_installed_scala_versions' && ret=0 + ;; + (switch|use) + # use installed version + _arguments \ + '1: :_svm_completion_not_selected_scala_versions' && ret=0 + ;; + esac + + ;; # end args +esac + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_teamocil b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_teamocil new file mode 100644 index 00000000..faf1e2af --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_teamocil @@ -0,0 +1,56 @@ +#compdef teamocil +# ------------------------------------------------------------------------------ +# Copyright (c) 2014 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for Teamocil 1.4.2 (https://github.com/remiprev/teamocil). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Petr Zelenin +# +# ------------------------------------------------------------------------------ + +_arguments \ + '--here[set up the first window in the current window]' \ + '--edit[edit the YAML layout file instead of using it]' \ + '--layout [use a specific layout file, instead of \`~/.teamocil/.yml\`]' \ + '--list[list all available layouts in \`~/.teamocil/\`]' \ + '--show[show the content of the layout file instead of executing it]' \ + '--debug[show the commands Teamocil will execute instead of actually executing them]' \ + '*:teamocil layouts:_files -W ~/.teamocil -g "*.yml(:r)"' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_thor b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_thor new file mode 100644 index 00000000..9e1e66d6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_thor @@ -0,0 +1,133 @@ +#compdef thor +# ------------------------------------------------------------------------------ +# Copyright (c) 2009-2015 Robby Russell and contributors (see +# https://github.com/ohmyzsh/ohmyzsh/graphs/contributors +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for thor 1.2.1 (https://github.com/rails/thor). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Andrew Hodges (https://github.com/betawaffle) +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_thor_subcommands() { + local -a commands=( + 'help:Describe available commands or one specific command' + ) + + if [[ -e Thorfile ]]; then + commands=(${(@f)"$(thor list 2>/dev/null | awk '/^thor/{sub(/^thor /,"\\"); sub(/[ ]*#[ ]*/,":");print}')"} $commands) + else + commands=( + $commands + 'install:Install an optionally named Thor file into your system commands' + 'installed:List the installed Thor modules and commands' + 'list:List the available thor commands' + 'uninstall:Uninstall a named Thor module' + 'update:Update a Thor file from its original location' + 'version:Show Thor version' + ) + fi + + _describe -t commands 'command' commands "$@" +} + +_thor_help() { + local -a commands + + if [[ -e Thorfile ]]; then + commands=(${(@f)"$(thor list 2>/dev/null | awk "/^thor/{ printf \"\\\\%s\\n\", \$2 }")"}) + else + commands=(help install installed list uninstall update version) + fi + + _values 'help' $commands +} + +_thor() { + typeset -A opt_args + local context state line + local curcontext="$curcontext" + local ret=1 + + _arguments -C -A "-*" \ + '1: :_thor_subcommands' \ + '*::arg:->args' \ + && ret=0 + + case "$state" in + (args) + case $words[1] in + (help) + _arguments \ + '1: :_thor_help' \ + && ret=0 + ;; + (install) + _arguments \ + '--as=[specify the name]:name' \ + '--relative[use relative path]' \ + '--force[force install]' \ + '*: :_files' \ + && ret=0 + ;; + (installed) + _arguments \ + '--internal[show internal]' \ + && ret=0 + ;; + (list) + _arguments \ + '--substring[use search keyword as substring]' \ + '--group=[specify the group name]' \ + '--all[search from all groups]' \ + '--debug[show all back trace if error raises]' \ + '*::' \ + && ret=0 + ;; + (*) + _arguments \ + '*::_files' \ + && ret=0 + ;; + esac + ;; + esac + + return ret +} + +_thor "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_tmuxinator b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_tmuxinator new file mode 100644 index 00000000..9fff48e9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_tmuxinator @@ -0,0 +1,65 @@ +#compdef tmuxinator mux +# ------------------------------------------------------------------------------ +# Copyright (c) 2010-2016 Christopher Chow +# +# 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. +# ------------------------------------------------------------------------------ +# +# Description +# ----------- +# +# Completion script for tmuxinator (https://github.com/tmuxinator/tmuxinator) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Christopher Chow (https://github.com/Soliah) +# +# ------------------------------------------------------------------------------ + +_tmuxinator() { + local commands projects + commands=(${(f)"$(tmuxinator commands zsh)"}) + projects=(${(f)"$(tmuxinator completions start)"}) + + if (( CURRENT == 2 )); then + _describe -t commands "tmuxinator subcommands" commands + _describe -t projects "tmuxinator projects" projects + elif (( CURRENT == 3)); then + case $words[2] in + copy|debug|delete|open|start) + _arguments '*:projects:($projects)' + ;; + esac + fi + + return +} + +_tmuxinator + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_tmuxp b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_tmuxp new file mode 100644 index 00000000..be221e9b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_tmuxp @@ -0,0 +1,198 @@ +#compdef tmuxp + +# ------------------------------------------------------------------------------ +# Copyright (c) 2017 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for tmuxp (https://github.com/tmux-python/tmuxp) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Bez Hermoso +# +# ------------------------------------------------------------------------------ + +_tmuxp() { + + local curcontext="$curcontext" state line + typeset -A opt_args + + _arguments -C \ + ":command:->command" \ + "*::options:->options" \ + "--log-level[log level(default info)]: :(debug info warning error critical)" \ + '(- *)'{-h,--help}'[display usage information]' \ + '(- *)'{-V,--version}'[show version number and exit]' + + case $state in + (command) + local -a subcommands + subcommands=( + 'load:Load tmuxp workspaces' + 'shell:launch python shell for tmux server, session, window and pane' + 'import:Import a teamocil/tmuxinator config' + 'convert:Convert a tmuxp config between JSON and YAML' + 'debug-info:print out all diagnostic info' + 'ls:list sessions in config directory' + 'edit: run $EDITOR on config' + 'freeze:Snapshot a session into a config' + ) + _describe -t commands 'commands' subcommands + ;; + (options) + case $line[1] in + (load) + __tmuxp_load + ;; + (import) + __tmuxp_import + ;; + (freeze) + local sessions="$(__tmux_sessions)" + _arguments -C \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '-S[pass-through for tmux -S]: :_files' \ + '-L[pass-through for tmux -L]: :' \ + '(-f --config-format)'{-f,--config-format}'[format to save in]: :(yaml json)' \ + '(-o --save-to)'{-o,--save-to}'[file to save to]: :_files' \ + '(-y --yes)'{-y,--yes}'[always answer yes]' \ + '(-q --quiet)'{-q,--quiet}"[don't prompt for confirmation]" \ + '--force[overwrite the config file]'\ + "1::session name:compadd $sessions" + ;; + (convert) + _arguments -C \ + '1:: :_files -g "*.(json|yaml|yml)"' + ;; + (shell) + local sessions="$(__tmux_sessions)" + local windows="$(__tmux_windows)" + _arguments -C \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '-S[pass-through for tmux -S]: :_files' \ + '-L[pass-through for tmux -L]: :' \ + '--best[use best shell available in site packages]' \ + '--pdb[use plain pdb]' \ + "--code[use stdlib's code.interact()]" \ + '--ptipython[use ptpython + ipython]' \ + '--ptpython[use ptpython]' \ + '--ipython[use ipython]' \ + '--bpython[use bpython]' \ + (--no-startup)'--use-pythonrc[load PYTHONSTARTUP env var and ~/.pythonrc.py script in --code]' \ + (--use-pythonrc)'--no-startup[do not load PYTHONSTARTUP env var and ~/.pythonrc.py script in --code]' \ + (--no-vi-mode)'--use-vi-mode[use vi-mode in ptpython/ptipython]' \ + (--vi-mode)'--no-vi-mode[do not use vi-mode in ptpython/ptipython]' \ + "1::session name:compadd $sessions" \ + "2::window name:compadd $windows" + ;; + (ls|debug-info) + _arguments -C \ + '(- *)'{-h,--help}'[show help message and exit]' + ;; + (edit) + _arguments -C \ + '(- *)'{-h,--help}'[show help message and exit]' \ + '1:: :_files -g "*.(json|yaml|yml)"' + ;; + esac + esac + +} + +__tmuxp_load() { + local state line + typeset -A opt_args + _arguments -C \ + '*:sessions:->sessions' \ + '--yes:yes' \ + '-d[Load the session without attaching it]' \ + '-2[Force tmux to assume the terminal supports 256 colors]' \ + '-8[Like -2, but indicates that the terminal supports 88 colors]' + + # Can't get the options to be recognized when there are sessions that has + # a dash. + + local tmuxp_dir="${HOME}/.tmuxp" + local tmuxp_xdg_dir="${XDG_CONFIG_HOME:-${HOME}/.config}/tmuxp" + if [[ -d "${TMUXP_CONFIGDIR-}" ]]; then + tmuxp_dir="${TMUXP_CONFIGDIR}" + elif [[ -d "${tmuxp_xdg_dir}" ]]; then + tmuxp_dir="${tmuxp_xdg_dir}" + fi + case $state in + (sessions) + local s + _alternative \ + 'sessions-user:user session:compadd -F line - ${tmuxp_dir}/*.(json|yml|yaml)(:r:t)' \ + 'sessions-other:session in current directory:_path_files -/ -g "**/.tmuxp.(yml|yaml|json)"' \ + 'sessions-other:session in current directory:_path_files -g "*.(yml|yaml|json)"' + ;; + esac +} + +__tmuxp_import() { + local state line + typeset -A opt_args + _arguments -C \ + '1::program:(tmuxinator teamocil)' \ + '2::project:->project' + + case $state in + (project) + if [[ $line[1] == 'tmuxinator' ]] + then + _wanted tmuxinator-projects exp 'tmuxinator projects' compadd $(tmuxinator completions start) + fi + ;; + esac +} + +__tmux_sessions () { + local tmux_sessions + tmux_sessions=($(_call_program tmux_sessions 'tmux ls -F "#{session_name}"')) + echo $tmux_sessions +} + +__tmux_windows () { + local tmux_windows + tmux_windows=($(_call_program tmux_sessions 'tmux ls -F "#{window_name}"')) + echo $tmux_windows +} + +_tmuxp "$@" + + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_tox b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_tox new file mode 100644 index 00000000..17231e7a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_tox @@ -0,0 +1,67 @@ +#compdef tox +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for tox (https://tox.readthedocs.io). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Julien Nicoulaud +# +# ------------------------------------------------------------------------------ + + +(( $+functions[_tox_envs_list] )) || +_tox_envs_list() { + local envs; envs=($(_call_program envs $service --listenvs-all)) + if [ ${#envs} -gt 0 ]; then + _values -s , 'tox environments' "${envs[@]}" + else + _message 'tox environments (none found)' + fi +} + +_arguments \ + '(- 1 *)--version[show version and exit]' \ + '(- 1 *)'{-h,--help}'[show help options]' \ + '(- 1 *)'{--hi,--help-ini}'[show help about ini-names]' \ + '*'{-v,--verbose}'[increase verbosity of reporting output]' \ + '*-q[progressively silence reporting output]' \ + '(- 1 *)--showconfig[show configuration information for all environments]' \ + '(- 1 *)'{-l,--listenvs}'[show list of test environments]' \ + '(- 1 *)'{-a,--listenvs-all}'[show list of all defined environments]' \ + '-c[config file name or directory with "tox.ini" file]:config path:_files -g "*.ini"' \ + '-e[work against specified environments]: :_tox_envs_list' \ + "--devenv[sets up a development environment at ENVDIR based on the env's tox configuration specified by '-e' ]: :" \ + '--notest[skip invoking test commands]' \ + '--sdistonly[only perform the sdist packaging activity]' \ + '--skip-pkg-install[skip package installation for this run]' \ + '(-p --parallel)'{-p,--parallel}'[run tox environments in parallel]: :' \ + '(-o --parallel-live)'{-o,--parallel-live}'[connect to stdout while running environments]' \ + '--parallel--safe-build[ensure two tox builds can run in parallel]' \ + '--installpkg[ensure two tox builds can run in parallel]:package path:_files -/' \ + '--develop[install package in the venv using "setup.py develop"]' \ + '(-i --index-url)'{-i,--index-url}'[set indexserver url]:index server URL:_urls' \ + '--pre[install pre-releases and development versions of dependencies]' \ + '(-r --recreate)'{-r,--recreate}'[force recreation of virtual environments]' \ + '--result-json[write a json file with detailed information about all commands and results involved]:JSON file path:_files -g "*.json"' \ + '--discover[for python discovery first try the python executables under these paths]:' \ + '--hashseed[set PYTHONHASHSEED to SEED before running commands]:seed' \ + '*--force-dep[forces a certain version of one of the dependencies when configuring the virtual environment]:pip requirement' \ + '--sitepackages[override sitepackages setting to True in all envs]' \ + '--alwayscopy[override alwayscopy setting to True in all envs]' \ + '--no-provision[do not perform provision, but fail and if a path was provided write provision metadata as JSON to it]:JSON file path:_files -g "*.json"' \ + '(-s --skip-missing-interpreters)'{-s,--skip-missing-interpreters}'[do not fail tests for missing interpreters]: :(config true false)' \ + '--workdir[tox working directory]: :_files -/' \ + '*: :_guard "^-*" command positional substitution arguments' + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ts-node b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ts-node new file mode 100644 index 00000000..12919227 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ts-node @@ -0,0 +1,77 @@ +#compdef ts-node +# ------------------------------------------------------------------------------ +# Copyright (c) 2023 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for ts-node v10.9.1. (https://github.com/TypeStrong/ts-node) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_arguments \ + '(- *)'{-h,--help}'[Print help message]' \ + '(- *)'{-v,--version}'[Print module version information]' \ + '(- *)-vvv[Print additional version information]' \ + '(-e --eval)'{-e,--eval}'[Evaluate code]:code' \ + '(-p --print)'{-p,--print}'[Print result of "--eval"]' \ + '*'{-r,--require}'[Require a node module before execution]:path:_files' \ + '--esm[Bootstrap with the ESM loader, enabling full ESM support]' \ + '--swc[Use the faster swc transpiler]' \ + '(- *)--showConfig[Print resolved configuration and exit]' \ + '(-T --transpileOnly)'{-T,--transpileOnly}"[Use TypeScript's faster 'transpileModule' or a third-party transpiler]" \ + '(-H --compilerHost)'{-H,--compilerHost}"[Use TypeScript's compiler host API]" \ + '*'{-I,--ignore}'[Override the path patterns to skip compilation]:pattern' \ + '(-P --project)'{-P,--project}'[Path to TypeScript JSON project file]:path:_files' \ + '(-C --compiler)'{-C,--compiler}'[Specify a custom TypeScript compiler]:compiler:_files' \ + '--transpiler[Specify a third-party, non-typechecking transpiler]' \ + '*'{-D,--ignoreDiagnostics}'[Ignore TypeScript warnings by diagnostic code]:code' \ + '*'{-O,--compilerOptions}'[JSON object to merge with compiler options]:option' \ + '--cwd[Behave as if invoked within this working directory]:dir:_files -/' \ + '--files[Load "files", "include", and "exclude" from "tsconfig.json" on startup]' \ + '--pretty[Use pretty diagnostic formatter]' \ + '--cwdMode[Use current directory instead of script,ts for config resolution]' \ + '--skipProject[Skip reading "tsconfig.json"]' \ + '--skipIgnore[Skip "--ignore" checks]' \ + '--emit[Emit output files into ".ts-node" directory]' \ + '--scope[Scope compiler to files within "scopeDir"]' \ + '--scopeDir[Directory for "--scope"]:dir:_files -/' \ + '--preferTsExts[Prefer importing TypeScript files over JavaScript files]' \ + '--logError[Logs TypeScript errors to stderr instead of throwing exceptions]' \ + '--noExperimentalReplAwait[Disable top-level await in REPL]' \ + "--experimentalSpecifierResolution[Like node's --experimental-specifier-resolution]: :(node explicit)" \ + '*:: :_files' \ + && return 0 + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_tsc b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_tsc new file mode 100644 index 00000000..0c28c241 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_tsc @@ -0,0 +1,61 @@ +#compdef tsc +# ------------------------------------------------------------------------------ +# Copyright (c) 2023 Github zsh-users - https://github.com/zsh-users +# +# 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. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for tsc v5.0.4. (https://www.typescriptlang.org/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Shohei Yoshida (https://github.com/syohex) +# +# ------------------------------------------------------------------------------ + +_arguments \ + '(- *)'{-h,--help}'[Print help message]' \ + '(- *)--all[Show all compiler options]' \ + '(-b --build)'{-b,--build}'[Build one or more projects and their dependencies if out of date]' \ + '--init[Initializes a TypeScript project and creates a tsconfig.json file]' \ + '--listFilesOnly[Print names of files that are part of the compilation and then stop processing]' \ + '--locale[Set the language of the messaging from TypeScript]:locale ' \ + '(-p --project)'{-p,--project}'[Compile the project given the path to its configuration file]:config:_files' \ + '--showConfig[Print the final configuration instead of building]' \ + '(- *)'{-v,--version}"[Print the compiler's version]" \ + '(-w --watch)'{-w,--watch}'[Watch input files]' \ + '(-v --verbose)'{-v,--verbose}'[Enable verbose logging]' \ + '(-d --dry)'{-d,--dry}'[Show what would be built]' \ + '(-f --force)'{-f,--force}'[Build all projects, including those that appear to be up to date]' \ + '--clean[Delete the outputs of all projects]' \ + '*:: :_files' \ + && return 0 + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_udisksctl b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_udisksctl new file mode 100644 index 00000000..00584494 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_udisksctl @@ -0,0 +1,176 @@ +#compdef udisksctl +# +# ------------------------------------------------------------------------------ +# The MIT License +# +# Copyright 2014 Damir Jelić +# +# 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. +# +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for udisksctl (https://github.com/storaged-project/udisks) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Damir Jelić [1] +# * Ole Jørgen Brønner (minor additions) +# +# [1] https://lists.freedesktop.org/archives/devkit-devel/2014-February/001554.html +# +# ------------------------------------------------------------------------------ +# Notes +# ----- +# +# udisksctl actually provide built-in support for completion: It accepts an +# special command 'complete' that returns completions. That is what drives the +# upstream bash completion. In the future one might consider rewriting using +# that. (but not sure how straight forward it would be to provide descriptions?) +# +# ------------------------------------------------------------------------------ + +(( $+functions[_udisksctl_paths] )) || +_udisksctl_paths() { + local -a _path_list + + for _path in $(_call_program paths "udisksctl complete \"udisksctl $words\" $CURSOR" | sed 's/:/\\:/g'); do + _path_list+=$_path + done + + _describe 'path' _path_list +} + +(( $+functions[_udisksctl_filesystems] )) || +_udisksctl_filesystems() { + local -a _fs_types=( + 'adfs' 'affs' 'autofs' 'btrfs' 'ceph' 'cifs' 'coda' 'coherent' 'cramfs' + 'debugfs' 'devpts' 'efs' 'exfat' 'ext' 'ext2' 'ext3' 'ext4' 'hfs' 'hfsplus' + 'hpfs' 'iso9660' 'jfs' 'minix' 'msdos' 'ncpfs' 'nfs' 'nfs4' 'ntfs' 'proc' + 'qnx4' 'ramfs' 'reiserfs' 'romfs' 'squashfs' 'smbfs' 'sysv' 'tmpfs' 'ubifs' + 'udf' 'ufs' 'umsdos' 'usbfs' 'vfat' 'xenix' 'xfs' 'xiafs' + ) + + _describe 'file system type' _fs_types +} + +_udisksctl() { + typeset -A opt_args + local curcontext="$curcontext" state line ret=1 + + _arguments -C \ + '1:udisksctl commands:->cmds' \ + '*:: :->cmd_args' && ret=0 + + case $state in + cmds) + local commands; commands=( + 'help:show help' + 'info:show info about an object' + 'dump:show info about all object' + 'status:shows high-level status' + 'monitor:monitor changes to objects' + 'mount:mount a filesystem' + 'unmount:unmount a filesystem' + 'unlock:unlock an encrypted device' + 'lock:lock an encrypted device' + 'loop-setup:set-up a loop device' + 'loop-delete:delete a loop device' + 'power-off:safely power off a drive' + 'smart-simulate:set SMART data for a drive' + ) + _describe -t commands 'udisksctl command' commands && ret=0 + ;; + + cmd_args) + case $words[1] in + info) + _arguments \ + {-p,--object-path}'[specify object to get information about]:object path:_udisksctl_paths' \ + {-b,--block-device}'[specify block device to get information about]:block device:_udisksctl_paths' \ + {-d,--drive}'[specify drive to get information about]:drive:_udisksctl_paths' && ret=0 + ;; + mount) + _arguments \ + {-p,--object-path}'[specify object to mount]:object path:_udisksctl_paths' \ + {-b,--block-device}'[specify block device to mount]:block device:_udisksctl_paths' \ + {-t,--filesystem-type}'[specify filesystem type to use]:fs type:_udisksctl_filesystems' \ + {-o,--options}'[mount options]' \ + "(--no-user-interaction)--no-user-interaction[don't authenticate the user if needed]" && ret=0 + ;; + unmount) + _arguments \ + {-p,--object-path}'[object to unmount]:object path:_udisksctl_paths' \ + {-b,--block-device}'[block device to unmount]:block device:_udisksctl_paths' \ + {-f,--force}'[force/lazy unmount]' \ + "(--no-user-interaction)--no-user-interaction[don't authenticate the user if needed]" && ret=0 + ;; + unlock|lock) + _arguments \ + {-p,--object-path}'[object to lock/unlock]:object path:_udisksctl_paths' \ + {-b,--block-device}'[block device to lock/unlock]:block device:_udisksctl_paths' \ + "(--no-user-interaction)--no-user-interaction[don't authenticate the user if needed]" && ret=0 + ;; + loop-setup) + _arguments \ + {-f,--file}'[specify file to set-up a loop device for]:files:_files' \ + {-r,--read-only}'[setup read-only device]' \ + {-o,--offset}'[start at specified offset into file]:offset (bytes)' \ + {-s,--size}'[limit size]:limit (bytes)' \ + "(--no-user-interaction)--no-user-interaction[don't authenticate the user if needed]" && ret=0 + ;; + loop-delete) + _arguments \ + {-p,--object-path}'[object for loop device to delete]:object path:_udisksctl_paths' \ + {-b,--block-device}'[loop device to delete]:block device:_udisksctl_paths' \ + "(--no-user-interaction)--no-user-interaction[don't authenticate the user if needed]" && ret=0 + ;; + power-off) + _arguments \ + {-p,--object-path}'[object path for ATA device]:object path:_udisksctl_paths' \ + {-b,--block-device}'[device file for ATA device]:block device:_udisksctl_paths' \ + "(--no-user-interaction)--no-user-interaction[don't authenticate the user if needed]" && ret=0 + ;; + smart-simulate) + _arguments \ + {-f,--file}'[file with libatasmart blob]:files:_files' \ + {-p,--object-path}'[object to get information about]:object path:_udisksctl_paths' \ + {-b,--block-device}'[block device to get information about]:block device:_udisksctl_paths' \ + "(--no-user-interaction)--no-user-interaction[don't authenticate the user if needed]" && ret=0 + ;; + esac + ;; + esac + + return ret +} + +_udisksctl "$@" + + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ufw b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ufw new file mode 100644 index 00000000..238ff1a7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_ufw @@ -0,0 +1,145 @@ +#compdef ufw +# ------------------------------------------------------------------------------ +# Copyright (c) 2016 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for The Uncomplicated Firewall (ufw). (https://launchpad.net/ufw). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Jindřich Pilař (https://github.com/JindrichPilar) +# +# ------------------------------------------------------------------------------ + + +_ufw_logging() { + + local params additional second + second=$words[2] + + if [ ! -z $second ]; then + return + fi + + params=( + "on" + "off" + ) + + additional=( + "low" + "medium" + "high" + "full" + ) + + _describe -t params 'on/off' params + _describe -t additional 'level' additional +} + + +_ufw_delete() { + local rules complrules second + + second=$words[2] + + if [ ! -z $second ]; then + return + fi + + complrules=() + rules=("${(f)$(ufw status | tr -s ' ' | tail -n +5 | tr -s '\n')}") + + for ((i=1; i<=${#rules[@]}; i++)); do + complrules+=("$i:$rules[i]"); + done + + _describe -t complrules 'Rules' complrules +} + +_ufw() { + local curcontext="$curcontext" ret=1 + local -a state line commands + + commands=( + "enable:enable the firewall" + "disable:disable the firewall" + "default:set default policy" + "logging:set logging level" + "allow:add allow rule" + "deny:add deny rule" + "reject:add reject rule" + "limit:add limit rule" + "delete:delete rule" + "insert:insert rule at position" + "route:add route rule" + "reload:reload firewall" + "reset:reset firewall" + "status:show firewall status" + "show:show firewall report" + "version:display version information" + "prepend:add rule before all of the same type" + ) + + _arguments -C -s -S -n \ + '(- 1 *)'--version"[display version information]: :->full" \ + '(- 1 *)'{-h,--help}'[display usage information]: :->full' \ + '(- 1 *)'--dry-run"[don't modify anything, just show the changes]: :->cmds" \ + '1:cmd:->cmds' \ + '*:: :->args' && ret=0 + + case "$state" in + (cmds) + _describe -t commands 'commands' commands + ;; + (args) + local cmd + cmd=$words[1] + case "$cmd" in + (logging) + _ufw_logging && ret=0 + ;; + (delete) + _ufw_delete && ret=0 + ;; + (*) + _default && ret=0 + ;; + esac + ;; + (*) + ;; + esac + + return ret +} + +_ufw + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_virtualbox b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_virtualbox new file mode 100644 index 00000000..655b1598 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_virtualbox @@ -0,0 +1,1618 @@ +#compdef VBoxManage=vboxmanage VBoxHeadless=vboxheadless vboxmanage=vboxmanage vboxheadless=vboxheadless +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for VirtualBox (https://www.virtualbox.org/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Massimiliano Torromeo +# * Julien Nicoulaud +# * Shohei YOSHIDA +# +# ------------------------------------------------------------------------------ + +_virtualbox() { + local ret=1 + _call_function ret _$service + return ret +} + +(( $+functions[_vboxmanage] )) || +_vboxmanage() { + local context state line expl + local -A opt_args + local ret=1 + + _arguments -C \ + '1: :_vboxmanage_commands' \ + '*:: :->subcmds' \ + && ret=0 + + case $state in + (subcmds) + case "$words[1]" in + (list) + _arguments \ + '--long[Show detailed information about each information]' \ + '--sorted[Sorts the list of information entries alphabetically]' \ + '1: :_vboxmanage_list_args' \ + && ret=0 + ;; + (showvminfo) + _arguments \ + '--details[Includes detailed information about the VM]' \ + '--machinereadable[Specifies that the VM information be in a machine-readable format]' \ + '--password-id[Specifies password id of the VM if it is encrypted]:id' \ + '--password[Specifies password of the VM if it is encrypted]: :_files' \ + '--log=[Specifies a numerical index that identifies the log file]:id' \ + '1:machine:_vboxmachines' \ + && ret=0 + ;; + (registervm) + _arguments \ + '--password[Use the --password to supply the encryption password of the VM]: :_files' \ + '1: :_files' \ + && ret=0 + ;; + (unregistervm) + _arguments \ + '--delete[Deletes the following files related to the VM automatically]' \ + '1:machine:_vboxmachines' \ + && ret=0 + ;; + (createvm) + _arguments \ + '--name[Specifies a new name for the new VM]:name' \ + '--basefolder=[Specifies the name of the folder in which to save the machine configuration file for the new VM]: :_files -/' \ + '--default[Applies a default hardware configuration for the specified guest OS]' \ + '--group=[Assigns the VM to the specified groups]:group_id' \ + '--ostype=[Specifies the guest OS to run in the VM]: :_vboxostypes' \ + '--register[Registers the VM with your Oracle VM VirtualBox installation]' \ + '--uuid=[Specifies the Universally Unique Identifier(UUID) of the VM]:uuid' \ + '--ciper=[Specifies the cipher to use for encryption]: :(AES-128 AES-256)' \ + '--password-id=[Specifies a new password identifier]:password_id' \ + '--password=[Use the --password to supply the encryption password of the VM]: :_files' \ + && ret=0 + ;; + (clonevm) + _arguments \ + '--basefolder=[Specifies the name of the folder in which to save the configuration for the new VM]: :_files -/' \ + '--groups=[Assigns the clone to the specified group or groups]:group' \ + '--mode=[Specifies which of the following cloning modes to use]: :(machine machineandchildren all)' \ + '--name=[Specifies a new name for the new VM]:name' \ + '--options=[Specifies how to create the new clone]' \ + '--register[Automatically registers the new clone in this Oracle VM VirtualBox installation]' \ + '--snapshot=[Specifies the snapshot on which to base the new VM]:name' \ + '--uuid=[Specifies the UUID for the new VM]:uuid' \ + '1:machine:_vboxmachines' \ + && ret=0 + ;; + (movevm) + _arguments \ + '--type=[Specifies the type of the move operation]: :(basic)' \ + '--folder=[Specifies a full path name or relative path name of the new location on the host file system]: :_files -/' \ + '1:machine:_vboxmachines' \ + && ret=0 + ;; + (encryptvm) + _vboxmanage_encryptvm && ret=0 + ;; + (cloud) + _vboxmanage_cloud && ret=0 + ;; + (cloudprofile) + _vboxmanage_cloudprofile && ret=0 + ;; + (import) + _arguments \ + '--dry-run[Performs a dry run of the VBoxManage import command]' \ + '--options=[Enables you to fine tune the import operation]: :(keepallmacs keepnatmacs importtovdi)' \ + '--ostype=[Specifies the guest operating system (OS) information for the VM]: :_vboxostypes' \ + '--vmname=[Specifies the name of the VM to be used by Oracle VM VirtualBox]:name' \ + '--basefolder=[Specifies the folder where the files of the imported VM are stored]: :_files -/' \ + '--memory=[Specifies the memory size in Megabytes for the imported VM]:memory' \ + '--cpus=[Specifies the number of CPUs for the imported VM]:cpus' \ + '--description=[Specifies the description text]:desc' \ + '--vsys=[Specifies the index selecting a specific VM within the appliance]:index' \ + '--unit=[Specifies the index selecting a specific unit of a VM within the appliance]:index' \ + '--settingsfile=[Specifies the name of the VM config file]: :_files' \ + '--group=[Specifies the primary group of the imported VM]:group' \ + '--eula=[Enables you to show or accept the license conditions]: :(show accept)' \ + '--ignore[Ignores the current unit of an imported VM]' \ + '--scsitype=[Enables you to select the type of the SCSI controller]: :(BusLogic LsiLogic)' \ + '--cloud[Specifies that the import should be from the cloud]' \ + '--cloudprofile=[Specifies the cloud profile]:profile' \ + '--cloudinstanceid=[Specifies the ID of an existing instance in the cloud]:id' \ + '--cloudbucket=[Specifies the bucket name in which to store the object created]:bucket' \ + '1:ovf file:_files -g \*.{ovf,ova}' \ + && ret=0 + ;; + (signova) + _arguments \ + '--certificate=[File containing the certificate that the OVA should be signed with]: :_files' \ + '--private-key=[The file containing the private key]: :_files' \ + '--private-key-password-file=[File containing the private key password]: :_files' \ + '--digest-type=[Select the cryptographic digest algorithm to use in the signing]: :(SHA-256 SHA-512 SHA-1)' \ + '(--pkcs7 --no-pkcs7)--pkcs7[Enables the creation of an additional PKCS#7/CMS signature]' \ + '(--pkcs7 --no-pkcs7)--no-pkcs7[Disables the creation of an additional PKCS#7/CMS signature]' \ + '--intermediate-cert=[File containing an intermediary certificate]: :_files' \ + '--force[Overwrite existing signature if present]' \ + '--dry-run[Do not actually modify the OVA, just test-run the signing operation]' \ + '(--verbose --quiet)--verbose[Verbose the command execution]' \ + '(--verbose --quiet)--quiet[Quiet the command execution]' \ + '1:ova' \ + && ret=0 + ;; + (startvm) + _arguments \ + '*--putenv=[Assigns a value to an environment variable as a name-value pair]:value' \ + '--type=[Specifies the frontend used to start the VM]: :(gui headless sdl separate)' \ + '--password[Use the --password to supply the encryption password]: :_files' \ + '--password-id=[Use the --password-id option to specify the id]:id' \ + '1:machine:_vboxmachines' \ + && ret=0 + ;; + (unattended) + _vboxmanage_unattended + ;; + (adoptstate) + _arguments \ + '1:machine:_vboxmachines' \ + '*:sav file:_files -g "*.sav"' \ + && ret=0 + ;; + (snapshot) + _vboxmanage_snapshot + ;; + (closemedium) + _arguments \ + '--delete[Deletes the image file]' \ + '1:type:(disk dvd floppy)' \ + '2:file:_files' \ + && ret=0 + ;; + (storageattach) + _arguments \ + '--storagectl=[Specifies the name of the storage controller]:name' \ + '--port=[Specifies the port number of the storage controller to modify]:port' \ + "--device=[Specifies the port's device number to modify]:num" \ + '--type=[Specifies the drive type to which the medium is associated]: :(dvddrive fdd hdd)' \ + '--medium=[Specifies media]:media' \ + '--mtype=[Specifies how this medium behaves]: :(normal writethrough immutable shareable readonly multiattach)' \ + '--comment=[Specifies an optional description to store with the medium]:text' \ + '--setuuid=[Modifies the UUID of a medium before attaching it to a VM]:uuid' \ + '--setparentuuid=[Modifies the parent UUID of a medium before attaching it to a VM]:uuid' \ + '--passthrough=[For a virtual DVD drive only]: :(on off)' \ + '--tempeject=[For a virtual DVD drive only]: :(on off)' \ + '--nonrotational=[Enables you to specify that the virtual hard disk is non-rotational]: :(on off)'\ + '--discard=[Specifies whether to enable the auto-discard feature for a virtual hard disk]: :(on off)' \ + '--bandwidthgroup=[Specifies the bandwidth group to use for the device]:name' \ + '--forceunmount[For a virtual DVD or floppy drive only]' \ + '--server=[Specifies the host name or IP address of the iSCSI target]:addr' \ + '--target=[Specifies the target name string]:name' \ + '--tport=[Specifies the TCP/IP port number of the iSCSI service on the target]:port' \ + '--lun=[Specifies the logical unit number (LUN) of the target resource]:lun' \ + '--encodedlun=[Specifies the hexadecimal-encoded of the target resource]:lun' \ + '--username=[Specifies the user name to use for target authentication]:name' \ + '--password=[Specifies the password used for target authentication]:password' \ + '--passwordfile=[Specifies a file that contains the target authentication password as clear text]: :_files' \ + '--iniitator=[Specifies the iSCSI initiator]:initiator' \ + '--intnet[Specifies whether to connect to the iSCSI target that uses internal networking]' \ + '1:machine:_vboxmachines' \ + && ret=0 + ;; + (storagectl) + _arguments \ + '--name=[Specifies the name of the storage controller]:name' \ + '--add=[Specifies the type of the system bus]: :(floppy ide pcie sas sata scsi usb)' \ + '--controller=[Specifies the chipset type]: :(BusLogic I82078 ICH6 IntelAHCI LSILogic LSILogicSAS NVMe PIIX3 PIIX4 USB)' \ + '--portcount=[Specifies the number of ports that the storage controller supports]:count' \ + '--hostiocache=[Specifies whether to use the host I/O cache]: :(on off)' \ + '--bootable=[Specifies whether this controller is bootable]: :(on off)' \ + '--rename=[Specifies a new name for the storage controller]:name' \ + '--remove[Removes a storage controller from the VM configuration]' \ + '1:machine:_vboxmachines' \ + && ret=0 + ;; + (bandwidthctl) + _vboxmanage_bandwidthctl + ;; + (showmediuminfo) + _arguments \ + '1:medium:(disk dvd floppy)' \ + '2: :_files' \ + && ret=0 + ;; + (createmedium) + _arguments \ + '--filename=[Specifies the absolute path name to a file on the host file system]: :_files'\ + '--size=[Specifies the image capacity in one megabyte units]:size' \ + '--sizebyte=[Specifies the image capacity in one byte units]:size' \ + '--diffparent=[Specifies the UUID or absolute path name of parent file]:uuid_or_file' \ + '--format=[Specifies the file format of the output file]: :(VDI VMDK VHD)' \ + '--variant[Specifies the file format variant for the target medium]:variant' \ + '*--property=[Specifies any required file format dependent parameters in key=value form]:value' \ + '--property-file=[Specifies any propertyrequired file]: :_files' \ + '1:medium:(disk dvd floppy)' \ + && ret=0 + ;; + (modifymedium) + _arguments \ + '--autoreset=[Specifies whether to automatically reset]: :(on off)' \ + '--compact[Compresses disk images by removing blocks that contain only zeroes]' \ + '--description=[Specifies a text description of the medium]:desc' \ + '--move=[Specifies a relative or absolute path to a medium on the host system]: :_files' \ + '*--property=[Specifies any required file format dependent parameters in key=value form]:value' \ + '--resize=[Specifies the new capacity of an existing image in MB]:size' \ + '--resizebyte=[Specifies the new capacity of an existing image in bytes]:size' \ + '--setlocation=[Specifies the new location of the medium]: :_files' \ + '--type=[Specifies the new mode type of an existing image]: :(normal immutable writethrough multi-attach shareable readonly)' \ + '1:medium:(disk dvd floppy)' \ + '2: :_files' \ + && ret=0 + ;; + (clonemedium) + _arguments \ + '--existing[Performs the clone operation by overwriting an existing target medium]' \ + '--format=[Specifies the file format of the target medium]: :(VDI VMDK VHD RAW)' \ + '--variant=[Specifies the file format variant for the target medium]:variant' \ + '1:medium:(disk dvd floppy)' \ + '2: :_files' \ + '3: :_files' \ + && ret=0 + ;; + (encryptmedium) + _arguments \ + '--newpassword=[Specifies the new encryption password]:password' \ + '--oldpassword=[Specifies the original encryption password]:password' \ + '--cipher=[Specifies the cipher to use for encryption]: :(AES-XTS128-PLAIN64 AES-XTS256-PLAIN64)' \ + '--newpasswordid=[Specifies a new password identifier]:password' \ + '1: :_files' \ + && ret=0 + ;; + (convertfromraw) + _arguments \ + '--format=[Specifies the format of the disk image to create]: :(VDI VMDK VHD)' \ + '--uuid=[Specifies the Universally Unique Identifier (UUID) of the output file]:uuid' \ + '--variant=[Specifies any required file format variants for the output file]:variant' \ + '*: :_files' \ + && ret=0 + ;; + (mediumio) + _vboxmanage_mediumio && ret=0 + ;; + (setproperty) + _arguments \ + '1: :(autostartdbpath defaultfrontend hwvirtexclusive launguage logginglevel loghistorycount machinefolder proxymode proxyurl vrdeauthlibrary vrdeextpack websrvauthlibrary)' \ + '2:value:_vboxmanage_setproperty_value' \ + && ret=0 + ;; + (usbfilter) + _vboxmanage_usbfilter && ret=0 + ;; + (sharedfolder) + _vboxmanage_sharedfolder && ret=0 + ;; + (guestproperty) + _vboxmanage_guestproperty && ret=0 + ;; + (guestcontrol) + _vboxmanage_guestcontrol && ret=0 + ;; + (debugvm) + _vboxmanage_debugvm && ret=0 + ;; + (metrics) + _vboxmanage_metrics && ret=0 + ;; + (natnetwork) + _vboxmanage_natnetwork && ret=0 + ;; + (hostonlyif) + _vboxmanage_hostonlyif && ret=0 + ;; + (hostonlynet) + _vboxmanage_hostonlynet && ret=0 + ;; + (dhcpserver) + _vboxmanage_dhcpserver && ret=0 + ;; + (usbdevsource) + _vboxmanage_usbdevsource && ret=0 + ;; + (extpack) + _vboxmanage_expack && ret=0 + ;; + (updatecheck) + _vboxmanage_updatecheck && ret=0 + ;; + (modifynvram) + _vboxmanage_modifynvram && ret=0 + ;; + (discardstate|getextradata|setextradata) + _arguments \ + '1:machine:_vboxmachines' \ + && ret=0 + ;; + (modifyvm|export) + local -a command_options=(${(@f)"$(vboxmanage $words[1] | perl -wln -e 'm{(--[a-zA-Z_-]+) [^]|]+} and print qq{$1:arg}')"}) + _arguments \ + $command_options \ + ':machine:_vboxmachines' + ;; + (controlvm) + local -a subcommands=(${(@f)"$(vboxmanage $words[1] | perl -wln -e 'm{^\s+([a-z][a-z-]+)} and print $1')"}) + _arguments \ + '1:commands:'"($subcommands)" \ + ':machine:_vboxmachines' + ;; + esac + ;; + esac + + return 0 +} + +(( $+functions[_vboxmanage_commands] )) || +_vboxmanage_commands() { + local -a commands=( + "list:gives information about VirtualBox's current settings" + 'showvminfo:shows information about a particular virtual machine' + 'registervm:import a virtual machine definition in an XML file into VirtualBox' + 'unregistervm:unregisters a virtual machine' + 'createvm:creates a new XML virtual machine definition file' + 'modifyvm:changes the properties of a registered virtual machine which is not running' + 'clonevm:Create a clone of an existing virtual machine' + 'movevm:Move a virtual machine to a new location on the host system' + 'encryptvm:Change encryption and passwords of the VM' + 'cloud:Manage the cloud entities' + 'cloudprofile:Manage the cloud profiles' + 'import:imports a virtual appliance in OVF format by copying the virtual disk images and creating virtual machines in VirtualBox' + 'export:exports one or more virtual machines from VirtualBox into a virtual appliance in OVF format' + 'signova:Digitally sign an OVA' + 'startvm:starts a virtual machine that is currently in the "Powered off" or "Saved" states' + 'controlvm:change the state of a virtual machine that is currently running' + 'unattended:Unattended guest OS installation' + 'discardstate:discards the saved state of a virtual machine which is not currently running' + 'adoptstate:adopt a saved state file (.sav)' + 'snapshot:control snapshots' + 'closemedium:removes a hard disk, DVD or floppy image from a VirtualBox media registry' + 'storageattach:attaches/modifies/removes a storage medium connected to a storage controller' + 'storagectl:attaches/modifies/removes a storage controller' + 'bandwidthctl:creates/deletes/modifies bandwidth groups' + 'showmediuminfo:shows information about a virtual hard disk image' + 'createmedium:creates a new virtual hard disk image' + 'modifymedium:change the characteristics of a disk image after it has been created' + 'clonemedium:duplicates a registered virtual hard disk image to a new image file with a new unique identifier' + 'mediumproperty:Manage medium properties' + 'encryptmedium:Manage a DEK-encrypted medium or image' + 'checkmediumpwd:Check encryption password on a DEK-encrypted medium or a disk image' + 'convertfromraw:converts a raw disk image to a VirtualBox Disk Image (VDI) file' + 'mediumio:Medium content access' + 'getextradata:retrieve string data to a virtual machine or to a VirtualBox configuration' + 'setextradata:attach string data to a virtual machine or to a VirtualBox configuration' + 'setproperty:change global settings which affect the entire VirtualBox installation' + 'usbfilter:used for working with USB filters in virtual machines, or global filters' + 'sharedfolder:share folders on the host computer with guest operating systems' + 'guestproperty:get or set properties of a running virtual machine' + 'guestcontrol:control certain things inside a guest from the host' + 'debugvm:for experts who want to tinker with the exact details of virtual machine execution' + 'metrics:monitor the usage of system resources' + 'natnetwork:add,modify,remove or start NatNetworks' + 'hostonlyif:change the IP configuration of a host-only network interface' + 'hostonlynet:Host Only Network management' + 'dhcpserver:control the DHCP server that is built into VirtualBox' + 'usbdevsource:Add and remove USB device sources' + 'extpack:add or remove VirtualBox extension pacnks' + 'updatecheck:Checks for a new version of Virtualbox' + 'modifynvram:List and modify the NVRAM content of a virtual machine' + ) + + _describe -t subcommands 'subcommand' commands +} + +(( $+functions[_vboxmanage_encryptvm] )) || +_vboxmanage_encryptvm() { + local ret=1 + + _arguments -C \ + '1: :_vboxmachines' \ + '2: :(setencryption checkpassword addpassword removepassword)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + compset -n 2 + case $words[1] in + (setencryption) + _arguments \ + '--cipher[specify the new cipher for encryption of the VM]: :(AES-128 AES-256)' \ + '--new-password[specify the new password for encryption of the VM]: :_files' \ + '--new-password-id[specify the new ID for the password for encryption of the VM]:id' \ + '--force[make the system to reencrypt the VM instead of the simple changing the password]' \ + && ret=0 + ;; + (addpassword) + _arguments \ + '--new-password[specify the new password for encryption of the VM]: :_files' \ + '--new-password-id[specify the new ID for the password for encryption of the VM]:id' \ + && ret=0 + ;; + esac + esac + + return $ret +} + +(( $+functions[_vboxmanage_cloud] )) || +_vboxmanage_cloud() { + local ret=1 + + _arguments -C \ + '1: :(list instance image network)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + local subcommand=$words[1] + if (( $+functions[_vboxmanage_cloud_${subcommand}] )); then + _vboxmanage_cloud_${subcommand} && ret=0 + fi + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_cloud_list] )) || +_vboxmanage_cloud_list() { + local ret=1 + + _arguments -C \ + '1: :(instances images)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + local -a state + if [[ $words[1] == "instances" ]]; then + state=(running paused terminated) + else + state=(available disabled deleted) + fi + + _arguments \ + '--provider=[Short cloud provider name]:provider' \ + '--profile=[Cloud profile name]:profile' \ + '--state=[The state of cloud instance]: :'"($state)" \ + '--compartment-id[A compartment is the logical container used]' + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_cloud_instance] )) || +_vboxmanage_cloud_instance() { + local ret=1 + + _arguments -C \ + '1: :(create info termination start pause images)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (create) + _arguments \ + '--provider=[Short cloud provider name]:provider' \ + '--profile=[Cloud profile name]:profile' \ + '--domain-name=[Cloud domain where new instance is created]:name' \ + '--image-id=[Unique identifier which fully identifies a custom image in the Cloud]:id' \ + '--boot-volume-id=[Unique identifier which fully identifies a boot volume in the Cloud]:id' \ + '--display-name=[Name for new instance in the Cloud]:name' \ + '--shape=[The shape of instance, defines the number of CPUs and RAM memory]:shape' \ + '--subnet=[Unique identifier which fully identifies an existing subnet]:subnet' \ + '--boot-disk-size=[The size of bootable image in GB]:size' \ + '--publicip=[Whether the instance will have a public IP or not]: :(true false)' \ + '--privateip=[Private IP address for the created instance]:ip' \ + '--public-ssh-key=[Public SSH key used to connect to the instance via SSH]:key' \ + '--launch-mode=[launch mode]: :(EMULATED NATIVE PARAVIRTUALIZED)' \ + '--cloud-init-script-path=[Absolute path to the user cloud-init script]: :_files' \ + && ret=0 + ;; + (*) + _arguments \ + '--provider=[Short cloud provider name]:provider' \ + '--profile=[Cloud profile name]:profile' \ + '--id=[Unique identifier which fully identify the instance in the Cloud]:id' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_cloud_image] )) || +_vboxmanage_cloud_image() { + local ret=1 + + _arguments -C \ + '1: :(create info delete import export)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (create) + _arguments \ + '--provider=[Short cloud provider name]:provider' \ + '--profile=[Cloud profile name]:profile' \ + '--display-name=[Name for new image in the Cloud]:name' \ + '--bucket-name=[Cloud bucket name where an object is located]:name' \ + '--object-name=[Name of object in the bucket]:name' \ + '--instance-id=[Unique identifier which fully identifies the instance in the Cloud]:id' \ + && ret=0 + ;; + (import) + _arguments \ + '--provider=[Short cloud provider name]:provider' \ + '--profile=[Cloud profile name]:profile' \ + '--bucket-name=[Cloud bucket name where an object is located]:name' \ + '--object-name=[Name of object in the bucket]:name' \ + && ret=0 + ;; + (export) + _arguments \ + '--provider=[Short cloud provider name]:provider' \ + '--profile=[Cloud profile name]:profile' \ + '--display-name=[Name for new image in the Cloud]:name' \ + '--bucket-name=[Cloud bucket name where an object is located]:name' \ + '--object-name=[Name of object in the bucket]:name' \ + && ret=0 + ;; + (*) + _arguments \ + '--provider=[Short cloud provider name]:provider' \ + '--profile=[Cloud profile name]:profile' \ + '--id=[Unique identifier which fully identify the instance in the Cloud]:id' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_cloud_network] )) || +_vboxmanage_cloud_network() { + local ret=1 + + _arguments -C \ + '1: :(setup create update delete info)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (setup) + _arguments \ + '--provider=[Short cloud provider name]:provider' \ + '--profile=[Cloud profile name]:profile' \ + '--gateway-os-name=[The name of OS to use for a cloud gateway]:os_name' \ + '--gateway-os-version=[The version of OS to use for a cloud gateway]:version' \ + '--gateway-shape=[The instance shape to use for a cloud gateway]:shape' \ + '--tunnel-network-name=[The name of VCN/subnet to use for tunneling]:name' \ + '--tunnel-network-range=[The IP address range to use for tunneling]:range' \ + '--proxy=[The proxy URL to be used in local gateway installation]:proxy' \ + '--compartment-id=[The compartment to create the tunnel network in]:id' \ + && ret=0 + ;; + (create|update) + _arguments \ + '--provider=[Short cloud provider name]:provider' \ + '--profile=[Cloud profile name]:profile' \ + '--name=[The name of an existing cloud network descriptor]:name' \ + '--network-id=[The unique identifier of an existing subnet in the cloud]:id' \ + '(--enable --disable)--enable[Enable the network descriptor]' \ + '(--enable --disable)--disable[Disable the network descriptor]' \ + && ret=0 + ;; + (delete|info) + _arguments \ + '--provider=[Short cloud provider name]:provider' \ + '--profile=[Cloud profile name]:profile' \ + '--name=[The name of an existing cloud network descriptor]:name' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_cloudprofile] )) || +_vboxmanage_cloudprofile() { + local ret=1 + + _arguments -C \ + '1: :(add update delete show)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (add|update) + _arguments \ + '--provider=[Short cloud provider name]:provider' \ + '--profile=[Cloud profile name]:profile' \ + '--clouduser=[The name which fully identifies the user in the specified cloud provider]:user' \ + '--fingerprint=[Fingerprint for the key pair being used]:finger_print' \ + '--keyfile=[Full path and filename of the private key]: :_files' \ + '--passphrase=[Passphrase used for the key, if it is encrypted]:pass' \ + '--tenancy=[ID of your tenancy]:tenancy' \ + '--compartment=[ID of your compartment]:compartment' \ + '--region=[region name]:region' && ret=0 + ;; + (*) + _arguments \ + '--provider=[Short cloud provider name]:provider' \ + '--profile=[Cloud profile name]:profile' + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_unattended] )) || +_vboxmanage_unattended() { + local ret=1 + + _arguments -C \ + '1: :(detect install)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (detect) + _arguments \ + '--iso=[The installation ISO to run the detection on]: :_files' \ + '--machine-readable[Produce output that is simpler to parse from a script]' \ + && ret=0 + ;; + (install) + _arguments \ + '--iso=[The installation ISO to run the detection on]: :_files' \ + '--user=[The login name]:user' \ + '--password=[The login password]:password' \ + '--full-user-name=[The full user name]:full_name' \ + '--key=[The guest OS product key]:key' \ + '--install-additions[Install the VirtualBox guest additions]' \ + '--additions-iso=[Path to the VirtualBox guest additions ISO]: :_files' \ + '--install-txs[Whether to install the test execution service from the VirtualBox ValidationKit]' \ + '--validation-kit-iso=[Path to the VirtualBox ValidationKit ISO]: :_files' \ + '--locale=[The base locale specification for the guest]:locale' \ + '--country=[The two letter country code]:country' \ + '--time-zone=[The time zone to set up the guest OS with]:timezone' \ + '--hostname=[The fully qualified domain name of the guest machine]:hostname' \ + '--package-selection-adjustment=[Adjustments to the guest OS packages/components selection]:adjustment' \ + '--dry-run[Do not create any files or make any changes to the VM configuration]' \ + '--start-vm=[Start the VM using the front end given by session-type]:session_type' \ + '--auxiliary-base-path=[The path prefix to the media related files generated for the installation]: :_files' \ + '--image-index=[Windows installation image index]:index' \ + '--script-template=[The unattended installation script template]: :_files' \ + '--post-install-template=[The post installation script template]: :_files' \ + '--post-install-command=[A single command to run after the installation is completed]:command' \ + '--extra-install-kernel-parameter=[List of extra linux kernel parameters to use during the installation]:param' \ + '--language=[Specifies the UI language for a Windows installation]:language' \ + '1:machine:_vboxmachines' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_snapshot] )) || +_vboxmanage_snapshot() { + local ret=1 + + _arguments -C \ + '1: :_vboxmachines' \ + '2: :(take delete restore restorecurrent edit list showvminfo)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + compset -n 2 + case $words[1] in + (take) + _arguments \ + '--description=[Specifies a description of the snapshot]:description' \ + '--live[Specifies that the VM is not stopped while you create the snapshot]' \ + '--uniquename=[unique name]' \ + && ret=0 + ;; + (edit) + _arguments \ + '--current[Specifies that you update the current version of the snapshot]' \ + '--description=[Specifies a new description for the snapshot]:description' \ + '--name=[Specifies a new name for the snapshot]:name' \ + && ret=0 + ;; + (list) + _arguments \ + '--details[Specifies that the output shows detailed information about the snapshot]' \ + '--machinereadable[Specifies that the output is shown in a machine-readable format]' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_bandwidthctl] )) || +_vboxmanage_bandwidthctl() { + local ret=1 + + _arguments -C \ + '1: :_vboxmachines' \ + '2: :(add list remove set)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + compset -n 2 + case $words[1] in + (add) + _arguments \ + '--limit=[Specifies the bandwidth limit for a bandwidth group]:limit' \ + '--type=[Specifies the type of the bandwidth group]: :(disk network)' \ + && ret=0 + ;; + (list) + _arguments \ + '--machinereadable[Outputs the information about the bandwidth groups in name-value pairs]' \ + && ret=0 + ;; + (set) + _arguments \ + '--limit=[Specifies the bandwidth limit for a bandwidth group]:limit' \ + && ret=0 + ;; + (*) + _arguments '*: :_files' && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_mediumio] )) || +_vboxmanage_mediumio() { + local ret=1 + + _arguments -C \ + '1: :(formatfat cat stream)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (formatfat) + _arguments \ + '--disk=[Either the UUID or filename of a harddisk image]: :_files' \ + '--dvd=[Either the UUID or filename of a DVD image]: :_files' \ + '--floppy=[Either the UUID or filename of a floppy image]: :_files' \ + '--password-file=[The name of a file containing the medium encryption password]: :_files' \ + '--quick[Quickformat the medium]' \ + && ret=0 + ;; + (cat) + _arguments \ + '--disk=[Either the UUID or filename of a harddisk image]: :_files' \ + '--dvd=[Either the UUID or filename of a DVD image]: :_files' \ + '--floppy=[Either the UUID or filename of a floppy image]: :_files' \ + '--password-file=[The name of a file containing the medium encryption password]: :_files' \ + '--hex[Dump as hex bytes]' \ + '--offset=[The byte offset in the medium to start]:offset' \ + '--size=[The number of bytes to dump]:size' \ + '--output=[The output filename]: :_files' \ + && ret=0 + ;; + (stream) + _arguments \ + '--disk=[Either the UUID or filename of a harddisk image]: :_files' \ + '--dvd=[Either the UUID or filename of a DVD image]: :_files' \ + '--floppy=[Either the UUID or filename of a floppy image]: :_files' \ + '--password-file=[The name of a file containing the medium encryption password]: :_files' \ + '--format=[The format of the destination image]:format' \ + '--variant=[The medium variant for the destination]:variant' \ + '--output=[The output filename]: :_files' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_usbfilter] )) || +_vboxmanage_usbfilter() { + local ret=1 + + _arguments -C \ + '1: :(add modify remove)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (add|modify) + _arguments \ + '--action=[Specifies whether to permit VMs access to devices]: :(ignore hold)' \ + '--active=[Specifies whether the USB filter is active or temporarily disabled]: :(yes no)' \ + '--manufacturer=[Specifies a manufacturer ID filter as a string]:manufacturer' \ + '--maskedinterfaces=[Specifies a masked interface filter]:interfaces' \ + '--name=[Specifies the name of the filter]:filter' \ + '--product=[Specifies a product ID filter as a string]:product' \ + '--productid=[Specifies a product ID filter]:product_id' \ + '--remote=[Specifies a remote or not]: :(yes no)' \ + '--revision=[Specifies a revision ID filter]:revision' \ + '--serialnumber=[Specifies a serial number filter as a string]:serial' \ + '--target=[Specifies the VM that the filter is attached to]: :_vboxmachines' \ + '--vendorid=[Specifies a vendor ID filter]:vendor_id' \ + && ret=0 + ;; + (remove) + _arguments \ + '--target=[Specifies the VM that the filter is attached to]: :_vboxmachines' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_sharedfolder] )) || +_vboxmanage_sharedfolder() { + local ret=1 + + _arguments -C \ + '1: :(add remove)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (add) + _arguments \ + '--name=[Specifies the name of the share]:name' \ + '--hostpath=[Specifies the absolute path of the folder or directory on the host OS]: :_files -/' \ + '--readonly[Specifies that the share has only read-only access to files at the host path]' \ + '--transient[Specifies that the share is transient]' \ + '--automount[Specifies that the share is automatically mounted]' \ + '--auto-mount-point=[Specifies the mount point of the share]: :_files -/' \ + '1: :_vboxmachines' \ + && ret=0 + ;; + (remove) + _arguments \ + '--name=[Specifies the name of the share]:name' \ + '--transient[Specifies that the share is transient]' \ + '1: :_vboxmachines' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_guestproperty] )) || +_vboxmanage_guestproperty() { + local ret=1 + + _arguments -C \ + '1: :(get enumerate set unset wait)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (enumerate) + _arguments \ + '--relative[Display the timestamp relative to current time]' \ + '--no-timestamp[Do not display the timestamp of the last update]' \ + '--no-flags[Do not display the flags]' \ + '--old-format[Use the output format from VirtualBox 6]' \ + '1: :_vboxmachines' \ + && ret=0 + ;; + (get) + _arguments \ + '--verbose[Provides the property value, timestamp, and any specified value attributes]' \ + '1: :_vboxmachines' \ + && ret=0 + ;; + (set) + _arguments \ + '--flags=[Specify the additional attributes of the value]: :(TRANSIENT TRANSRESET RDONLYGUEST RDONLYHOST READONLY)' \ + '1: :_vboxmachines' \ + && ret=0 + ;; + (wait) + _arguments \ + '1: :_vboxmachines' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_guestcontrol] )) || +_vboxmanage_guestcontrol() { + local ret=1 + + _arguments -C \ + '1: :_vboxmachines' \ + '2: :(run start copyfrom copyto mkdir rmdir rm mv mktemp stat list closeprocess closesession updatega watch)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + compset -n 2 + case $words[1] in + (add) + _arguments \ + '--quiet[Specifies that the command produce quieter output]' \ + '--verbose[Specifies that the command produce more detailed output]' \ + '--exe=[Specifies the absolute path of the executable program to run on the guest VM]: :_files' \ + '--timeout=[Specifies the maximum amount of time, in milliseconds]:msecs' \ + '*--putenv=[Sets, modifies, and unsets environment variables]:env' \ + '--unquoted-args[Disables the escaped double quoting of arguments]' \ + '--ignore-orphaned-processes[Ignores orphaned processes]' \ + '--profile[Uses a shell profile to specify the environment to use]' \ + '--no-wait-stdout[Does not wait for the guest process to end]' \ + '--wait-stdout[Waits for the guest process to end to receive its exit code]' \ + '--no-wait-stderr[Does not wait for the guest process to end to receive its exit code]' \ + '--wait-stderr[Waits for the guest process to end to receive its exit code]' \ + '--dos2unix[Transform DOS or Windows guest output to UNIX or Linux output]' \ + '--unix2doc[Transform UNIX or Linux guest output to DOS or Windows output]' \ + '*:: :_files' \ + && ret=0 + ;; + (copyfrom|copyto) + _arguments \ + '--quiet[Specifies that the command produce quieter output]' \ + '--verbose[Specifies that the command produce more detailed output]' \ + '--domain=[Specifies the user domain for Windows guest VMs]:domain' \ + '--password=[Specifies the password for the specified user]:password' \ + '--passwordfile=[Specifies the absolute path to a file on the guest OS]: :_files' \ + '--username=[Specifies an existing user on the guest OS that runs the process]:user' \ + '--follow[Enables following of symbolic links on the guest file system]' \ + '--recursive[Recursively copies files and directories from the specified directory on the guest VM]' \ + '--quiet[Specifies that the command produce quieter output]' \ + '--target-directory=[Specifies the absolute path of the destination directory on the host system]: :_files -/' \ + && ret=0 + ;; + (mkdir) + _arguments \ + '--quiet[Specifies that the command produce quieter output]' \ + '--verbose[Specifies that the command produce more detailed output]' \ + '--domain=[Specifies the user domain for Windows guest VMs]:domain' \ + '--password=[Specifies the password for the specified user]:password' \ + '--passwordfile=[Specifies the absolute path to a file on the guest OS]: :_files' \ + '--username=[Specifies an existing user on the guest OS that runs the process]:user' \ + '--parents[Creates any of the missing parent directories of the specified directory]' \ + '--mode=[Specifies the permission mode to use for the specified directory]:mode' \ + && ret=0 + ;; + (rmdir) + _arguments \ + '--quiet[Specifies that the command produce quieter output]' \ + '--verbose[Specifies that the command produce more detailed output]' \ + '--domain=[Specifies the user domain for Windows guest VMs]:domain' \ + '--password=[Specifies the password for the specified user]:password' \ + '--passwordfile=[Specifies the absolute path to a file on the guest OS]: :_files' \ + '--username=[Specifies an existing user on the guest OS that runs the process]:user' \ + '--recursive[Recursively removes directories from the specified from the guest VM]' \ + && ret=0 + ;; + (rmdir) + _arguments \ + '--quiet[Specifies that the command produce quieter output]' \ + '--verbose[Specifies that the command produce more detailed output]' \ + '--domain=[Specifies the user domain for Windows guest VMs]:domain' \ + '--password=[Specifies the password for the specified user]:password' \ + '--passwordfile=[Specifies the absolute path to a file on the guest OS]: :_files' \ + '--username=[Specifies an existing user on the guest OS that runs the process]:user' \ + '--force[Forces the operation and overrides any confirmation requests]' \ + && ret=0 + ;; + (mktemp) + _arguments \ + '--quiet[Specifies that the command produce quieter output]' \ + '--verbose[Specifies that the command produce more detailed output]' \ + '--domain=[Specifies the user domain for Windows guest VMs]:domain' \ + '--password=[Specifies the password for the specified user]:password' \ + '--passwordfile=[Specifies the absolute path to a file on the guest OS]: :_files' \ + '--username=[Specifies an existing user on the guest OS that runs the process]:user' \ + '--directory[Creates a temporary directory that is specified by the template operand]' \ + '--secure[Enforces secure file and directory creation by setting the permission mode to 0755]' \ + '--mode=[Specifies the permission mode to use for the specified directory]:mode' \ + '--tmpdir=[Specifies the absolute path of the directory on the guest VM]: :_files -/' \ + && ret=0 + ;; + (closeprocess|closesession) + _arguments \ + '--quiet[Specifies that the command produce quieter output]' \ + '--verbose[Specifies that the command produce more detailed output]' \ + '--session-id=[Specifies the ID of the guest session]:id' \ + '--session-name=[Specifies the name of the guest session]:name' \ + && ret=0 + ;; + (updatega) + _arguments \ + '--quiet[Specifies that the command produce quieter output]' \ + '--verbose[Specifies that the command produce more detailed output]' \ + '--source=[Specifies the absolute path of the Guest Additions update]: :_files' \ + '--reboot[Automatically reboots the guest after a successful Guest Additions update]' \ + '--timeout=[Sets the timeout (in ms) to wait for the overall Guest Additions update to complete]:ms' \ + '--verify[Verifies whether the Guest Additions were updated successfully]' \ + '--wait-ready[Waits for the current Guest Additions being ready to handle the Guest Additions update]' \ + '--wait-start[Starts the VBoxManage update process on the guest VM and then waits for the Guest Additions update]' \ + && ret=0 + (start|start) + _arguments \ + '--quiet[Specifies that the command produce quieter output]' \ + '--verbose[Specifies that the command produce more detailed output]' \ + '--domain=[Specifies the user domain for Windows guest VMs]:domain' \ + '--password=[Specifies the password for the specified user]:password' \ + '--passwordfile=[Specifies the absolute path to a file on the guest OS]: :_files' \ + '--username=[Specifies an existing user on the guest OS that runs the process]:user' \ + && ret=0 + ;; + (*) + _arguments \ + '--quiet[Specifies that the command produce quieter output]' \ + '--verbose[Specifies that the command produce more detailed output]' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_debugvm] )) || +_vboxmanage_debugvm() { + local ret=1 + + _arguments -C \ + '1: :_vboxmachines' \ + '2: :(dumpvmcore info injectnmi log logdest logflags osdetect osinfo osdmesg getregisters setregisters show stack statistics guestsample)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + compset -n 2 + case $words[1] in + (dumpvmcore) + _arguments \ + '--filename=[The name of the output file]: :_files' \ + && ret=0 + ;; + (log|logdest|logflags) + _arguments \ + '(--release --debug)--release[release flag]' \ + '(--release --debug)--debug[debug flag]' \ + && ret=0 + ;; + (osdmesg) + _arguments \ + '--lines=[Number of lines of the log to display]:line' \ + && ret=0 + ;; + (getregisters|setregisters|stack) + _arguments \ + '--cpu=[Selects the CPU register set when specifying just a CPU register]:id' \ + && ret=0 + ;; + (show) + _arguments \ + '--human-readable[Selects human readable output]' \ + '--sh-export[Selects output format as bourne shell style export commands]' \ + '--sh-eval[Selects output format as bourne shell style eval command input]' \ + '--cmd-set[Selects output format as DOS style SET commands]' \ + && ret=0 + ;; + (statistics) + _arguments \ + '--pattern=[DOS/NT-style wildcards patterns for selecting statistics]:pattern' \ + '--reset[Select reset instead of display mode]' \ + && ret=0 + ;; + (guestsample) + _arguments \ + '--filename=[The filename to dump the sample report to]: :_files' \ + '--sample-interval-us=[The interval in microseconds between guest samples]:us' \ + '--sample-time-us=[The amount of microseconds to take guest samples]:us' \ + '*:: :_files' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_metrics] )) || +_vboxmanage_metrics() { + local ret=1 + + _arguments -C \ + '1: :(collect disable enable list query setup)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (collect) + _arguments \ + '--detach[Disables the collection of metric data, so no data is output]' \ + '--list[Shows which metrics match the specified filter]' \ + '--period=[Specifies the number of seconds to wait between collecting metric data samples]:sec' \ + '--samples=[Specifies the number of metric data samples to save]' \ + '1: :_vboxmachines' \ + && ret=0 + ;; + (disable) + _arguments \ + '--list[Shows which metrics match the specified filter]' \ + '1: :_vboxmachines' \ + && ret=0 + ;; + (setup) + _arguments \ + '--list[Shows which metrics match the specified filter]' \ + '--period=[Specifies the number of seconds to wait between collecting metric data samples]:sec' \ + '--samples=[Specifies the number of metric data samples to save]' \ + '1: :_vboxmachines' \ + && ret=0 + ;; + (*) + _arguments \ + '1: :_vboxmachines' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_natnetwork] )) || +_vboxmanage_natnetwork() { + local ret=1 + + _arguments -C \ + '1: :(add list modify remove start stop)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (add|modify) + _arguments \ + '(--disable --enable)--disable[Disables the NAT network service]' \ + '(--disable --enable)--enable[Enable the NAT network service]' \ + '--natname=[Specifies the name of the new internal network interface on the host OS]:name' \ + '--network=[Specifies the static or DHCP network address and mask of the NAT service interface]:network' \ + '--dhcp=[Enables or disables the DHCP server]: :(on off)' \ + '--ipv6=[Enables or disables IPv6]: :(on off)' \ + '--loopback-4=[Enables an IPv4 loopback interface by using the specified rule]:rule' \ + '--loopback-6=[Enables an IPv6 loopback interface by using the specified rule]:rule' \ + '--port-forward-4=[Enables IPv4 port forwarding by using the rule specified by rule]' \ + '--port-forward-6=[Enables IPv6 port forwarding by using the rule specified by rule]' \ + '*: :_files' \ + && ret=0 + ;; + (remove|start|stop) + _arguments \ + '--natname=[Specifies the name of the NAT]:name' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_hostonlyif] )) || +_vboxmanage_hostonlyif() { + local ret=1 + + _arguments -C \ + '1: :(ipconfig create remove)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (ipconfig) + _arguments \ + '--dhcp[Uses DHCP for the network interface]' \ + '--ip=[Specifies the IPv4 IP address for the network interface]:ipv4' \ + '--netmask=[Specifies the IPv4 netmask of the network interface]:v4mask' \ + '--ipv6=[Specifies the IPv6 IP address for the network interface]:ipv6' \ + '--netmasklengthv6=[Specifies the length of the IPv6 network interface]:length' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_hostonlynet] )) || +_vboxmanage_hostonlynet() { + local ret=1 + + _arguments -C \ + '1: :(add modify remove)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (add|modify) + _arguments \ + '--name=[The host-only network name]:name' \ + '--id=[The host-only network uuid]:netid' \ + '--netmask=[The network mask]:netmask' \ + '--lower-ip=[The lower IP address range for handing out via DHCP]:lower' \ + '--upper-ip=[The upper IP address range for handing out via DHCP]:upper' \ + '(--enable --disable)--enable[Enable the host-only network]' \ + '(--enable --disable)--disable[Disable the host-only network]' \ + && ret=0 + ;; + (remove) + _arguments \ + '--name=[The host-only network name]:name' \ + '--id=[The host-only network uuid]:netid' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_dhcpserver] )) || +_vboxmanage_dhcpserver() { + local ret=1 + + _arguments -C \ + '1: :(add modify remove start restart stop findlease)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (add|modify) + _arguments \ + '--network=[The internal network name]:name' \ + '--interface=[The host only interface name]:interface' \ + '--server-ip=[The IP address the DHCP server should use]:server_ip' \ + '--lower-ip-address=[The lower IP address range for the DHCP server to manage]:lower' \ + '--upper-ip-address=[The upper IP address range for the DHCP server to manage]:upper' \ + '--netmask=[The network mask]:netmask' \ + '(--enable --disable)--enable[Enable the DHCP server]' \ + '(--enable --disable)--disable[Disable the DHCP server]' \ + '--global[Set the configuration scope to global]' \ + '--vm=[Set the configuration scope to the first NIC of the specified VM]:_vboxmachines' \ + '--nic=[Set the configuration scope to a NIC]:id' \ + '--mac-address=[Set the configuration scope to the specified MAC address]:mac' \ + '--group=[Set the configuration scope to the specified group]:group' \ + '--set-opt=[Adds the specified DHCP option number (0-255) and value]:option' \ + '--set-opt-hex=[Adds the specified DHCP option number (0-255) and value]:hex' \ + '--force-opt=[Forces the specified DHCP option number (0-255)]:opt' \ + '--suppress-opt=[Prevents the specified DHCP option number (0-255)]:opt' \ + '--min-lease-time=[Sets the minimum lease time for the current scope in seconds]:sec' \ + '--default-lease-time=[Sets the default lease time for the current scope in seconds]:sec' \ + '--max-lease-time=[Sets the maximum lease time for the current scope in seconds]:sec' \ + '--fixed-address=[Fixed address assignment for a --vm or --mac-address configuration scope]:address' \ + '--incl-mac=[Include the specific MAC address in the group]:mac' \ + '--excl-mac=[Exclude the specific MAC address from the group]:mac' \ + '--incl-mac-wild=[Include the specific MAC address pattern in the group]:pattern' \ + '--excl-mac-wild=[Exclude the specific MAC address pattern from the group]:pattern' \ + '--incl-vendor=[Include the specific vendor class ID in the group]:vendor' \ + '--excl-vendor=[Exclude the specific vendor class ID from the group]:vendor' \ + '--incl-vendor-wild=[Include the specific vendor class ID pattern in the group]:pattern' \ + '--excl-vendor-wild=[Exclude the specific vendor class ID pattern from the group]:pattern' \ + '--incl-user=[Include the specific user class ID in the group]:user' \ + '--excl-user=[Exclude the specific user class ID from the group]:user' \ + '--incl-user-wild=[Include the specific user class ID pattern in the group]:pattern' \ + '--excl-user-wild=[Exclude the specific user class ID pattern from the group]:pattern' \ + && ret=0 + ;; + (remove|start|restart|stop) + _arguments \ + '--network=[The internal network name]:name' \ + '--interface=[The host only interface name]:interface' \ + && ret=0 + ;; + (findlease) + _arguments \ + '--network=[The internal network name]:name' \ + '--interface=[The host only interface name]:interface' \ + '--mac-address=[The MAC address to lookup in the lease database]:mac' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_usbdevsource] )) || +_vboxmanage_usbdevsource() { + local ret=1 + + _arguments -C \ + '1: :(add remove)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (add) + _arguments \ + '--address=[Specifies the address of the USB backend]:address' \ + '--backend=[Specifies the USB proxy service backend to use]:backend' \ + '*: :_files' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_expack] )) || +_vboxmanage_expack() { + local ret=1 + + _arguments -C \ + '1: :(install uninstall cleanup)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (install) + _arguments \ + '--replace[Uninstall existing extension pack version]' \ + '--accept-license=[Accept the license text with the given SHA-256 hash value]:sha256' \ + '*: :_files' \ + && ret=0 + ;; + (uninstall) + _arguments \ + '--force[Overrides most refusals to uninstall an extension pack]' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_updatecheck] )) || +_vboxmanage_updatecheck() { + local ret=1 + + _arguments -C \ + '1: :(perform list modify)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + case $words[1] in + (perform|list) + _arguments \ + '--machine-readable[Machine readable output]' \ + && ret=0 + ;; + (modify) + _arguments \ + '--verbose[Provides the property value, timestamp, and any specified value attributes]' \ + '(--enable --disable)--enable[Enable the update check service]' \ + '(--enable --disable)--disable[Disable the update check service]' \ + '--channel=[The preferred release type]: :(stable withbetas all)' \ + '--frequency=[Specifies how often in days to check for a newer version of VirtualBox]:days' \ + '--proxy-mode=[Specifies the proxy mode to use]: :(system manual none)' \ + '--proxy-url=[Specifies the proxy address to use]:proxy' \ + '1: :_vboxmachines' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxmanage_modifynvram] )) || +_vboxmanage_modifynvram() { + local ret=1 + + _arguments -C \ + '1: :_vboxmachines' \ + '2: :(inituefivarstore enrollmssignatures enrollorclpk enrollpk listvars queryvar deletevar changevar)' \ + '*:: :->arg' \ + && ret=0 + + case $state in + (arg) + compset -n 2 + case $words[1] in + (enrollpk) + _arguments \ + '--platform-key=[The platform key provided as a DER encoded X]: :_files' \ + '--owner-uuid=[The UUID identifying the owner of the platform key]:uuid' \ + && ret=0 + ;; + (queryvar) + _arguments \ + '--name=[UEFI variable name to query]:name' \ + '--filename=[Where to store the content of the variable upon success]: :_files' \ + && ret=0 + ;; + (deletevar) + _arguments \ + '--name=[UEFI variable name to query]:name' \ + '--owner-uuid=[The UUID identifying the owner of the variable to delete]:uuid' \ + && ret=0 + ;; + (queryvar) + _arguments \ + '--name=[UEFI variable name to change the data for]:name' \ + '--filename=[The file to read the data from]: :_files' \ + && ret=0 + ;; + esac + ;; + esac + + return $ret +} + +(( $+functions[_vboxheadless] )) || +_vboxheadless() { + local ret=1 + + _arguments \ + '--startvm[Start given VM]:machine:_vboxmachines' \ + "--vrde[Enable (default) or disable the VRDE server or don't change the setting]: :(on off config)" \ + '--vrdeproperty[Set a VRDE property]:name' \ + '(--settingspw --settingspwfile)--settingspw[Specify the settings password]:password' \ + '(--settingspw --settingspwfile)--settingspwfile[Specify a containing the settings password]: :_files' \ + '--stat-paused[Start the VM in paused state]' \ + '--capture[Record the VM screen output to a file]' \ + '--width[Frame width when recording]:width' \ + '--height[Frame height when recording]:height' \ + '--bitrate[Recording bit rate when recording]:bitrate' \ + '--filename[File name when recording.]:filename:_files' \ + && ret=0 + + return $ret +} + +(( $+functions[_vboxmanage_list_args] )) || +_vboxmanage_list_args() { + local -a args=(vms runningvms ostypes hostdvds hostfloppies + intnets bridgedifs hostonlyifs natnets dhcpservers + hostinfo hostcpuids hddbackends hdds dvds floppies + usbhost usbfilters systemproperties extpacks + groups webcams screenshotformats cloudproviders + cloudprofiles cloudnets) + + _values 'args' $args +} + +(( $+functions[_vboxmachines] )) || +_vboxmachines() { + local -a machines=(${(@f)"$(vboxmanage list vms | grep -v '' | perl -wln -e 'm{^"([^"]+)"} and print $1')"}) + _values 'machines' $machines +} + +(( $+functions[_vboxostypes] )) || +_vboxostypes() { + local -a os=(${(@f)"$(vboxmanage list ostypes | awk '/^ID:/{ print $2 }')"}) + _values 'ostypes' $os +} + +(( $+functions[_vboxmanage_setproperty_value] )) || +_vboxmanage_setproperty_value() { + case $words[2] in + (autostartdbpath) + _arguments '*: :_files' + ;; + (machinefolder) + _arguments '*: :_files -/' + ;; + (proxymode) + local -a mode=(manual noproxy system) + _values 'proxymode' $mode + ;; + esac +} + +_virtualbox "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_vnstat b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_vnstat new file mode 100644 index 00000000..87d9ff1c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_vnstat @@ -0,0 +1,127 @@ +#compdef vnstat +# ------------------------------------------------------------------------------ +# Copyright (c) 2012 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for vnstat 2.10 +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Aaron Schrab +# +# ------------------------------------------------------------------------------ + +local curcontext="$curcontext" state state_descr line ret=1 +typeset -A opt_args + +local period="-d --days -h --hours -m --months -w --weeks" + +_arguments -C : \ + '--add[create database entry for interface specified]' \ + '(-b --begin)'{-b,--begin}'[begin the list output with a specific date]:date:' \ + '--config[specify alternate configuration file]:file:_files' \ + "($period)"{-d,--days}'[show traffic for days]' \ + "($period)"{-h,--hours}'[show traffic for last 24 hours]' \ + "($period)"{-m,--months}'[show traffic for months]' \ + "($period)"{-w,--weeks}'[show traffic for 7 days]' \ + "($period)"{-y,--years}'[show traffic statistics for the last year]' \ + "($period)"{-5,--fiveminutes}'[show traffic statistic with a 5 minute resolution for the last hours]' \ + '--dbdir[specify database directory]:directory:_files -/' \ + '--dbiflist[List interfaces currently in the database]::mode:->dbiflist' \ + '(-D --debug)'{-D,--debug}'[show additional debug output]' \ + '(-e --end)'{-e,--end}'[end the list output with a specific date]:date:' \ + '--delete[delete database and stop monitoring selected interface]' \ + '--dumpdb[dump database in parseable format]' \ + '(--disable)--enable[enable updates for selected interface]' \ + '(--enable)--disable[disable updates for selected interface]' \ + '(-hg --hoursgraph)'{-hg,--hoursgraph}'[show traffic statistics using a bar graph]' \ + '(-i --iface)'{-i,--iface}'[specify interface for actions]:interface:->interface' \ + '--iflist[list available interfaces]' \ + '--limit[set the maximum number of shown entries]:limit:' \ + '(-l --live)'{-l,--live}'[display current transfer rate]:mode:->live' \ + '--json[show database content in json format]' \ + '--locale[specify locale]:locale:' \ + '--nick[set nickname for alias]:nickname:' \ + '--oneline[traffic summary in one-line, parseable format]' \ + '(-q --query)'{-q,--query}'[force database query mode]' \ + '--remove[delete the database entry for the interface specified]' \ + '--rename[rename the interface specified in the database with new name]' \ + '(-r --reset)'{-r,--reset}'[reset internal counters]' \ + '--setalias[set alias as an alias for the selected interface]:alias:' \ + '(-ru --rateunit)'{-ru,--rateunit}'[swap configured rate unit]' \ + '(-s --short)'{-s,--short}'[use short output mode]' \ + '--showconfig[show current configuration]' \ + '--style[modify content and style of output]:style:->style' \ + '--sync[synchronize internal counters]' \ + '--testkernel[test kernel boot time information]' \ + '(-t --top)'{-t,--top}'[show all time top traffic days]' \ + '(-tr --traffic)'{-tr,--traffic}'[calculate amount of traffic in given time]:seconds:' \ + '--xml[show database content in XML format]' \ + '(-)'{-v,--version}'[show current version]' \ + '(-)'{-\?,--help}'[show command summary]' \ + '(-)--longhelp[show complete options list]' \ + && ret=0 + +case "$state" in + (live) + _values 'live mode' \ + '0[packets per second]' \ + '1[traffic counters]' && ret=0 + ;; + (style) + _values 'output style' \ + '0[narrow output]' \ + '1[enable bar column]' \ + '2[bar column with average traffic rate]' \ + '3[enable average traffic rate]' \ + '4[disable use of terminal control characters]' && ret=0 + ;; + (interface) + local interfaces="$(_call_program interfaces 'vnstat --iflist')" + interfaces="${interfaces#*:}" + _values -s + 'interface' ${(z)interfaces} && ret=0 + ;; + (dbiflist) + _values 'mode' \ + '0[one line verbose format]' \ + '1[one interface per line]' \ + && ret=0 + ;; +esac + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: filetype=zsh shiftwidth=2 tabstop=2 expandtab diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_wemux b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_wemux new file mode 100644 index 00000000..691636f0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_wemux @@ -0,0 +1,82 @@ +#compdef wemux +# ------------------------------------------------------------------------------ +# Copyright (c) 2015 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for wemux (https://github.com/zolrath/wemux) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Akira Maeda +# +# ------------------------------------------------------------------------------ +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------ + +_wemux() { + + local -a host_commands client_commands multi_host_commands + + host_commands=( + 'start:Start the wemux server/attach to an existing wemux server.' + 'attach:Attach to an existing wemux server.' + 'stop:Kill the wemux server '\''wemux'\'', delete its socket.' + 'users:List all users currently attached to '\''wemux'\''' + 'kick:Disconnect an SSH user, remove their wemux server.' + 'config:Open the wemux configuration file in your $EDITOR.' + 'help:Display this screen.' + 'version:shows wemux version number' + ) + + client_commands=( + 'mirror:Attach to Host in read-only mode.' + 'pair:Attach to Host in pair mode, which allows editing.' + 'rogue:Attach to Host in rogue mode, which allows editing and switching to windows independently from the host.' + 'logout:Log out of the wemux rogueing session.' + 'users:List the currently attached wemux users.' + ) + + multi_host_commands=( + 'join:Join wemux server with supplied name.' + 'reset:Join default wemux server: wemux' + 'list:List all currently active wemux servers.' + ) + + if (( CURRENT == 2 )); then + _describe -t host_commands 'HOST COMMANDS' host_commands + _describe -t client_commands 'CLIENT COMMANDS' client_commands + _describe -t multi_host_commands 'MULTI-HOST COMMANDS' multi_host_commands + fi + + return 0 +} + +_wemux diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_wg-quick b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_wg-quick new file mode 100644 index 00000000..8de17ce5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_wg-quick @@ -0,0 +1,25 @@ +#compdef wg-quick +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for wg-quick (a script for easy managemant of wireguard +# VPN tunnels) (https://www.wireguard.com/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Nicolas Lenz +# +# ------------------------------------------------------------------------------ + +# The possible modes +local modes=('up\:"bring a wireguard interface up"'\ + 'down\:"tear down and remove a wireguard interface"'\ + 'save\:"save configuration of a running wireguard interface"') + +# 1: Complete mode +# 2: Complete interface with all .conf files in /etc/wireguard without the filename extension. +_arguments "1:mode:((${modes}))"\ + '2:interface:_path_files -W /etc/wireguard -g "*.conf(^/:r)"' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_xsel b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_xsel new file mode 100644 index 00000000..460d9921 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_xsel @@ -0,0 +1,63 @@ +#compdef xsel +# ------------------------------------------------------------------------------ +# Copyright (c) 2017 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for xsel (https://www.vergenet.net/~conrad/software/xsel/). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Tomo Kazahaya (https://github.com/tomonacci) +# +# ------------------------------------------------------------------------------ + +local input='(-a --append -f --follow -i --input)' +local operation='(-c --clear -d --delete -k --keep -x --exchange)' +local selection='(-p --primary -s --secondary -b --clipboard)' + +_arguments -s \ + $input{-a,--append}'[append standard input to the selection]' \ + $input{-f,--follow}'[append to selection as standard input grows]' \ + $input{-i,--input}'[read standard input into the selection]' \ + {-o,--output}'[write the selection to standard output]' \ + $operation{-c,--clear}'[clear the selection]' \ + $operation{-d,--delete}'[request that the current selection be deleted]' \ + $selection{-p,--primary}'[operate on the PRIMARY selection (default)]' \ + $selection{-s,--secondary}'[operate on the SECONDARY selection]' \ + $selection{-b,--clipboard}'[operate on the CLIPBOARD selection]' \ + $operation{-k,--keep}'[do not modify the selections, but make the PRIMARY and SECONDARY selections persist even after the programs they were selected in exit]' \ + $operation{-x,--exchange}'[exchange the PRIMARY and SECONDARY selections]' \ + '--display[specify the server to use; see X(1)]:X display:_x_display' \ + {-t,--selectionTimeout}'[specify the timeout in milliseconds within which the selection must be retrieved]:number' \ + {-l,--logfile}'[specify the file to log errors to when detached (default $HOME/.xsel.log)]:log file:_files' \ + {-n,--nodetach}'[do not detach from the controlling terminal]' \ + {-h,--help}'[display usage information and exit]' \ + {-v,--verbose}'[print informative messages; additional instances of -v raise the debugging level]' \ + '--version[output version information and exit]' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_yarn b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_yarn new file mode 100644 index 00000000..1237ba67 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_yarn @@ -0,0 +1,502 @@ +#compdef yarn +# ------------------------------------------------------------------------------ +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for yarn (https://yarnpkg.com/) +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Massimiliano Torromeo +# * Shohei YOSHIDA +# +# ------------------------------------------------------------------------------ + +declare -g _yarn_run_cwd + +_commands=( + 'access' + 'audit:Checks for known security issues with the installed packages' + 'autoclean:Clean and remove unnecessary files from package dependencies' + 'cache:List or clean every cached package' + "check:Verify package dependencies against yarn's lock file" + 'config:Manages the yarn configuration files' + 'create:Creates new projects from any create-* starter kits' + 'exec' + 'generate-lock-entry:Generates a lock file entry' + 'global:Install packages globally on your operating system' + 'help:Show information about a command' + 'import:Generate yarn.lock from an existing npm-installed node_modules folder' + 'info:Show information about a package' + 'init:Interactively creates or updates a package.json file' + 'install:Install all the dependencies listed within package.json' + 'licenses:List licenses for installed packages' + 'link:Symlink a package folder during development' + 'login:Store registry username and email' + 'logout:Clear registry username and email' + 'node:Runs Node with the same version that the one used by Yarn itself' + 'outdated:Check for outdated package dependencies' + 'owner:Manage package owners' + 'pack:Create a compressed gzip archive of package dependencies' + 'policies:Defines project-wide policies for your project' + 'publish:Publish a package to the npm registry' + 'run:Run a defined package script' + 'tag:Add, remove, or list tags on a package' + 'team:Maintain team memberships' + 'unlink:Unlink a previously created symlink for a package' + 'unplug:Temporarily copies a package outside of the global cache for debugging purposes' + 'version:Update the package version' + 'versions:Display version information of currently installed Yarn, Node.js, and its dependencies' + 'why:Show information about why a package is installed' + 'workspace' + 'workspaces:Show information about your workspaces' +) + +_global_commands=( + 'add:Installs a package and any packages that it depends on' + 'bin:Displays the location of the yarn bin folder' + 'list:List installed packages' + 'remove:Remove installed package from dependencies updating package.json' + 'upgrade:Upgrades packages to their latest version based on the specified range' + 'upgrade-interactive:Interactively upgrade packages' +) + +_yarn_find_package_json() { + local dir=$(cd "$1" && pwd) + + while true + do + if [[ -e "${dir}/package.json" ]]; then + echo "${dir}/package.json" + return + fi + + if [[ $dir == '/' ]]; then + break + fi + + dir=$(dirname $dir) + done +} + +_yarn_commands_scripts() { + local -a scripts binaries + local packageJson + + if [[ -n $opt_args[--cwd] ]]; then + packageJson=$(_yarn_find_package_json $opt_args[--cwd]) + binaries=($(cd $opt_args[--cwd] && echo node_modules/.bin/*(x:t))) + else + packageJson=$(_yarn_find_package_json $pwd) + binaries=($(echo node_modules/.bin/*(x:t))) + fi + + if [[ -n $packageJson ]]; then + scripts=($(cat "$packageJson" | perl -0777 -MJSON::PP -n -E '$r=decode_json($_); do{($k=$_)=~s/:/\\:/g;say $k}for sort keys %{$r->{scripts}}')) + fi + + _describe 'command or script' _commands -- _global_commands -- scripts -- binaries +} + +_yarn_scripts() { + local -a binaries scripts + local -a commands + local packageJson + + if [[ -n $_yarn_run_cwd ]]; then + packageJson=$(_yarn_find_package_json $_yarn_run_cwd) + if [[ -d "${_yarn_run_cwd}/node_modules" ]]; then + binaries=($(cd $_yarn_run_cwd && echo node_modules/.bin/*(x:t))) + else + binaries=($(cd $_yarn_run_cwd && yarn bin | perl -wln -e 'm{^[^:]+: (\S+)$} and print $1')) + fi + else + packageJson=$(_yarn_find_package_json $pwd) + if [[ -d node_modules ]]; then + binaries=($(echo node_modules/.bin/*(x:t))) + else + binaries=($(yarn bin | perl -wln -e 'm{^[^:]+: (\S+)$} and print $1')) + fi + fi + + if [[ -n $packageJson ]]; then + scripts=("${(@f)$(cat ${packageJson} | perl -0777 -MJSON::PP -n -E '%r=%{decode_json($_)->{scripts}}; do{$k=$_;($e=$k)=~s/:/\\:/g; printf "$e:$r{$k}\n"} for sort keys %r')}") + fi + + commands=('env' $scripts $binaries) + _describe 'command' commands +} + +_yarn_global_commands() { + local -a cmds + cmds=('ls:List installed packages') + _describe 'command' _global_commands +} + +_yarn_commands() { + _describe 'command' _commands -- _global_commands +} + +_yarn_add_files() { + if compset -P "(file|link):"; then + _files + fi +} + +_yarn_workspaces() { + local version=$(yarn --version |sed -n 's|\([0-9]*\).*|\1|p') + local -a workspaces + if [[ $version == "1" ]]; then + workspaces=(${(@f)$(yarn workspaces info |sed -n -e 's/^ "\([^"]*\)": {/\1/p')}) + else + workspaces=(${(@f)$(yarn workspaces list --json | sed -n 's|.*"name":"\([^"]*\)"}|\1|p')}) + fi + _describe 'workspace' workspaces +} + +_yarn() { + local context state state_descr line + typeset -A opt_args + + _arguments \ + '(-h --help)'{-h,--help}'[output usage information]' \ + '(-V --version)'{-V,--version}'[output the version number]' \ + '--verbose[output verbose messages on internal operations]' \ + '--cache-folder=[specify a custom folder to store the yarn cache]:folder:_files -/' \ + '--check-files[install will verify file tree of packages for consistency]' \ + '--cwd=[working directory to use]:path:_files -/' \ + "(--enable-pnp --pnp)--disable-pnp[disable the Plug'n'Play installation]" \ + '(--no-emoji)--emoji=[enable emoji in output(default: false)]:enabled:(true false)' \ + '(--emoji)--no-emoji[disable emoji in output]' \ + '(--disable-pnp)'{--enable-pnp,--pnp}"[enable the Plug'n'Play installation]" \ + '--flat[only allow one version of a package]' \ + '--focus[Focus on a single workspace by installing remote copies of its sibling workspaces]' \ + '--force[install and build packages even if they were built before, overwrite lockfile]' \ + "--frozen-lockfile[don't generate a lockfile and fail if an update is needed]" \ + '--global-folder=[modules folder]:folder:_files -/' \ + '--har[save HAR output of network traffic]' \ + '--https-proxy=[HTTPS proxy]:host:_hosts' \ + '--ignore-engines[ignore engines check]' \ + "--ignore-scripts[don't run lifecycle scripts]" \ + '--ignore-optional[ignore optional dependencies]' \ + '--ignore-platform[ignore platform checks]' \ + '--json[format Yarn log messages as lines of JSON]' \ + '--link-duplicates[create hardlinks to the repeated modules in node_modules]' \ + '--link-folder=[specify a custom folder to store global links]' \ + '--modules-folder=[rather than installing modules into the node_modules folder relative to the cwd, output them here]:folder:_files -/' \ + '--mutex=[use a mutex to ensure only one yarn instance is executing]:type[\:specifier]' \ + '--network-concurrency=[maximum number of concurrent network requests]:number' \ + '--network-timeout=[TCP timeout for network requests]:milliseconds' \ + "--no-bin-links[don't generate bin links when setting up packages]" \ + '--no-default-rc[prevent Yarn from automatically detecting yarnrc and npmrc files]' \ + "--no-lockfile[don't read or generate a lockfile]" \ + '--non-interactive[do not show interactive prompts]' \ + '--no-node-version-check[do not warn when using a potentially unsupported Node version]' \ + '--no-progress[disable progress bar]' \ + '--offline[trigger an error if any required dependencies are not available in local cache]' \ + '--otp=[one-time password for two factor authentication]:otpcode' \ + '--prefer-offline[use network only if dependencies are not available in local cache]' \ + '--preferred-cache-folder=[specify a custom folder to store the yarn cache if possible]:folder:_files -/' \ + '(--prod --production)'{--prod,--production}'[install only production dependencies]' \ + '--proxy=[HTTP proxy]:host:_hosts' \ + "--pure-lockfile[don't generate a lockfile]" \ + '--registry=[override configuration registry]:url:_urls' \ + '(-s --silent)'{-s,--silent}'[skip Yarn console logs, other types of logs (script output) will be printed]' \ + '--scripts-prepend-node-path=[prepend the node executable dir to the PATH in scripts]:bool:(true false)' \ + '--skip-integrity-check[run install without checking if node_modules is installed]' \ + "--strict-semver[don't compare semver loosely]" \ + '--update-checksum[update package checksums from current repository]' \ + '--use-yarnrc=[specifies a yarnrc that Yarn should use]:yarnrc:_files' \ + '1: :_yarn_commands_scripts' \ + '*:: :->command_args' + + + case $state in + command_args) + case $words[1] in + help) + _arguments \ + '1: :_yarn_commands' \ + ;; + + access) + _arguments \ + '1: :(public restricted grant revoke ls-packages ls-collaborators edit)' + ;; + + add) + _arguments \ + '(-D --dev)'{-D,--dev}'[install packages in devDependencies]' \ + '(-P --peer)'{-P,--peer}'[install packages in peerDependencies]' \ + '(-O --optional)'{-O,--optional}'[install packages in optionalDependencies]' \ + '(-E --exact)'{-E,--exact}'[install packages as exact versions]' \ + '(-T --tilde)'{-T,--tilde}'[install the most recent release of the packages that have the same minor version]' \ + '(--ignore-workspace-root-check -W)'{--ignore-workspace-root-check,-W}'[allows a package to be installed at the workspaces root]' \ + '--audit[checks for known security issues with the installed packages]' \ + '*:package-name:_yarn_add_files' + ;; + + audit) + _arguments \ + '--verbose[output verbose message]' \ + '--json[format Yarn log messages as lines of JSON]' \ + '--level=[only print advisories with severity greater than or equal to]:level:(info low moderate high critical)' \ + '--groups=[only audit dependencies from listed groups]:groups:->groups_args' + ;; + + cache) + _arguments \ + '1: :(list dir clean)' \ + '*:: :->cache_args' + ;; + + check) + _arguments \ + '--integrity[Verifies that versions and hashed values of the package contents in package.json]' \ + '--verify-tree[Recursively verifies that the dependencies in package.json are present in node_modules]' + ;; + + config) + _arguments \ + '1: :(set get delete list)' \ + '*:: :->config_args' + ;; + + global) + _arguments \ + '--prefix=[bin prefix to use to install binaries]' \ + '1: :_yarn_global_commands' \ + '*:: :->command_args' + ;; + + info) + _arguments \ + '1:package:' \ + '2:field' + ;; + + init) + _arguments \ + '(-y --yes)'{-y,--yes}'[install packages in devDependencies]' + ;; + + licenses) + _arguments \ + '1: :(ls generate-disclaimer)' \ + ;; + + link|unlink|outdated) + _arguments \ + '1:package' \ + ;; + + list) + _arguments \ + '--depth=[Limit the depth of the shown dependencies]:depth' \ + '--pattern=[filter the list of dependencies by the pattern]' + ;; + + owner) + _arguments \ + '1: :(list add rm)' \ + '*:: :->owner_args' + ;; + + pack) + _arguments \ + '(-f --filename)'{-f,--filename}':filename:_files' + ;; + + publish) + _arguments \ + '--new-version:version:' \ + '--message:message:' \ + '--no-git-tag-version' \ + '--access:access:' \ + '--tag:tag:' \ + '1: :_files' + ;; + + policies) + _arguments \ + '1: :(set-version)' + ;; + + remove|upgrade) + _arguments \ + '*:package:' + ;; + + run) + if [[ -n $opt_args[--cwd] ]]; then + _yarn_run_cwd=$opt_args[--cwd] + else + _yarn_run_cwd='' + fi + _arguments \ + '1: :_yarn_scripts' \ + '*:: :_default' + ;; + + tag) + _arguments \ + '1: :(lists add rm)' \ + '*:: :->tag_args' + ;; + + team) + _arguments \ + '1: :(create destroy add rm list)' \ + '*:: :->team_args' + ;; + + upgrade-interactive) + _arguments \ + '--latest[use the version tagged latest in the registry]' + ;; + + version) + _arguments \ + '--new-version[create a new version using an interactive session to prompt you]:version:' \ + '--major[creates a new version by incrementing the major version]' \ + '--minor[creates a new version by incrementing the minor version]' \ + '--patch[creates a new version by incrementing the patch version]' \ + '--premajor[creates a new prerelease version by incrementing the major version]' \ + '--preminor[creates a new prerelease version by incrementing the minor version]' \ + '--prepatch[creates a new prerelease version by incrementing the patch version]' \ + '--prerelease[increments the prerelease version number keeping the main version]' \ + '--no-git-tag-version[creates a new version without creating a git tag]' \ + '--no-commit-hooks[bypasses running commit hooks when committing the new version]' + ;; + + why) + _arguments \ + '1:query:_files' + ;; + + workspace) + _arguments \ + '1:workspace:_yarn_workspaces' \ + '*:: :_yarn_global_commands' + ;; + + workspaces) + _arguments \ + '--json[format Yarn log messages as lines of JSON]' \ + '1:commands:(info run)' + ;; + + *) + _default + ;; + esac + ;; + esac + + case $state in + cache_args) + if [[ $words[1] == "list" ]]; then + _arguments \ + '--pattern=[print out every cached package that matches the pattern]:pattern:' + fi + ;; + config_args) + case $words[1] in + get|delete) + _arguments \ + '1:key:' + ;; + + set) + _arguments \ + '(-g --global)'{-g,--global} \ + '1:key:' \ + '2:value:' + ;; + esac + ;; + groups_args) + local dependency_groups=(devDependencies dependencies optionalDependencies peerDependencies bundledDependencies) + _values -s ',' 'groups' $dependency_groups + ;; + + owner_args) + case $words[1] in + ls) + _arguments \ + '1:package:' + ;; + + add|rm) + _arguments \ + '1:user:' \ + '2:package:' + ;; + esac + ;; + + tag_args) + case $words[1] in + ls) + _arguments \ + '1:package' + ;; + + add|rm) + _arguments \ + '1:package:' \ + '2:tag:' + ;; + esac + ;; + + team_args) + case $words[1] in + create|destroy|ls) + _arguments \ + '1:scope\:team:' + ;; + + add|rm) + _arguments \ + '1:scope\:team:' \ + '2:user:' + ;; + esac + ;; + esac +} + +_yarn "$@" + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_zcash-cli b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_zcash-cli new file mode 100644 index 00000000..5859b2ff --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/src/_zcash-cli @@ -0,0 +1,181 @@ +#compdef zcash-cli +# ------------------------------------------------------------------------------ +# Copyright (c) 2017 Github zsh-users - https://github.com/zsh-users +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without +# modification, are permitted provided that the following conditions are met: +# * Redistributions of source code must retain the above copyright +# notice, this list of conditions and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright +# notice, this list of conditions and the following disclaimer in the +# documentation and/or other materials provided with the distribution. +# * Neither the name of the zsh-users nor the +# names of its contributors may be used to endorse or promote products +# derived from this software without specific prior written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND +# ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED +# WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +# DISCLAIMED. IN NO EVENT SHALL ZSH-USERS BE LIABLE FOR ANY +# DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES +# (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; +# LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND +# ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT +# (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS +# SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------ +# Description +# ----------- +# +# Completion script for zcash-cli (https://z.cash). +# +# ------------------------------------------------------------------------------ +# Authors +# ------- +# +# * Jordy van Wolferen (https://github.com/jvwdev) +# +# ------------------------------------------------------------------------------ + +local state line curcontext="$curcontext" ret=1 + +_arguments -C \ + '-?[display usage information]' \ + -conf='[specify configuration file]:file [zcash.conf]:_files' \ + -datadir='[specify data directory]:directory:_directories' \ + -testnet'[use the test network]' \ + -regtest'[enter regression test mode, which uses a special chain in which blocks can be solved instantly. This is intended for regression testing tools and app development.]' \ + -rpcconnect='[send commands to node running on specified ip]:rpcconnect [127.0.0.1]:_hosts' \ + -rpcport='[connect to JSON-RPC on specified port]: :_guard "[[\:digit\:]]#" "port [8232 or testnet\: 18232]"' \ + -rpcwait'[wait for RPC server to start]' \ + -rpcuser='[username for JSON-RPC connections]:rpcuser' \ + -rpcpassword='[password for JSON-RPC connections]:rpcpassword' \ + -rpcclienttimeout='[specify timeout during HTTP requests, or 0 for no timeout]: :_guard "[[\:digit\:]]#" "timeout (seconds) [900]"' \ + ':subcommand:->subcommand' && ret=0 + +case $state in + subcommand) + subcommands=( + 'getbestblockhash' + 'getblock' + 'getblockchaininfo' + 'getblockcount' + 'getblockhash' + 'getblockheader' + 'getchaintips' + 'getdifficulty' + 'getmempoolinfo' + 'getrawmempool' + 'gettxout' + 'gettxoutproof' + 'gettxoutsetinfo' + 'verifychain' + 'verifytxoutproof' + 'getinfo' + 'help' + 'stop' + 'generate' + 'getgenerate' + 'setgenerate' + 'getblocksubsidy' + 'getblocktemplate' + 'getlocalsolps' + 'getmininginfo' + 'getnetworkhashps' + 'getnetworksolps' + 'prioritisetransaction' + 'submitblock' + 'addnode' + 'clearbanned' + 'disconnectnode' + 'getaddednodeinfo' + 'getconnectioncount' + 'getnettotals' + 'getnetworkinfo' + 'getpeerinfo' + 'listbanned' + 'ping' + 'setban' + 'createrawtransaction' + 'decoderawtransaction' + 'decodescript' + 'fundrawtransaction' + 'getrawtransaction' + 'sendrawtransaction' + 'signrawtransaction' + 'createmultisig' + 'estimatefee' + 'estimatepriority' + 'validateaddress' + 'verifymessage' + 'z_validateaddress' + 'addmultisigaddress' + 'backupwallet' + 'dumpprivkey' + 'dumpwallet' + 'encryptwallet' + 'getaccount' + 'getaccountaddress' + 'getaddressesbyaccount' + 'getbalance' + 'getnewaddress' + 'getrawchangeaddress' + 'getreceivedbyaccount' + 'getreceivedbyaddress' + 'gettransaction' + 'getunconfirmedbalance' + 'getwalletinfo' + 'importaddress' + 'importprivkey' + 'importwallet' + 'keypoolrefill' + 'listaccounts' + 'listaddressgroupings' + 'listlockunspent' + 'listreceivedbyaccount' + 'listreceivedbyaddress' + 'listsinceblock' + 'listtransactions' + 'listunspent' + 'lockunspent' + 'move' + 'sendfrom' + 'sendmany' + 'sendtoaddress' + 'setaccount' + 'settxfee' + 'signmessage' + 'z_exportkey' + 'z_exportwallet' + 'z_getbalance' + 'z_getnewaddress' + 'z_getoperationresult' + 'z_getoperationstatus' + 'z_gettotalbalance' + 'z_importkey' + 'z_importwallet' + 'z_listaddresses' + 'z_listoperationids' + 'z_listreceivedbyaddress' + 'z_sendmany' + 'zcbenchmark' + 'zcrawjoinsplit' + 'zcrawkeygen' + 'zcrawreceive' + 'zcsamplejoinsplit' + ) + + _describe -t subcommands 'zcash-cli subcommand' subcommands && ret=0 + ;; +esac + +return ret + +# Local Variables: +# mode: Shell-Script +# sh-indentation: 2 +# indent-tabs-mode: nil +# sh-basic-offset: 2 +# End: +# vim: ft=zsh sw=2 ts=2 et diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/zsh-completions-howto.org b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/zsh-completions-howto.org new file mode 100644 index 00000000..094e29bc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/zsh-completions-howto.org @@ -0,0 +1,464 @@ +* Table of Contents :TOC: +- [[#intro][Intro]] +- [[#getting-started][Getting started]] + - [[#telling-zsh-which-function-to-use-for-completing-a-command][Telling zsh which function to use for completing a command]] + - [[#completing-generic-gnu-commands][Completing generic gnu commands]] + - [[#copying-completions-from-another-command][Copying completions from another command]] +- [[#writing-your-own-completion-functions][Writing your own completion functions]] + - [[#utility-functions][Utility functions]] + - [[#writing-simple-completion-functions-using-_describe][Writing simple completion functions using _describe]] + - [[#writing-completion-functions-using-_alternative][Writing completion functions using _alternative]] + - [[#writing-completion-functions-using-_arguments][Writing completion functions using _arguments]] + - [[#writing-completion-functions-using-_regex_arguments-and-_regex_words][Writing completion functions using _regex_arguments and _regex_words]] + - [[#complex-completions-with-_values-_sep_parts--_multi_parts][complex completions with _values, _sep_parts, & _multi_parts]] + - [[#adding-completion-words-directly-using-compadd][Adding completion words directly using compadd]] +- [[#testing--debugging][Testing & debugging]] +- [[#gotchas-things-to-watch-out-for][Gotchas (things to watch out for)]] +- [[#tips][Tips]] +- [[#other-resources][Other resources]] + +* Intro +The official documentation for writing zsh completion functions is difficult to understand, and doesn't give many examples. +At the time of writing this document I was able to find a few other tutorials on the web, however those tutorials only +explain a small portion of the capabilities of the completion system. This document aims to cover areas not explained elsewhere, +with examples, so that you can learn how to write more advanced completion functions. I do not go into all the details, but will +give enough information and examples to get you up and running. If you need more details you can look it up for yourself in the + [[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-System][official documentation]]. + +Please make any scripts that you create publicly available for others (e.g. by forking this repo and making a [[id:64bcd501-b0f0-48c7-b8e2-07af708b95ec][pull request]]). +Also if you have any more information to add or improvements to make to this tutorial, please do. +* Getting started +** Telling zsh which function to use for completing a command +Completion functions for commands are stored in files with names beginning with an underscore _, and these files should +be placed in a directory listed in the $fpath variable. +You can add a directory to $fpath by adding a line like this to your ~/.zshrc file: +#+BEGIN_SRC sh +fpath=(~/newdir $fpath) +#+END_SRC +The first line of a completion function file can look something like this: +#+BEGIN_SRC sh +#compdef foobar +#+END_SRC +This tells zsh that the file contains code for completing the foobar command. +This is the format that you will use most often for the first line, but you can also use the same file for completing +several different functions if you want. See [[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Autoloaded-files][here]] for more details. + +You can also use the compdef command directly (e.g. in your ~/.zshrc file) to tell zsh which function to use for completing +a command like this: +#+BEGIN_SRC sh +> compdef _function foobar +#+END_SRC +or to use the same completions for several commands: +#+BEGIN_SRC sh +> compdef _function foobar goocar hoodar +#+END_SRC +or if you want to supply arguments: +#+BEGIN_SRC sh +> compdef '_function arg1 arg2' foobar +#+END_SRC +See [[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Functions-4][here]] for more details. +** Completing generic gnu commands +Many [[https://www.gnu.org/][gnu]] commands have a standardized way of listing option descriptions (when the --help option is used). +For these commands you can use the _gnu_generic function for automatically creating completions, like this: +#+BEGIN_SRC sh +> compdef _gnu_generic foobar +#+END_SRC +or to use _gnu_generic with several different commands: +#+BEGIN_SRC sh +> compdef _gnu_generic foobar goocar hoodar +#+END_SRC +This line can be placed in your ~/.zshrc file. +** Copying completions from another command +If you want a command, say cmd1, to have the same completions as another, say cmd2, which has already had +completions defined for it, you can do this: +#+BEGIN_SRC sh +> compdef cmd1=cmd2 +#+END_SRC +This can be useful for example if you have created an alias for a command to help you remember it. +* Writing your own completion functions +A good way to get started is to look at some already defined completion functions. +On my linux installation these are found in /usr/share/zsh/functions/Completion/Unix +and /usr/share/zsh/functions/Completion/Linux and a few other subdirs. + +You will notice that the _arguments function is used a lot in these files. +This is a utility function that makes it easy to write simple completion functions. +The _arguments function is a wrapper around the compadd builtin function. +The compadd builtin is the core function used to add completion words to the command line, and control its behaviour. +However, most of the time you will not need to use compadd, since there are many utility functions such as _arguments +and _describe which are easier to use. + +For very basic completions the _describe function should be adequate + +** Utility functions +Here is a list of some of the utility functions that may be of use. +The full list of utility functions, with full explanations, is available [[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-Functions][here]]. +Examples of how to use these functions are given in the next section. + +*** main utility functions for overall completion +| _alternative | Can be used to generate completion candidates from other utility functions or shell code. | +| _arguments | Used to specify how to complete individual options & arguments for a command with unix style options. | +| _describe | Used for creating simple completions consisting of words with descriptions (but no actions). Easier to use than _arguments | +| _gnu_generic | Can be used to complete options for commands that understand the `--help' option. | +| _regex_arguments | Creates a function for matching commandline arguments with regular expressions, and then performing actions/completions. | +*** functions for performing complex completions of single words +| _values | Used for completing arbitrary keywords (values) and their arguments, or comma separated lists of such combinations. | +| _combination | Used to complete combinations of values, for example pairs of hostnames and usernames. | +| _multi_parts | Used for completing multiple parts of words separately where each part is separated by some char, e.g. for completing partial filepaths: /u/i/sy -> /usr/include/sys | +| _sep_parts | Like _multi_parts but allows different separators at different parts of the completion. | +| _sequence | Used as a wrapper around another completion function to complete a delimited list of matches generated by that other function. +*** functions for completing specific types of objects +| _path_files | Used to complete filepaths. Take several options to control behaviour. | +| _files | Calls _path_files with all options except -g and -/. These options depend on file-patterns style setting. | +| _net_interfaces | Used for completing network interface names | +| _users | Used for completing user names | +| _groups | Used for completing group names | +| _options | Used for completing the names of shell options. | +| _parameters | Used for completing the names of shell parameters/variables (can restrict to those matching a pattern). | +*** functions for handling cached completions +If you have a very large number of completions you can save them in a cache file so that the completions load quickly. +| _cache_invalid | indicates whether the completions cache corresponding to a given cache identifier needs rebuilding | +| _retrieve_cache | retrieves completion information from a cache file | +| _store_cache | store completions corresponding to a given cache identifier in a cache file | +*** other functions +| _message | Used for displaying help messages in places where no completions can be generated. | +| _regex_words | Can be used to generate arguments for the _regex_arguments command. This is easier than writing the arguments manually. | +| _guard | Can be used in the ACTION of specifications for _arguments and similar functions to check the word being completed. | +*** Actions +Many of the utility functions such as _arguments, _regex_arguments, _alternative and _values may include an action +at the end of an option/argument specification. This action indicates how to complete the corresponding argument. +The actions can take one of the following forms: +| ( ) | Argument is required but no matches are generated for it. | +| (ITEM1 ITEM2) | List of possible matches | +| ((ITEM1\:'DESC1' ITEM2\:'DESC2')) | List of possible matches, with descriptions. Make sure to use different quotes than those around the whole specification. | +| ->STRING | Set $state to STRING and continue ($state can be checked in a case statement after the utility function call) | +| FUNCTION | Name of a function to call for generating matches or performing some other action, e.g. _files or _message | +| {EVAL-STRING} | Evaluate string as shell code to generate matches. This can be used to call a utility function with arguments, e.g. _values or _describe | +| =ACTION | Inserts a dummy word into completion command line without changing the point at which completion takes place. | +Not all action types are available for all utility functions that use them. For example the ->STRING type is not available in the +_regex_arguments or _alternative functions. +** Writing simple completion functions using _describe +The _describe function can be used for simple completions where the order and position of the options/arguments is +not important. You just need to create an array parameter to hold the options & their descriptions, and then pass +the parameter name as an argument to _describe. The following example creates completion candidates c and d, with +the descriptions (note this should be put in a file called _cmd in some directory listed in $fpath). +#+BEGIN_SRC sh +#compdef cmd +local -a subcmds +subcmds=('c:description for c command' 'd:description for d command') +_describe 'command' subcmds +#+END_SRC + +You can use several different lists separated by a double hyphen as follows but note that this mixes the matches under and single heading and is not intended to be used with different types of completion candidates: +#+BEGIN_SRC sh +local -a subcmds topics +subcmds=('c:description for c command' 'd:description for d command') +topics=('e:description for e help topic' 'f:description for f help topic') +_describe 'command' subcmds -- topics +#+END_SRC + +If two candidates have the same description, _describe collects them together on the same row and ensures that descriptions are aligned in neatly in columns. +The _describe function can be used in an ACTION as part of a specification for _alternative, _arguments or _regex_arguments. +In this case you will have to put it in braces with its arguments, e.g. 'TAG:DESCRIPTION:{_describe 'values' options}' +** Writing completion functions using _alternative +Like _describe, this function performs simple completions where the order and position of options/arguments is not important. +However, unlike _describe, instead of fixed matches further functions may be called to generate the completion candidates. Furthermore, _alternative allows a mix of different types of completion candidates to be mixed. + +As arguments it takes a list of specifications each in the form 'TAG:DESCRIPTION:ACTION' where TAG is a special tag that identifies the type of completion matches, +DESCRIPTION is used as a heading to describe the group of completion candidates collectively, and ACTION is one of the action types listed previously (apart from the ->STRING and =ACTION forms). +For example: +#+BEGIN_SRC sh +_alternative 'arguments:custom arg:(a b c)' 'files:filename:_files' +#+END_SRC +The first specification adds completion candidates a, b & c, and the second specification calls the _files function for completing filepaths. + +We could split the specifications over several lines with \ and add descriptions to each of the custom args like this: +#+BEGIN_SRC sh +_alternative \ + 'args:custom arg:((a\:"description a" b\:"description b" c\:"description c"))' \ + 'files:filename:_files' +#+END_SRC + +If we want to pass arguments to _files they can simply be included, like this: +#+BEGIN_SRC sh +_alternative \ + 'args:custom arg:((a\:"description a" b\:"description b" c\:"description c"))'\ + 'files:filename:_files -/' +#+END_SRC + +To use parameter expansion to create our list of completions we must use double quotes to quote the specifications, +e.g: +#+BEGIN_SRC sh +_alternative \ + "dirs:user directory:($userdirs)" \ + "pids:process ID:($(ps -A o pid=))" +#+END_SRC +In this case the first specification adds the words stored in the $userdirs variable, and the second specification +evaluates 'ps -A o pid=' to get a list of pids to use as completion candidates. In practice, we would make used of the existing _pids function for this. + +We can use other utility functions such as _values in the ACTION to perform more complex completions, e.g: +#+BEGIN_SRC sh +_alternative \ + "directories:user directory:($userdirs)" \ + 'options:comma-separated opt: _values -s , letter a b c' +#+END_SRC +this will complete the items in $userdirs, as well as a comma separated list containing a, b &/or c. Note the use of the initial space before _values. This is needed because _values doesn't understand standard compadd options for descriptions. + +As with _describe, the _alternative function can itself be used in an ACTION as part of a specification for _arguments +or _regex_arguments. +** Writing completion functions using _arguments +With a single call to the _arguments function you can create fairly sophisticated completion functions. It is intended to handle typical commands that take a variety of options along with some normal arguments. +Like the _alternative function, _arguments takes a list of specification strings as arguments. +These specification strings specify options and any corresponding option arguments (e.g. -f filename), +or command arguments. + +Basic option specifications take the form '-OPT[DESCRIPTION]', e.g. like this: +#+BEGIN_SRC sh +_arguments '-s[sort output]' '--l[long output]' '-l[long output]' +#+END_SRC +Arguments for the option can be specified after the option description in this form '-OPT[DESCRIPTION]:MESSAGE:ACTION', +where MESSAGE is a message to display and ACTION can be any of the forms mentioned in the ACTIONS section above. +For example: +#+BEGIN_SRC sh +_arguments '-f[input file]:filename:_files' +#+END_SRC + +Command argument specifications take the form 'N:MESSAGE:ACTION' where N indicates that it is the Nth command argument, +and MESSAGE & ACTION are as before. If the N is omitted then it just means the next command argument (after any that have +already been specified). If a double colon is used at the start (after N) then the argument is optional. +For example: +#+BEGIN_SRC sh +_arguments '-s[sort output]' '1:first arg:_net_interfaces' '::optional arg:_files' ':next arg:(a b c)' +#+END_SRC +here the first arg is a network interface, the next optional arg is a file name, the last arg can be either a, b or c, +and the -s option may be completed at any position. + +The _arguments function allows the full set of ACTION forms listed in the ACTION section above. +This means that you can use actions for selecting case statement branches like this: +#+BEGIN_SRC sh +_arguments '-m[music file]:filename:->files' '-f[flags]:flag:->flags' +case "$state" in + files) + local -a music_files + music_files=( Music/**/*.{mp3,wav,flac,ogg} ) + _multi_parts / music_files + ;; + flags) + _values -s , 'flags' a b c d e + ;; +esac +#+END_SRC +In this case paths to music files are completed stepwise descending down directories using the _multi_parts function, +and the flags are completed as a comma separated list using the _values function. + +I have just given you the basics of _arguments specifications here, you can also specify mutually exclusive options, +repeated options & arguments, options beginning with + instead of -, etc. For more details see the [[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-System][official documentation]]. +Also have a look at the tutorials mentioned at the end of this document, and the completion functions in the [[https://github.com/vapniks/zsh-completions/tree/master/src][src directory]]. +** Writing completion functions using _regex_arguments and _regex_words +If you have a complex command line specification with several different possible argument sequences then +the _regex_arguments function may be what you need. It typically works well where you have a series of keywords followed by a variable number of arguments. + +_regex_arguments creates a completion function whose name is given by the first argument. +Hence you need to first call _regex_arguments to create the completion function, and then call that function, +e.g. like this: +#+BEGIN_SRC sh +_regex_arguments _cmd OTHER_ARGS.. +_cmd "$@" +#+END_SRC + +The OTHER_ARGS should be sequences of specifications for matching & completing words on the command line. +These sequences can be separated by '|' to represent alternative sequences of words. +You can use bracketing to arbitrary depth to specify alternate subsequences, but the brackets must be backslashed like this \( \) +or quoted like this '(' ')'. + +For example: +#+BEGIN_SRC sh +_regex_arguments _cmd SEQ1 '|' SEQ2 \( SEQ2a '|' SEQ2b \) +_cmd "$@" +#+END_SRC +This specifies a command line matching either SEQ1, or SEQ2 followed by SEQ2a or SEQ2b. You are describing the form arguments to the command take in the form of a regular expression grammar. + +Each specification in a sequence must contain a / PATTERN/ part at the start followed by an optional ':TAG:DESCRIPTION:ACTION' +part. + +Each PATTERN is a regular expression to match a word on the command line. These patterns are processed sequentially +until we reach a pattern that doesn't match at which point any corresponding ACTION is performed to obtain completions +for that word. Note that there needs to be a pattern to match the initial command itself. +See below for further explanation about PATTERNs. + +The ':TAG:DESCRIPTION:ACTION' part is interpreted in the same way as for the _alternative function specifications, +except that it has an extra : at the start, and now all of the possible ACTION formats listed previously are allowed. + +Here is an example: +#+BEGIN_SRC sh +_regex_arguments _cmd /$'[^\0]##\0'/ \( /$'word1(a|b|c)\0'/ ':word:first word:(word1a word1b word1c)' '|'\ + /$'word11(a|b|c)\0'/ ':word:first word:(word11a word11b word11c)' \( /$'word2(a|b|c)\0'/ ':word:second word:(word2a word2b word2c)'\ + '|' /$'word22(a|b|c)\0'/ ':word:second word:(word22a word22b word22c)' \) \) +_cmd "$@" +#+END_SRC +in this case the first word can be word1 or word11 followed by an a, b or c, and if the first word contains 11 then a second +word is allowed which can be word2 followed by and a, b, or c, or a filename. + +If this sounds too complicated a much simpler alternative is to use the _regex_words function for creating +specifications for _regex_arguments. +*** Patterns +You may notice that the / PATTERN/ specs in the previous example don't look like normal regular expressions. +Often a string parameter in the form $'foo\0' is used. This is so that the \0 in the string is interpreted correctly +as a null char which is used to separate words in the internal representation. If you don't include the \0 at the end +of the pattern you may get problems matching the next word. If you need to use the contents of a variable in a pattern, +you can double quote it so that it gets expanded and then put a string parameter containing a null char afterwards, +like this: "$somevar"$'\0' + +The regular expression syntax for patterns seems to be a bit different from normal regular expressions, +and I can't find documentation anywhere. +However I have managed to work out what the following special chars are for: +| * | wildcard - any number of chars | +| ? | wildcard - single char | +| # | zero or more of the previous char (like * in a normal regular expression) | +| ## | one or more of the previous char (like + in a normal regular expression) | +*** _regex_words +The _regex_words function makes it much easier to create specifications for _regex_arguments. +The results of calling _regex_words can be stored in a variable which can then be used instead +of a specification for _regex_arguments. + +To create a specification using _regex_words you supply it with a tag followed by a description followed by a list +of specifications for individual words. These specifications take the form 'WORD:DESCRIPTION:SPEC' where WORD is the +word to be completed, DESCRIPTION is a description for it, and SPEC can be another variable created by _regex_words +specifying words that come after the current word or blank if there are no further words. +For example: +#+BEGIN_SRC sh +_regex_words firstword 'The first word' 'word1a:a word:' 'word1b:b word:' 'word1c:c word' +#+END_SRC +the results of this function call will be stored in the $reply array, and so we should store it in another array +before $reply gets changed again, like this: +#+BEGIN_SRC sh +local -a firstword +_regex_words word 'The first word' 'word1a:a word:' 'word1b:b word:' 'word1c:c word' +firstword="$reply[@]" +#+END_SRC +we could then use it with _regex_arguments like this: +#+BEGIN_SRC sh +_regex_arguments _cmd /$'[^\0]##\0'/ "$firstword[@]" +_cmd "$@" +#+END_SRC +Note that I have added an extra pattern for the initial command word itself. + +Here is a more complex example where we call _regex_words for different words on the command line +#+BEGIN_SRC sh +local -a firstword firstword2 secondword secondword2 +_regex_words word1 'The second word' 'woo:tang clan' 'hoo:not me' +secondword=("$reply[@]") +_regex_words word2 'Another second word' 'yee:thou' 'haa:very funny!' +secondword2=("$reply[@]") +_regex_words commands 'The first word' 'foo:do foo' 'man:yeah man' 'chu:at chu' +firstword=("$reply[@]") +_regex_words word4 'Another first word' 'boo:scare somebody:$secondword' 'ga:baby noise:$secondword'\ + 'loo:go to the toilet:$secondword2' +firstword2=("$reply[@]") + +_regex_arguments _hello /$'[^\0]##\0'/ "${firstword[@]}" "${firstword2[@]}" +_hello "$@" +#+END_SRC +In this case the first word can be one of "foo", "man", "chu", "boo", "ga" or "loo". +If the first word is "boo" or "ga" then the second word can be "woo" or "hoo", +and if the first word is "loo" then the second word can be "yee" or "haa", in the other +cases there is no second word. + +For a good example of the usage of _regex_words have a look at the _ip function. +** complex completions with _values, _sep_parts, & _multi_parts +The _values, _sep_parts & _multi_parts functions can be used either on their own, or as ACTIONs in specifications for +_alternative, _arguments or _regex_arguments. The following examples may be instructive. +See the [[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-System][official documentation]] for more info. + +Space separated list of mp3 files: +#+BEGIN_SRC sh +_values 'mp3 files' ~/*.mp3 +#+END_SRC + +Comma separated list of session id numbers: +#+BEGIN_SRC sh +_values -s , 'session id' "${(uonzf)$(ps -A o sid=)}" +#+END_SRC + +Completes foo@news:woo, or foo@news:laa, or bar@news:woo, etc: +#+BEGIN_SRC sh +_sep_parts '(foo bar)' @ '(news ftp)' : '(woo laa)' +#+END_SRC + +Complete some MAC addresses one octet at a time: +#+BEGIN_SRC sh +_multi_parts : '(00:11:22:33:44:55 00:23:34:45:56:67 00:23:45:56:67:78)' +#+END_SRC + +** Adding completion words directly using compadd +For more fine grained control you can use the builtin compadd function to add completion words directly. +This function has many different options for controlling how completions are displayed and how text on the command line +can be altered when words are completed. Read the [[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-System][official documentation]] for full details. +Here I just give a few simple examples. + +Add some words to the list of possible completions: +#+BEGIN_SRC sh +compadd foo bar blah +#+END_SRC + +As above but also display an explanation: +#+BEGIN_SRC sh +compadd -X 'Some completions' foo bar blah +#+END_SRC + +As above but automatically insert a prefix of "what_" before the completed word: +#+BEGIN_SRC sh +compadd -P what_ foo bar blah +#+END_SRC + +As above but automatically insert a suffix of "_todo" after the completed word: +#+BEGIN_SRC sh +compadd -S _todo foo bar blah +#+END_SRC + +As above but automatically remove the "_todo" suffix if a blank char is typed after the suffix: +#+BEGIN_SRC sh +compadd -P _todo -q foo bar blah +#+END_SRC + +Add words in array $wordsarray to the list of possible completions +#+BEGIN_SRC sh +compadd -a wordsarray +#+END_SRC + +* Testing & debugging +To reload a completion function: +#+BEGIN_SRC sh +> unfunction _func +> autoload -U _func +#+END_SRC + +The following functions can be called to obtain useful information. +If the default keybindings don't work you can try pressing Alt+x and then enter the command name. +| Function | Default keybinding | Description | +|-----------------+--------------------+--------------------------------------------------------------------------------------------------------------------------------| +| _complete_help | Ctrl+x h | displays information about context names, tags, and completion functions used when completing at the current cursor position | +| _complete_help | Alt+2 Ctrl+x h | as above but displays even more information | +| _complete_debug | Ctrl+x ? | performs ordinary completion, but captures in a temporary file a trace of the shell commands executed by the completion system | +* Gotchas (things to watch out for) +Remember to include a #compdef line at the beginning of the file containing the completion function. + +Take care to use the correct type of quoting for specifications to _arguments or _regex_arguments: +use double quotes if there is a parameter that needs to be expanded in the specification, single quotes otherwise, +and make sure to use different quotes around item descriptions. + +Check that you have the correct number of :'s in the correct places for specifications for _arguments, +_alternative, _regex_arguments, etc. + +Remember to include an initial pattern to match the command word when using _regex_arguments (it does not need a matching action). + +Remember to put a null char $'\0' at the end of any PATTERN argument for _regex_arguments +* Tips +Sometimes you have a situation where there is just one option that can come after a subcommand, and zsh will complete this +automatically when tab is pressed after the subcommand. If instead you want it listed with its description before completing +you can add another empty option (i.e. \:) to the ACTION like this ':TAG:DESCRIPTION:((opt1\:"description for opt1" \:))' +Note this only applies to utility functions that use ACTIONs in their specification arguments (_arguments, _regex_arguments, etc.) + +* Other resources +[[https://wikimatze.de/writing-zsh-completion-for-padrino/][Here]] is a nicely formatted short tutorial showing basic usage of the _arguments function, +and [[https://web.archive.org/web/20190411104837/http://www.linux-mag.com/id/1106/][here]] is a slightly more advanced tutorial using the _arguments function. +[[https://zsh.sourceforge.net/Doc/Release/Completion-System.html#Completion-System][Here]] is the zshcompsys man page. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/zsh-completions.plugin.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/zsh-completions.plugin.zsh new file mode 100644 index 00000000..4c8b884f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-completions/zsh-completions.plugin.zsh @@ -0,0 +1 @@ +fpath+="${0:A:h}/src" diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/.github/issue_template.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/.github/issue_template.md new file mode 100644 index 00000000..00a6aa76 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/.github/issue_template.md @@ -0,0 +1,19 @@ +--- +name: Bug report +about: Create a report to help us improve + +--- + +## Issue description + +Did you install the plugin according to the installation guide? If not, does the issue persist if you do install it that way? + +### Steps to reproduce + + + +## Technical details + +Please run the following commands and paste the results: +1. `command nix-shell -p nix-info --run "nix-info -m"` +2. `zsh --version` diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/.gitignore b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/.gitignore new file mode 100644 index 00000000..2ff03177 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/.gitignore @@ -0,0 +1,3 @@ +logs/ +*.swp + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/LICENSE b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/LICENSE new file mode 100644 index 00000000..8ef47347 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/LICENSE @@ -0,0 +1,27 @@ +Copyright (c) 2018, Philipp Dargel +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +* Neither the name of Spencer Whitt nor the names of other + contributors may be used to endorse or promote products derived from + this software without specific prior written permission. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/README.MD b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/README.MD new file mode 100644 index 00000000..fd653f75 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/README.MD @@ -0,0 +1,113 @@ + +# zsh in nix-shell + +This [oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh/) plugin lets you use zsh as the default shell in a `nix-shell` environment. It's recommended to use this in conjunction with [nix-zsh-completions](https://github.com/spwhitt/nix-zsh-completions). + +# Motivation + +In theory all you need to do to use `zsh` in `nix-shell` is to set `NIX_BUILD_SHELL` to `zsh`. Unfortunatly nix assumes that the `NIX_BUILD_SHELL` is a bash variant and passes bash specific arguments to the shell. To fix this, we need a shim that translates these arguments. + +The information that `nix-shell` exposes to the environment is also pretty sparse. It would be nice to know what derivations are included in the current environment for example to display them in the shells prompt. + +# Installation + +## Oh-My-ZSH + +Clone this repository into your plugins directory + +```sh +git clone https://github.com/chisui/zsh-nix-shell.git $ZSH_CUSTOM/plugins/nix-shell +``` + +Then add `nix-shell` to the plugins list in `~/.zshrc`. + +### NixOS + +If you have installed `zsh` using `nix` the plugins directory is readonly since it's inside of the nix store. +To get around this you can override the [`ZSH_CUSTOM` directory](https://github.com/ohmyzsh/ohmyzsh/wiki/Customization#using-another-customization-directory). +Simply create a writable directory inside of your home directory (e.g. `$HOME/.config/oh-my-zsh`) and set `ZSH_CUSTOM` to that path inside of your `.zshrc` file. + +```sh +ZSH_CUSTOM=$HOME/.config/oh-my-zsh +``` + +After that simply install for `oh-my-zsh` as normal. + +## Plain ZSH + +Clone this repository and add the following to your `~/.zshrc`. + +```sh +source /path/to/zsh-nix-shell/nix-shell.plugin.zsh +``` + +## home-manager + +Add this repository to the [`plugins` list of your configurations](https://rycee.gitlab.io/home-manager/options.html#opt-programs.zsh.plugins): + +```nix +{ + programs.zsh = { + enable = true; + enableCompletion = true; + plugins = [ + { + name = "zsh-nix-shell"; + file = "nix-shell.plugin.zsh"; + src = pkgs.fetchFromGitHub { + owner = "chisui"; + repo = "zsh-nix-shell"; + rev = "v0.7.0"; + sha256 = "149zh2rm59blr2q458a5irkfh82y3dwdich60s9670kl3cl5h2m1"; + }; + } + ]; + }; +} +``` + +## Plugin managers + +It should be possible to install this plugin through most `zsh` plugin managers. If the one of your choice is not supported, feel free to open an issue or even better create a pull request. + +## MacOS + +On MacOS you have to have a `bash` with version `4` or greater. [See Issue 14](https://github.com/chisui/zsh-nix-shell/issues/14) + +# Usage + +Use `nix-shell` as you did before. + +Commands run with `--run` or `--command` argument are executed in `nix-shell`s default shell. In the case of `--command` you are put into a `zsh` shell afterwards. + +## `--pure` + +If you use the `--pure` flag the interactive shell will be the default shell. + +## Environment info + +If you are inside a `nix-shell` environment `IN_NIX_SHELL` will be set. The value will be `impure` or `pure` if you specified `--pure`. + +The `packages` argument is passed through as `NIX_SHELL_PACKAGES` to the shell. + +If this Variable is empty `nix-shell` was called for a specific nix expression which is stored in the `name` environment variable. + +These variables can now be used inside a theme to customize the prompt. Take a look at this [variant of the agnoster theme](https://gist.github.com/chisui/0d12bd51a5fd8e6bb52e6e6a43d31d5e#file-agnoster-nix-zsh-theme) for an example of how this might look. + +![example prompt](https://gist.githubusercontent.com/chisui/0d12bd51a5fd8e6bb52e6e6a43d31d5e/raw/8787d8e234e895b2c74194936290a0da9be539ff/example.png) + +![example prompt for projects](https://gist.githubusercontent.com/chisui/0d12bd51a5fd8e6bb52e6e6a43d31d5e/raw/ea75cad507e2899b9b6d6ce423330641911110d8/exampleProject.png) + +# Limitations + +## Shell hooks + +Shell hooks are supported in general. Since they are executed inside of `bash` before the `zsh` shell is spawned they aren't executed in the same environment. This means that things like aliases won't work. + +## Zsh dotfiles + +The normal zsh dotfiles are sourced after the nix-shell is opened. This means that you have to take into account that these files may override variables set by nix-shell. + +# Contributing + +Please do. Pull requests welcome. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/nix-shell.plugin.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/nix-shell.plugin.zsh new file mode 100644 index 00000000..316f528a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/nix-shell.plugin.zsh @@ -0,0 +1,82 @@ + +NIX_SHELL_PLUGIN_DIR=${0:a:h} + +which bash > /dev/null 2>&1 +if [ "$?" -ne "0" ]; then + echo + echo " WARNING: bash is not installed." + echo " for zsh-nix-shell to work bash has to be in PATH" + echo +fi + + +# extracts packages argument from args and passes them in $NIX_SHELL_PACKAGES variable. +function nix-shell() { + local -a ARGS; ARGS=("$@") + local NIX_SHELL_PACKAGES="${NIX_SHELL_PACKAGES}" + + # extract -p|--packages argument into NIX_SHELL_PACKAGES + local IN_PACKAGES=0 + local PURE=0 + while [[ ${#ARGS[@]} -gt 0 ]] + do + key=${ARGS[1]} + # enter "--packages packages..." mode + if [[ $key = "-p" || $key = "--packages" ]] + then + IN_PACKAGES=1 + NIX_SHELL_PACKAGES+=${NIX_SHELL_PACKAGES:+ }${ARGS[2]} + ARGS=("${ARGS[@]:1}") + + # skip "--arg name value" argument + elif [[ $key = "--arg" ]] + then + IN_PACKAGES=0 + ARGS=("${ARGS[@]:2}") + + elif [[ $key = "--pure" ]] + then + PURE=1 + + # skip all other unary arguments + elif [[ $key == "-"* ]] + then + IN_PACKAGES=0 + ARGS=("${ARGS[@]:1}") + + # If we don't have any argument prefix we are either in package mode + # or we have encountered the path argument + elif [[ $IN_PACKAGES = 1 ]] + then + NIX_SHELL_PACKAGES+=" $key" + fi + ARGS=("${ARGS[@]:1}") + done + + # call real nix shell + if [[ $PURE = 1 ]] + then + # if you use --pure you get bash + command nix-shell "$@" + else + NIX_EXECUTING_SHELL=$(readlink /proc/$$/exe) + if [[ -z "$NIX_EXECUTING_SHELL" ]] && command -v lsof &> /dev/null + then + NIX_EXECUTING_SHELL=$(lsof -p $$ | awk '$4=="txt" {print $9}' | head -n 1) + fi + if [[ -z "$NIX_EXECUTING_SHELL" ]] && command -v zsh &> /dev/null + then + NIX_EXECUTING_SHELL="zsh" + fi + if [[ -z "$NIX_EXECUTING_SHELL" ]] + then + echo "could not determine executing shell. please install `lsof` or `zsh` directly to your PATH" + echo "If this error persists create an issue at https://github.com/chisui/zsh-nix-shell/issues/new/choose" + return 1 + fi + NIX_SHELL_PACKAGES="$NIX_SHELL_PACKAGES" \ + NIX_BUILD_SHELL="$NIX_SHELL_PLUGIN_DIR/scripts/buildShellShim" \ + NIX_EXECUTING_SHELL=$NIX_EXECUTING_SHELL \ + command nix-shell "$@" + fi +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/scripts/buildShellShim b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/scripts/buildShellShim new file mode 100755 index 00000000..e7a6faf3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-nix-shell/scripts/buildShellShim @@ -0,0 +1,26 @@ +#! /usr/bin/env sh + +if [ "$1" = "--rcfile" ]; then + # This means the shell should stay open after executing. So we remove the last line which contains 'exit' + shift + tmp="$(cat $1)" + echo ${tmp%exit} > $1 + cat >> $1 <> ${ZDOTDIR:-$HOME}/.zshrc +``` + + Then, enable syntax highlighting in the current interactive shell: + +```zsh +source ./zsh-syntax-highlighting/zsh-syntax-highlighting.zsh +``` + + If `git` is not installed, download and extract a snapshot of the latest + development tree from: + +``` +https://github.com/zsh-users/zsh-syntax-highlighting/archive/master.tar.gz +``` + + Note the `source` command must be **at the end** of `~/.zshrc`. + + +### With a plugin manager + +Note that `zsh-syntax-highlighting` must be the last plugin sourced. + +The zsh-syntax-highlighting authors recommend manual installation over the use +of a framework or plugin manager. + +This list is incomplete as there are too many +[frameworks / plugin managers][framework-list] to list them all here. + +[framework-list]: https://github.com/unixorn/awesome-zsh-plugins#frameworks + +#### [Antigen](https://github.com/zsh-users/antigen) + +Add `antigen bundle zsh-users/zsh-syntax-highlighting` as the last bundle in +your `.zshrc`. + +#### [Fig](https://fig.io) + +Click the `Install Plugin` button on the [Fig plugin page][fig-plugin]. + +[fig-plugin]: https://fig.io/plugins/other/zsh-syntax-highlighting + +#### [Oh-my-zsh](https://github.com/robbyrussell/oh-my-zsh) + +1. Clone this repository in oh-my-zsh's plugins directory: + + ```zsh + git clone https://github.com/zsh-users/zsh-syntax-highlighting.git ${ZSH_CUSTOM:-~/.oh-my-zsh/custom}/plugins/zsh-syntax-highlighting + ``` + +2. Activate the plugin in `~/.zshrc`: + + ```zsh + plugins=( [plugins...] zsh-syntax-highlighting) + ``` + +3. Restart zsh (such as by opening a new instance of your terminal emulator). + +#### [Prezto](https://github.com/sorin-ionescu/prezto) + +Zsh-syntax-highlighting is included with Prezto. See the +[Prezto documentation][prezto-docs] to enable and configure highlighters. + +[prezto-docs]: https://github.com/sorin-ionescu/prezto/tree/master/modules/syntax-highlighting + +#### [zgen](https://github.com/tarjoilija/zgen) + +Add `zgen load zsh-users/zsh-syntax-highlighting` to the end of your `.zshrc`. + +#### [zplug](https://github.com/zplug/zplug) + +Add `zplug "zsh-users/zsh-syntax-highlighting", defer:2` to your `.zshrc`. + +#### [zplugin](https://github.com/psprint/zplugin) + +Add `zplugin load zsh-users/zsh-syntax-highlighting` to the end of your +`.zshrc`. + + +### System-wide installation + +Any of the above methods is suitable for a single-user installation, +which requires no special privileges. If, however, you desire to install +zsh-syntax-highlighting system-wide, you may do so by running + +```zsh +make install +``` + +and directing your users to add + +```zsh +source /usr/local/share/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh +``` + +to their `.zshrc`s. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/Makefile b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/Makefile new file mode 100644 index 00000000..bbc1d439 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/Makefile @@ -0,0 +1,64 @@ +NAME=zsh-syntax-highlighting + +INSTALL?=install -c +PREFIX?=/usr/local +SHARE_DIR?=$(DESTDIR)$(PREFIX)/share/$(NAME) +DOC_DIR?=$(DESTDIR)$(PREFIX)/share/doc/$(NAME) +ZSH?=zsh # zsh binary to run tests with + +all: + cd docs && \ + cp highlighters.md all.md && \ + printf '\n\nIndividual highlighters documentation\n=====================================' >> all.md && \ + for doc in highlighters/*.md; do printf '\n\n'; cat "$$doc"; done >> all.md + +install: all + $(INSTALL) -d $(SHARE_DIR) + $(INSTALL) -d $(DOC_DIR) + cp .version zsh-syntax-highlighting.zsh $(SHARE_DIR) + cp COPYING.md README.md changelog.md $(DOC_DIR) + sed -e '1s/ .*//' -e '/^\[build-status-[a-z]*\]: /d' < README.md > $(DOC_DIR)/README.md + if [ x"true" = x"`git rev-parse --is-inside-work-tree 2>/dev/null`" ]; then \ + git rev-parse HEAD; \ + else \ + cat .revision-hash; \ + fi > $(SHARE_DIR)/.revision-hash + : +# The [ -e ] check below is to because sh evaluates this with (the moral +# equivalent of) NONOMATCH in effect, and highlighters/*.zsh has no matches. + for dirname in highlighters highlighters/*/ ; do \ + $(INSTALL) -d $(SHARE_DIR)/"$$dirname"; \ + for fname in "$$dirname"/*.zsh ; do [ -e "$$fname" ] && cp "$$fname" $(SHARE_DIR)"/$$dirname"; done; \ + done + cp -R docs/* $(DOC_DIR) + +clean: + rm -f docs/all.md + +test: + @$(ZSH) -fc 'echo ZSH_PATCHLEVEL=$$ZSH_PATCHLEVEL' + @result=0; \ + for test in highlighters/*; do \ + if [ -d $$test/test-data ]; then \ + echo "Running test $${test##*/}"; \ + env -i QUIET=$$QUIET $${TERM:+"TERM=$$TERM"} $(ZSH) -f tests/test-highlighting.zsh "$${test##*/}"; \ + : $$(( result |= $$? )); \ + fi \ + done; \ + exit $$result + +quiet-test: + $(MAKE) test QUIET=y + +perf: + @result=0; \ + for test in highlighters/*; do \ + if [ -d $$test/test-data ]; then \ + echo "Running test $${test##*/}"; \ + $(ZSH) -f tests/test-perfs.zsh "$${test##*/}"; \ + : $$(( result |= $$? )); \ + fi \ + done; \ + exit $$result + +.PHONY: all install clean test perf diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/README.md new file mode 100644 index 00000000..4768b3dd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/README.md @@ -0,0 +1,97 @@ +zsh-syntax-highlighting [![Build Status][build-status-image]][build-status] +======================= + +**[Fish shell][fish]-like syntax highlighting for [Zsh][zsh].** + +*Requirements: zsh 4.3.11+.* + +[fish]: https://fishshell.com/ +[zsh]: https://www.zsh.org/ + +This package provides syntax highlighting for the shell zsh. It enables +highlighting of commands whilst they are typed at a zsh prompt into an +interactive terminal. This helps in reviewing commands before running +them, particularly in catching syntax errors. + +Some examples: + +Before: [![Screenshot #1.1](images/before1-smaller.png)](images/before1.png) +
+After:  [![Screenshot #1.2](images/after1-smaller.png)](images/after1.png) + +Before: [![Screenshot #2.1](images/before2-smaller.png)](images/before2.png) +
+After:  [![Screenshot #2.2](images/after2-smaller.png)](images/after2.png) + +Before: [![Screenshot #3.1](images/before3-smaller.png)](images/before3.png) +
+After:  [![Screenshot #3.2](images/after3-smaller.png)](images/after3.png) + +Before: [![Screenshot #4.1](images/before4-smaller.png)](images/before4-smaller.png) +
+After:  [![Screenshot #4.2](images/after4-smaller.png)](images/after4-smaller.png) + + + +How to install +-------------- + +See [INSTALL.md](INSTALL.md). + + +FAQ +--- + +### Why must `zsh-syntax-highlighting.zsh` be sourced at the end of the `.zshrc` file? + +zsh-syntax-highlighting works by hooking into the Zsh Line Editor (ZLE) and +computing syntax highlighting for the command-line buffer as it stands at the +time z-sy-h's hook is invoked. + +In zsh 5.2 and older, +`zsh-syntax-highlighting.zsh` hooks into ZLE by wrapping ZLE widgets. It must +be sourced after all custom widgets have been created (i.e., after all `zle -N` +calls and after running `compinit`) in order to be able to wrap all of them. +Widgets created after z-sy-h is sourced will work, but will not update the +syntax highlighting. + +In zsh newer than 5.8 (not including 5.8 itself), +zsh-syntax-highlighting uses the `add-zle-hook-widget` facility to install +a `zle-line-pre-redraw` hook. Hooks are run in order of registration, +therefore, z-sy-h must be sourced (and register its hook) after anything else +that adds hooks that modify the command-line buffer. + +### Does syntax highlighting work during incremental history search? + +Highlighting the command line during an incremental history search (by default bound to +to Ctrl+R in zsh's emacs keymap) requires zsh 5.4 or newer. + +Under zsh versions older than 5.4, the zsh-default [underlining][zshzle-Character-Highlighting] +of the matched portion of the buffer remains available, but zsh-syntax-highlighting's +additional highlighting is unavailable. (Those versions of zsh do not provide +enough information to allow computing the highlighting correctly.) + +See issues [#288][i288] and [#415][i415] for details. + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting +[i288]: https://github.com/zsh-users/zsh-syntax-highlighting/pull/288 +[i415]: https://github.com/zsh-users/zsh-syntax-highlighting/pull/415 + +### How are new releases announced? + +There is currently no "push" announcements channel. However, the following +alternatives exist: + +- GitHub's RSS feed of releases: https://github.com/zsh-users/zsh-syntax-highlighting/releases.atom +- An anitya entry: https://release-monitoring.org/project/7552/ + + +How to tweak +------------ + +Syntax highlighting is done by pluggable highlighter scripts. See the +[documentation on highlighters](docs/highlighters.md) for details and +configuration settings. + +[build-status]: https://github.com/zsh-users/zsh-syntax-highlighting/actions +[build-status-image]: https://github.com/zsh-users/zsh-syntax-highlighting/workflows/Tests/badge.svg diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/changelog.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/changelog.md new file mode 100644 index 00000000..861fea5f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/changelog.md @@ -0,0 +1,884 @@ +# Changes in HEAD + + +## Changes fixed as part of the switch to zle-line-pre-redraw + +The changes in this section were fixed by switching to a `zle-line-pre-redraw`-based +implementation. + +Note: The new implementation will only be used on future zsh releases, +numbered 5.8.1.1 and newer, due to interoperability issues with other plugins +(issues #418 and #579). The underlying zsh feature has been available since +zsh 5.3. + +Whilst under development, the new implementation was known as the +"feature/redrawhook" topic branch. + +- Fixed: Highlighting not triggered after popping a buffer from the buffer stack + (using the `push-line` widget, default binding: `M-q`) + [#40] + +- Fixed: Invoking completion when there were no matches removed highlighting + [#90, #470] + +- Fixed: Two successive deletes followed by a yank only yanked the latest + delete, rather than both of them + [#150, #151, #160; cf. #183] + +- Presumed fixed: Completing `$(xsel)` results in an error message from `xsel`, + with pre-2017 versions of `xsel`. (For 2017 vintage and newer, see the issue + for details.) + [#154] + +- Fixed: When the standard `bracketed-paste-magic` widget is in use, pastes were slow + [#295] + +- Fixed: No way to prevent a widget from being wrapped + [#324] + +- Fixed: No highlighting while cycling menu completion + [#375] + +- Fixed: Does not coexist with the `IGNORE_EOF` option + [#377] + +- Fixed: The `undefined-key` widget was wrapped + [#421] + +- Fixed: Does not coexist with the standard `surround` family of widgets + [#520] + +- Fixed: First completed filename doesn't get `path` highlighting + [#632] + + +## Other changes + +- Add issue #712 to the previous release's changelog (hereinafter). + + +# Changes in 0.8.0-alpha1-pre-redrawhook + +## Notice about an improbable-but-not-impossible forward incompatibility + +Everyone can probably skip this section. + +The `master` branch of zsh-syntax-highlighting uses a zsh feature that has not +yet appeared in a zsh release: the `memo=` feature, added to zsh in commit +zsh-5.8-172-gdd6e702ee (after zsh 5.8, before zsh 5.9). In the unlikely event +that this zsh feature should change in an incompatible way before the next +stable zsh release, set `zsh_highlight__memo_feature=0` in your .zshrc files to +disable use of the new feature. + +z-sy-h dogfoods the new, unreleased zsh feature because that feature was +added to zsh at z-sy-h's initiative. The new feature is used in the fix +to issue #418. + + +## Incompatible changes: + +- An unsuccessful completion (a ⮀ Tab press that doesn't change the + command line) no longer causes highlighting to be lost. Visual feedback can + alternatively be achieved by setting the `format` zstyle under the `warnings` + tag, for example, + + zstyle ':completion:*:warnings' format '%F{red}No matches%f' + + Refer to the [description of the `format` style in `zshcompsys(1)`] + [zshcompsys-Standard-Styles-format]. + + (#90, part of #245 (feature/redrawhook)) + +[zshcompsys-Standard-Styles]: https://zsh.sourceforge.io/Doc/Release/Completion-System.html#Standard-Styles +[zshcompsys-Standard-Styles-format]: https://zsh.sourceforge.io/Doc/Release/Completion-System.html#index-format_002c-completion-style + + + +## Other changes: + +- Document `$ZSH_HIGHLIGHT_MAXLENGTH`. + [#698] + +- Optimize highlighting unquoted words (words that are not in single quotes, double quotes, backticks, or dollar-single-quotes) + [#730] + +- Redirection operators (e.g., `<` and `>`) are now highlighted by default + [#646] + +- Propertly terminate `noglob` scope in try/always blocks + [#577] + +- Don't error out when `KSH_ARRAYS` is set in the calling scope + [#622, #689] + +- Literal semicolons in array assignments (`foo=( bar ; baz )`) are now + highlighted as errors. + [3ca93f864fb6] + +- Command separators in array assignments (`foo=( bar | baz )`) are now + highlighted as errors. + [#651, 81267ca3130c] + +- Support parameter elision in command position (e.g., `$foo ls` where `$foo` is unset or empty) + [#667] + +- Don't consider the filename in `sudo -e /path/to/file` to be a command position + [#678] + +- Don't look up absolute directory names in $cdpath + [2cc2583f8f12, part of #669] + +- Fix `exec 2>&1;` being highlighted as an error. + [#676] + +- Fix `: $(<*)` being highlighted as globbing. + [#582] + +- Fix `cat < *` being highlighting as globbing when the `MULTIOS` option is unset. + [#583] + +- Fix `echo >&2` highlighting the `2` as a filename if a file by that name happened to exist + [#694, part of #645] + +- Fix `echo >&-` highlighting the `-` as a filename if a file by that name happened to exist + [part of #645] + +- Fix `echo >&p` highlighting the `p` as a filename if a file by that name happened to exist + [part of #645] + +- Fix wrong highlighting of unquoted parameter expansions under zsh 5.2 and older + [e165f18c758e] + +- Highlight global aliases + [#700] + +- Highlight `: =nosuchcommand' as an error (when the `EQUALS` option hasn't been unset). + [#430] + +- Highlight reserved word after assignments as errors (e.g., `foo=bar (ls;)`) + [#461] + +- Correctly highlight `[[ foo && bar || baz ]]`. + +- Highlight non-executable files in command position correctly (e.g., `% /etc/passwd`) + [#202, #669] + +- Highlight directories in command position correctly, including `AUTO_CD` support + [#669] + +- Recognize `env` as a precommand (e.g., `env FOO=bar ls`) + +- Recognize `strace` as a precommand + +- Fix an error message on stderr before every prompt when the `WARN_NESTED_VAR` zsh option is set: + `_zsh_highlight_main__precmd_hook:1: array parameter _zsh_highlight_main__command_type_cache set in enclosing scope in function _zsh_highlight_main__precmd_hook` + [#727, #731, #732, #733] + +- Fix highlighting of alias whose definitions use a simple command terminator + (such as `;`, `|`, `&&`) before a newline + [#677; had regressed in 0.7.0] + +- Highlight arithmetic expansions (e.g., `$(( 42 ))`) + [#607 #649 #704] + +- Highlight the parentheses of array assignments as reserved words (`foo=( bar )`). + The `assign` style remains supported and has precedence. + [#585] + +- Fix interoperability issue with other plugins that use highlighting. The fix + requires zsh 5.8.0.3 or newer. (zsh 5.8.0.2-dev from the `master` branch, + revision zsh-5.8-172-gdd6e702ee or newer is also fine.) + [#418, https://github.com/okapia/zsh-viexchange/issues/1] + +- Improve performance of the `brackets` highlighter. + +- Fix highlighting of pre-command redirections (e.g., the `$fn` in `<$fn cat`) + [#712] + + +# Changes in version 0.7.1 + +- Remove out-of-date information from the 0.7.0 changelog. + + +# Changes in version 0.7.0 + +This is a stable bugfix and feature release. Major new features and changes include: + +- Add `ZSH_HIGHLIGHT_DIRS_BLACKLIST` to disable "path" and "path prefix" + highlighting for specific directories + [#379] + +- Add the "regexp" highlighter, modelled after the pattern highlighter + [4e6f60063f1c] + +- When a word uses globbing, only the globbing metacharacters will be highlighted as globbing: + in `: foo*bar`, only the `*` will be blue. + [e48af357532c] + +- Highlight pasted quotes (e.g., `: foo"bar"`) + [dc1b2f6fa4bb] + +- Highlight command substitutions (`` : `ls` ``, `: $(ls)`) + [c0e64fe13178 and parents, e86f75a840e7, et al] + +- Highlight process substitutions (`: >(nl)`, `: <(pwd)`, `: =(git diff)`) + [c0e64fe13178 and parents, e86f75a840e7, et al] + +- Highlight command substitutions inside double quotes (``: "`foo`"``) + [f16e858f0c83] + +- Highlight many precommands (e.g., `nice`, `stdbuf`, `eatmydata`; + see `$precommand_options` in the source) + +- Highlight numeric globs (e.g., `echo /lib<->`) + +- Assorted improvements to aliases highlighting + (e.g., + `alias sudo_u='sudo -u'; sudo_u jrandom ls`, + `alias x=y y=z z=nosuchcommand; x`, + `alias ls='ls -l'; \ls`) + [f3410c5862fc, 57386f30aec8, #544, and many others] + +- Highlight some more syntax errors + [dea05e44e671, 298ef6a2fa30] + +- New styles: named file descriptors, `RC_QUOTES`, and unclosed quotes (e.g., `echo "foo`) + [38c794a978cd, 25ae1c01216c, 967335dfc5fd] + +- The 'brackets' highlighting no longer treats quotes specially. + [ecdda36ef56f] + + +Selected bugfixes include: + +- Highlight `sudo` correctly when it's not installed + [26a82113b08b] + +- Handle some non-default options being set in zshrc + [b07ada1255b7, a2a899b41b8, 972ad197c13d, b3f66fc8748f] + +- Fix off-by-one highlighting in vi "visual" mode (vicmd keymap) + [be3882aeb054] + +- The 'yank-pop' widget is not wrapped + [#183] + + +Known issues include: + +- A multiline alias that uses a simple command terminator (such as `;`, `|`, `&&`) + before a newline will incorrectly be highlighted as an error. See issue #677 + for examples and workarounds. + [#677] + [UPDATE: Fixed in 0.8.0] + + +# Changes in version 0.6.0 + +This is a stable release, featuring bugfixes and minor improvements. + + +## Performance improvements: + +(none) + + +## Added highlighting of: + +- The `isearch` and `suffix` [`$zle_highlight` settings][zshzle-Character-Highlighting]. + (79e4d3d12405, 15db71abd0cc, b56ee542d619; requires zsh 5.3 for `$ISEARCHMATCH_ACTIVE` / `$SUFFIX_ACTIVE` support) + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting + +- Possible history expansions in double-quoted strings. + (76ea9e1df316) + +- Mismatched `if`/`then`/`elif`/`else`/`fi`. + (73cb83270262) + + +## Fixed highlighting of: + +- A comment line followed by a non-comment line. + (#385, 9396ad5c5f9c) + +- An unquoted `$*` (expands to the positional parameters). + (237f89ad629f) + +- history-incremental-pattern-search-backward under zsh 5.3.1. + (#407, #415, 462779629a0c) + + +## API changes (for highlighter authors): + +(none) + + +## Developer-visible changes: + +- tests: Set the `ALIAS_FUNC_DEF` option for zsh 5.4 compatibility. + (9523d6d49cb3) + + +## Other changes: + +- docs: Added before/after screenshots. + (cd9ec14a65ec..b7e277106b49) + +- docs: Link Fedora package. + (3d74aa47e4a7, 5feed23962df) + +- docs: Link FreeBSD port. + (626c034c68d7) + +- docs: Link OpenSUSE Build Service packages + (#419, dea1fedc7358) + +- Prevent user-defined aliases from taking effect in z-sy-h's own code. + (#390, 2dce602727d7, 8d5afe47f774; and #392, #395, b8fa1b9dc954) + +- docs: Update zplug installation instructions. + (#399, 4f49c4a35f17) + +- Improve "unhandled ZLE widget 'foo'" error message. + (#409, be083d7f3710) + +- Fix printing of "failed loading highlighters" error message. + (#426, ad522a091429) + + +# Changes in version 0.5.0 + + +## Performance improvements: + +We thank Sebastian Gniazdowski and "m0viefreak" for significant contributions +in this area. + +- Optimize string operations in the `main` (default) highlighter. + (#372/3cb58fd7d7b9, 02229ebd6328, ef4bfe5bcc14, #372/c6b6513ac0d6, #374/15461e7d21c3) + +- Command word highlighting: Use the `zsh/parameter` module to avoid forks. + Memoize (cache) the results. + (#298, 3ce01076b521, 2f18ba64e397, 12b879caf7a6; #320, 3b67e656bff5) + +- Avoid forks in the driver and in the `root` highlighter. + (b9112aec798a, 38c8fbea2dd2) + + +## Added highlighting of: + +- `pkexec` (a precommand). + (#248, 4f3910cbbaa5) + +- Aliases that cannot be defined normally nor invoked normally (highlighted as an error). + (#263 (in part), 28932316cca6) + +- Path separators (`/`) — the default behaviour remains to highlight path separators + and path components the same way. + (#136, #260, 6cd39e7c70d3, 9a934d291e7c, f3d3aaa00cc4) + +- Assignments to individual positional arguments (`42=foo` to assign to `$42`). + (f4036a09cee3) + +- Linewise region (the `visual-line-mode` widget, bound to `V` in zsh's `vi` keymap). + (#267, a7a7f8b42280, ee07588cfd9b) + +- Command-lines recalled by `isearch` mode; requires zsh≥5.3. + (#261 (in part); #257; 4ad311ec0a68) + +- Command-lines whilst the `IGNORE_BRACES` or `IGNORE_CLOSE_BRACES` option is in effect. + (a8a6384356af, 02807f1826a5) + +- Mismatched parentheses and braces (in the `main` highlighter). + (51b9d79c3bb6, 2fabf7ca64b7, a4196eda5e6f, and others) + +- Mismatched `do`/`done` keywords. + (b2733a64da93) + +- Mismatched `foreach`/`end` keywords. + (#96, 2bb8f0703d8f) + +- In Bourne-style function definitions, when the `MULTI_FUNC_DEF` option is set + (which is the default), highlight the first word in the function body as + a command word: `f() { g "$@" }`. + (6f91850a01e1) + +- `always` blocks. + (#335, e5782e4ddfb6) + +- Command substitutions inside double quotes, `"$(echo foo)"`. + (#139 (in part), c3913e0d8ead) + +- Non-alphabetic parameters inside double quotes (`"$$"`, `"$#"`, `"$*"`, `"$@"`, `"$?"`, `"$-"`). + (4afe670f7a1b, 44ef6e38e5a7) + +- Command words from future versions of zsh (forward compatibly). + This also adds an `arg0` style that all other command word styles fall back to. + (b4537a972eed, bccc3dc26943) + +- Escaped history expansions inside double quotes: `: "\!"` + (28d7056a7a06, et seq) + + +## Fixed highlighting of: + +- Command separator tokens in syntactically-invalid positions. + (09c4114eb980) + +- Redirections with a file descriptor number at command word. + (#238 (in part), 73ee7c1f6c4a) + +- The `select` prompt, `$PS3`. + (#268, 451665cb2a8b) + +- Values of variables in `vared`. + (e500ca246286) + +- `!` as an argument (neither a history expansion nor a reserved word). + (4c23a2fd1b90) + +- "division by zero" error under the `brackets` highlighter when `$ZSH_HIGHLIGHT_STYLES` is empty. + (f73f3d53d3a6) + +- Process substitutions, `<(pwd)` and `>(wc -l)`. + (#302, 6889ff6bd2ad, bfabffbf975c, fc9c892a3f15) + +- The non-`SHORT_LOOPS` form of `repeat` loops: `repeat 42; do true; done`. + (#290, 4832f18c50a5, ef68f50c048f, 6362c757b6f7) + +- Broken symlinks (are now highlighted as files). + (#342, 95f7206a9373, 53083da8215e) + +- Lines accepted from `isearch` mode. + (#284; #257, #259, #288; 5bae6219008b, a8fe22d42251) + +- Work around upstream bug that triggered when the command word was a relative + path, that when interpreted relative to a $PATH directory denoted a command; + the effect of that upstream bug was that the relative path was cached as + a "valid external command name". + (#354, #355, 51614ca2c994, fdaeec45146b, 7d38d07255e4; + upstream fix slated to be released in 5.3 (workers/39104)) + +- After accepting a line with the cursor on a bracket, the matching bracket + of the bracket under the cursor no longer remains highlighted (with the + `brackets` highlighter). + (4c4baede519a) + +- The first word on a new line within an array assignment or initialization is no + longer considered a command position. + (8bf423d16d46) + +- Subshells that end at command position, `(A=42)`, `(true;)`. + (#231, 7fb6f9979121; #344, 4fc35362ee5a) + +- Command word after array assignment, `a=(lorem ipsum) pwd`. + (#330, 7fb6f9979121) + + +## API changes (for highlighter authors): + +- New interface `_zsh_highlight_add_highlight`. + (341a3ae1f015, c346f6eb6fb6) + +- tests: Specify the style key, not its value, in test expectations. + (a830613467af, fd061b5730bf, eaa4335c3441, among others) + +- Module author documentation improvements. + (#306 (in part), 217669270418, 0ff354b44b6e, 80148f6c8402, 364f206a547f, and others) + +- The driver no longer defines a `_zsh_highlight_${highlighter}_highlighter_cache` + variable, which is in the highlighters' namespace. + (3e59ab41b6b8, 80148f6c8402, f91a7b885e7d) + +- Rename highlighter entry points. The old names remain supported for + backwards compatibility. + (a3d5dfcbdae9, c793e0dceab1) + +- tests: Add the "NONE" expectation. + (4da9889d1545, 13018f3dd735, d37c55c788cd) + +- tests: consider a test that writes to stderr to have failed. + (#291, 1082067f9315) + + +## Developer-visible changes: + +- Add `make quiet-test`. + (9b64ad750f35) + +- test harness: Better quote replaceables in error messages. + (30d8f92df225) + +- test harness: Fix exit code for XPASS. + (bb8d325c0cbd) + +- Create [HACKING.md](HACKING.md). + (cef49752fd0e) + +- tests: Emit a description for PASS test points. + (6aa57d60aa64, f0bae44b76dd) + +- tests: Create a script that generates a test file. + (8013dc3b8db6, et seq; `tests/generate.zsh`) + + +## Other changes: + +- Under zsh≤5.2, widgets whose names start with a `_` are no longer excluded + from highlighting. + (ed33d2cb1388; reverts part of 186d80054a40 which was for #65) + +- Under zsh≤5.2, widgets implemented by a function named after the widget are + no longer excluded from highlighting. + (487b122c480d; reverts part of 776453cb5b69) + +- Under zsh≤5.2, shell-unsafe widget names can now be wrapped. + (#278, 6a634fac9fb9, et seq) + +- Correct some test expectations. + (78290e043bc5) + +- `zsh-syntax-highlighting.plugin.zsh`: Convert from symlink to plain file + for msys2 compatibility. + (#292, d4f8edc9f3ad) + +- Document installation under some plugin managers. + (e635f766bef9, 9cab566f539b) + +- Don't leak the `PATH_DIRS` option. + (7b82b88a7166) + +- Don't require the `FUNCTION_ARGZERO` option to be set. + (#338, 750aebc553f2) + +- Under zsh≤5.2, support binding incomplete/nonexistent widgets. + (9e569bb0fe04, part of #288) + +- Make the driver reentrant, fixing possibility of infinite recursion + under zsh≤5.2 under interaction with theoretical third-party code. + (#305, d711563fe1bf, 295d62ec888d, f3242cbd6aba) + +- Fix warnings when `WARN_CREATE_GLOBAL` is set prior to sourcing zsh-syntax-highlighting. + (z-sy-h already sets `WARN_CREATE_GLOBAL` internally.) + (da60234fb236) + +- Warn only once, rather than once per keypress, when a highlighter is unavailable. + (0a9b347483ae) + + +# Changes in version 0.4.1 + +## Fixes: + +- Arguments to widgets were not properly dash-escaped. Only matters for widgets + that take arguments (i.e., that are invoked as `zle ${widget} -- ${args}`). + (282c7134e8ac, reverts c808d2187a73) + + +# Changes in version 0.4.0 + + +## Added highlighting of: + +- incomplete sudo commands + (a3047a912100, 2f05620b19ae) + + ```zsh + sudo; + sudo -u; + ``` + +- command words following reserved words + (#207, #222, b397b12ac139 et seq, 6fbd2aa9579b et seq, 8b4adbd991b0) + + ```zsh + if ls; then ls; else ls; fi + repeat 10 do ls; done + ``` + + (The `ls` are now highlighted as a command.) + +- comments (when `INTERACTIVE_COMMENTS` is set) + (#163, #167, 693de99a9030) + + ```zsh + echo Hello # comment + ``` + +- closing brackets of arithmetic expansion, subshells, and blocks + (#226, a59f442d2d34, et seq) + + ```zsh + (( foo )) + ( foo ) + { foo } + ``` + +- command names enabled by the `PATH_DIRS` option + (#228, 96ee5116b182) + + ```zsh + # When ~/bin/foo/bar exists, is executable, ~/bin is in $PATH, + # and 'setopt PATH_DIRS' is in effect + foo/bar + ``` + +- parameter expansions with braces inside double quotes + (#186, 6e3720f39d84) + + ```zsh + echo "${foo}" + ``` + +- parameter expansions in command word + (#101, 4fcfb15913a2) + + ```zsh + x=/bin/ls + $x -l + ``` + +- the command separators '\|&', '&!', '&\|' + + ```zsh + view file.pdf &! ls + ``` + + +## Fixed highlighting of: + +- precommand modifiers at non-command-word position + (#209, 2c9f8c8c95fa) + + ```zsh + ls command foo + ``` + +- sudo commands with infix redirections + (#221, be006aded590, 86e924970911) + + ```zsh + sudo -u >/tmp/foo.out user ls + ``` + +- subshells; anonymous functions + (#166, #194, 0d1bfbcbfa67, 9e178f9f3948) + + ```zsh + (true) + () { true } + ``` + +- parameter assignment statements with no command + (#205, 01d7eeb3c713) + + ```zsh + A=1; + ``` + + (The semicolon used to be highlighted as a mistake) + +- cursor highlighter: Remove the cursor highlighting when accepting a line. + (#109, 4f0c293fdef0) + + +## Removed features: + +- Removed highlighting of approximate paths (`path_approx`). + (#187, 98aee7f8b9a3) + + +## Other changes: + +- main highlighter refactored to use states rather than booleans. + (2080a441ac49, et seq) + +- Fix initialization when sourcing `zsh-syntax-highlighting.zsh` via a symlink + (083c47b00707) + +- docs: Add screenshot. + (57624bb9f64b) + +- widgets wrapping: Don't add '--' when invoking widgets. + (c808d2187a73) [_reverted in 0.4.1_] + +- Refresh highlighting upon `accept-*` widgets (`accept-line` et al). + (59fbdda64c21) + +- Stop leaking match/mbegin/mend to global scope (thanks to upstream + `WARN_CREATE_GLOBAL` improvements). + (d3deffbf46a4) + +- 'make install': Permit setting `$(SHARE_DIR)` from the environment. + (e1078a8b4cf1) + +- driver: Tolerate KSH_ARRAYS being set in the calling context. + (#162, 8f19af6b319d) + +- 'make install': Install documentation fully and properly. + (#219, b1619c001390, et seq) + +- docs: Improve 'main' highlighter's documentation. + (00de155063f5, 7d4252f5f596) + +- docs: Moved to a new docs/ tree; assorted minor updates + (c575f8f37567, 5b34c23cfad5, et seq) + +- docs: Split README.md into INSTALL.md + (0b3183f6cb9a) + +- driver: Report `$ZSH_HIGHLIGHT_REVISION` when running from git + (84734ba95026) + + +## Developer-visible changes: + +- Test harness converted to [TAP](http://testanything.org/tap-specification.html) format + (d99aa58aaaef, et seq) + +- Run each test in a separate subprocess, isolating them from each other + (d99aa58aaaef, et seq) + +- Fix test failure with nonexisting $HOME + (#216, b2ac98b98150) + +- Test output is now colorized. + (4d3da30f8b72, 6fe07c096109) + +- Document `make install` + (a18a7427fd2c) + +- tests: Allow specifying the zsh binary to use. + (557bb7e0c6a0) + +- tests: Add 'make perf' target + (4513eaea71d7) + +- tests: Run each test in a sandbox directory + (c01533920245) + + +# Changes in version 0.3.0 + + +## Added highlighting of: + +- suffix aliases (requires zsh 5.1.1 or newer): + + ```zsh + alias -s png=display + foo.png + ``` + +- prefix redirections: + + ```zsh + foo.txt + ``` + +- arithmetic evaluations: + + ```zsh + (( 42 )) + ``` + +- $'' strings, including \x/\octal/\u/\U escapes + + ```zsh + : $'foo\u0040bar' + ``` + +- multiline strings: + + ```zsh + % echo "line 1 + line 2" + ``` + +- string literals that haven't been finished: + + ```zsh + % echo "Hello, world + ``` +- command words that involve tilde expansion: + + ```zsh + % ~/bin/foo + ``` + +## Fixed highlighting of: + +- quoted command words: + + ```zsh + % \ls + ``` + +- backslash escapes in "" strings: + + ```zsh + % echo "\x41" + ``` + +- noglob after command separator: + + ```zsh + % :; noglob echo * + ``` + +- glob after command separator, when the first command starts with 'noglob': + + ```zsh + % noglob true; echo * + ``` + +- the region (vi visual mode / set-mark-command) (issue #165) + +- redirection and command separators that would be highlighted as `path_approx` + + ```zsh + % echo foo;‸ + % echo <‸ + ``` + + (where `‸` represents the cursor location) + +- escaped globbing (outside quotes) + + ```zsh + % echo \* + ``` + + +## Other changes: + +- implemented compatibility with zsh's paste highlighting (issue #175) + +- `$?` propagated correctly to wrapped widgets + +- don't leak $REPLY into global scope + + +## Developer-visible changes: + +- added makefile with `install` and `test` targets + +- set `warn_create_global` internally + +- document release process + + + + +# Version 0.2.1 + +(Start of changelog.) + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters.md new file mode 100644 index 00000000..fb64c3af --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters.md @@ -0,0 +1,132 @@ +zsh-syntax-highlighting / highlighters +====================================== + +Syntax highlighting is done by pluggable highlighters: + +* `main` - the base highlighter, and the only one [active by default][main]. +* `brackets` - [matches brackets][brackets] and parenthesis. +* `pattern` - matches [user-defined patterns][pattern]. +* `regexp` - matches [user-defined regular expressions][regexp]. +* `cursor` - matches [the cursor position][cursor]. +* `root` - highlights the whole command line [if the current user is root][root]. +* `line` - applied to [the whole command line][line]. + +[main]: highlighters/main.md +[brackets]: highlighters/brackets.md +[pattern]: highlighters/pattern.md +[regexp]: highlighters/regexp.md +[cursor]: highlighters/cursor.md +[root]: highlighters/root.md +[line]: highlighters/line.md + + +Highlighter-independent settings +-------------------------------- + +By default, all command lines are highlighted. However, it is possible to +prevent command lines longer than a fixed number of characters from being +highlighted by setting the variable `${ZSH_HIGHLIGHT_MAXLENGTH}` to the maximum +length (in characters) of command lines to be highlighter. This is useful when +editing very long command lines (for example, with the [`fned`][fned] utility +function). Example: + +[fned]: https://zsh.sourceforge.io/Doc/Release/User-Contributions.html#index-zed + +```zsh +ZSH_HIGHLIGHT_MAXLENGTH=512 +``` + + +How to activate highlighters +---------------------------- + +To activate an highlighter, add it to the `ZSH_HIGHLIGHT_HIGHLIGHTERS` array. +By default `ZSH_HIGHLIGHT_HIGHLIGHTERS` is `(main)`. For example to activate +`brackets`, `pattern`, and `cursor` highlighters, in `~/.zshrc` do: + +```zsh +ZSH_HIGHLIGHT_HIGHLIGHTERS+=(brackets pattern cursor) +``` + + +How to tweak highlighters +------------------------- + +Highlighters look up styles from the `ZSH_HIGHLIGHT_STYLES` associative array. +Navigate into the [individual highlighters' documentation](highlighters/) to +see what styles (keys) each highlighter defines; the syntax for values is the +same as the syntax of "types of highlighting" of the zsh builtin +`$zle_highlight` array, which is documented in [the `zshzle(1)` manual +page][zshzle-Character-Highlighting]. + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting + +Some highlighters support additional configuration parameters; see each +highlighter's documentation for details and examples. + + +How to implement a new highlighter +---------------------------------- + +To create your own `acme` highlighter: + +* Create your script at + `highlighters/acme/acme-highlighter.zsh`. + +* Implement the `_zsh_highlight_highlighter_acme_predicate` function. + This function must return 0 when the highlighter needs to be called and + non-zero otherwise, for example: + + ```zsh + _zsh_highlight_highlighter_acme_predicate() { + # Call this highlighter in SVN working copies + [[ -d .svn ]] + } + ``` + +* Implement the `_zsh_highlight_highlighter_acme_paint` function. + This function does the actual syntax highlighting, by calling + `_zsh_highlight_add_highlight` with the start and end of the region to + be highlighted and the `ZSH_HIGHLIGHT_STYLES` key to use. Define the default + style for that key in the highlighter script outside of any function with + `: ${ZSH_HIGHLIGHT_STYLES[key]:=value}`, being sure to prefix + the key with your highlighter name and a colon. For example: + + ```zsh + : ${ZSH_HIGHLIGHT_STYLES[acme:aurora]:=fg=green} + + _zsh_highlight_highlighter_acme_paint() { + # Colorize the whole buffer with the 'aurora' style + _zsh_highlight_add_highlight 0 $#BUFFER acme:aurora + } + ``` + + If you need to test which options the user has set, test `zsyh_user_options` + with a sensible default if the option is not present in supported zsh + versions. For example: + + ```zsh + [[ ${zsyh_user_options[ignoreclosebraces]:-off} == on ]] + ``` + + The option name must be all lowercase with no underscores and not an alias. + +* Name your own functions and global variables `_zsh_highlight_acme_*`. + + - In zsh-syntax-highlighting 0.4.0 and earlier, the entrypoints + `_zsh_highlight_highlighter_acme_predicate` and + `_zsh_highlight_highlighter_acme_paint` + were named + `_zsh_highlight_acme_highlighter_predicate` and + `_zsh_highlight_highlighter_acme_paint` respectively. + + These names are still supported for backwards compatibility; + however, support for them will be removed in a future major or minor release (v0.x.0 or v1.0.0). + +* Activate your highlighter in `~/.zshrc`: + + ```zsh + ZSH_HIGHLIGHT_HIGHLIGHTERS+=(acme) + ``` + +* [Write tests](../tests/README.md). diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/brackets.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/brackets.md new file mode 100644 index 00000000..0101699e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/brackets.md @@ -0,0 +1,31 @@ +zsh-syntax-highlighting / highlighters / brackets +------------------------------------------------- + +This is the `brackets` highlighter, that highlights brackets and parentheses, and +matches them. + + +### How to tweak it + +This highlighter defines the following styles: + +* `bracket-error` - unmatched brackets +* `bracket-level-N` - brackets with nest level N +* `cursor-matchingbracket` - the matching bracket, if cursor is on a bracket + +To override one of those styles, change its entry in `ZSH_HIGHLIGHT_STYLES`, +for example in `~/.zshrc`: + +```zsh +# To define styles for nested brackets up to level 4 +ZSH_HIGHLIGHT_STYLES[bracket-level-1]='fg=blue,bold' +ZSH_HIGHLIGHT_STYLES[bracket-level-2]='fg=red,bold' +ZSH_HIGHLIGHT_STYLES[bracket-level-3]='fg=yellow,bold' +ZSH_HIGHLIGHT_STYLES[bracket-level-4]='fg=magenta,bold' +``` + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/cursor.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/cursor.md new file mode 100644 index 00000000..3f87d422 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/cursor.md @@ -0,0 +1,24 @@ +zsh-syntax-highlighting / highlighters / cursor +----------------------------------------------- + +This is the `cursor` highlighter, that highlights the cursor. + + +### How to tweak it + +This highlighter defines the following styles: + +* `cursor` - the style for the current cursor position + +To override one of those styles, change its entry in `ZSH_HIGHLIGHT_STYLES`, +for example in `~/.zshrc`: + +```zsh +ZSH_HIGHLIGHT_STYLES[cursor]='bg=blue' +``` + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/line.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/line.md new file mode 100644 index 00000000..f76639ee --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/line.md @@ -0,0 +1,24 @@ +zsh-syntax-highlighting / highlighters / line +--------------------------------------------- + +This is the `line` highlighter, that highlights the whole line. + + +### How to tweak it + +This highlighter defines the following styles: + +* `line` - the style for the whole line + +To override one of those styles, change its entry in `ZSH_HIGHLIGHT_STYLES`, +for example in `~/.zshrc`: + +```zsh +ZSH_HIGHLIGHT_STYLES[line]='bold' +``` + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/main.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/main.md new file mode 100644 index 00000000..4a27653f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/main.md @@ -0,0 +1,121 @@ +zsh-syntax-highlighting / highlighters / main +--------------------------------------------- + +This is the `main` highlighter, that highlights: + +* Commands +* Options +* Arguments +* Paths +* Strings + +This highlighter is active by default. + + +### How to tweak it + +This highlighter defines the following styles: + +* `unknown-token` - unknown tokens / errors +* `reserved-word` - shell reserved words (`if`, `for`) +* `alias` - aliases +* `suffix-alias` - suffix aliases (requires zsh 5.1.1 or newer) +* `global-alias` - global aliases +* `builtin` - shell builtin commands (`shift`, `pwd`, `zstyle`) +* `function` - function names +* `command` - command names +* `precommand` - precommand modifiers (e.g., `noglob`, `builtin`) +* `commandseparator` - command separation tokens (`;`, `&&`) +* `hashed-command` - hashed commands +* `autodirectory` - a directory name in command position when the `AUTO_CD` option is set +* `path` - existing filenames +* `path_pathseparator` - path separators in filenames (`/`); if unset, `path` is used (default) +* `path_prefix` - prefixes of existing filenames +* `path_prefix_pathseparator` - path separators in prefixes of existing filenames (`/`); if unset, `path_prefix` is used (default) +* `globbing` - globbing expressions (`*.txt`) +* `history-expansion` - history expansion expressions (`!foo` and `^foo^bar`) +* `command-substitution` - command substitutions (`$(echo foo)`) +* `command-substitution-unquoted` - an unquoted command substitution (`$(echo foo)`) +* `command-substitution-quoted` - a quoted command substitution (`"$(echo foo)"`) +* `command-substitution-delimiter` - command substitution delimiters (`$(` and `)`) +* `command-substitution-delimiter-unquoted` - an unquoted command substitution delimiters (`$(` and `)`) +* `command-substitution-delimiter-quoted` - a quoted command substitution delimiters (`"$(` and `)"`) +* `process-substitution` - process substitutions (`<(echo foo)`) +* `process-substitution-delimiter` - process substitution delimiters (`<(` and `)`) +* `arithmetic-expansion` - arithmetic expansion `$(( 42 ))`) +* `single-hyphen-option` - single-hyphen options (`-o`) +* `double-hyphen-option` - double-hyphen options (`--option`) +* `back-quoted-argument` - backtick command substitution (`` `foo` ``) +* `back-quoted-argument-unclosed` - unclosed backtick command substitution (`` `foo ``) +* `back-quoted-argument-delimiter` - backtick command substitution delimiters (`` ` ``) +* `single-quoted-argument` - single-quoted arguments (`` 'foo' ``) +* `single-quoted-argument-unclosed` - unclosed single-quoted arguments (`` 'foo ``) +* `double-quoted-argument` - double-quoted arguments (`` "foo" ``) +* `double-quoted-argument-unclosed` - unclosed double-quoted arguments (`` "foo ``) +* `dollar-quoted-argument` - dollar-quoted arguments (`` $'foo' ``) +* `dollar-quoted-argument-unclosed` - unclosed dollar-quoted arguments (`` $'foo ``) +* `rc-quote` - two single quotes inside single quotes when the `RC_QUOTES` option is set (`` 'foo''bar' ``) +* `dollar-double-quoted-argument` - parameter expansion inside double quotes (`$foo` inside `""`) +* `back-double-quoted-argument` - backslash escape sequences inside double-quoted arguments (`\"` in `"foo\"bar"`) +* `back-dollar-quoted-argument` - backslash escape sequences inside dollar-quoted arguments (`\x` in `$'\x48'`) +* `assign` - parameter assignments (`x=foo` and `x=( )`) +* `redirection` - redirection operators (`<`, `>`, etc) +* `comment` - comments, when `setopt INTERACTIVE_COMMENTS` is in effect (`echo # foo`) +* `comment` - elided parameters in command position (`$x ls` when `$x` is unset or empty) +* `named-fd` - named file descriptor (the `fd` in `echo foo {fd}>&2`) +* `numeric-fd` - numeric file descriptor (the `2` in `echo foo {fd}>&2`) +* `arg0` - a command word other than one of those enumerated above (other than a command, precommand, alias, function, or shell builtin command). +* `default` - everything else + +To override one of those styles, change its entry in `ZSH_HIGHLIGHT_STYLES`, +for example in `~/.zshrc`: + +```zsh +# Declare the variable +typeset -A ZSH_HIGHLIGHT_STYLES + +# To differentiate aliases from other command types +ZSH_HIGHLIGHT_STYLES[alias]='fg=magenta,bold' + +# To have paths colored instead of underlined +ZSH_HIGHLIGHT_STYLES[path]='fg=cyan' + +# To disable highlighting of globbing expressions +ZSH_HIGHLIGHT_STYLES[globbing]='none' +``` + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +#### Parameters + +To avoid partial path lookups on a path, add the path to the `ZSH_HIGHLIGHT_DIRS_BLACKLIST` array. + +```zsh +ZSH_HIGHLIGHT_DIRS_BLACKLIST+=(/mnt/slow_share) +``` + +### Useless trivia + +#### Forward compatibility. + +zsh-syntax-highlighting attempts to be forward-compatible with zsh. +Specifically, we attempt to facilitate highlighting _command word_ types that +had not yet been invented when this version of zsh-syntax-highlighting was +released. + +A _command word_ is something like a function name, external command name, et +cetera. (See +[Simple Commands & Pipelines in `zshmisc(1)`][zshmisc-Simple-Commands-And-Pipelines] +for a formal definition.) + +If a new _kind_ of command word is ever added to zsh — something conceptually +different than "function" and "alias" and "external command" — then command words +of that (new) kind will be highlighted by the style `arg0_$kind`, +where `$kind` is the output of `type -w` on the new kind of command word. If that +style is not defined, then the style `arg0` will be used instead. + +[zshmisc-Simple-Commands-And-Pipelines]: https://zsh.sourceforge.io/Doc/Release/Shell-Grammar.html#Simple-Commands-_0026-Pipelines + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/pattern.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/pattern.md new file mode 100644 index 00000000..ecaa6a7f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/pattern.md @@ -0,0 +1,24 @@ +zsh-syntax-highlighting / highlighters / pattern +------------------------------------------------ + +This is the `pattern` highlighter, that highlights user-defined patterns. + + +### How to tweak it + +To use this highlighter, associate patterns with styles in the +`ZSH_HIGHLIGHT_PATTERNS` associative array, for example in `~/.zshrc`: + +```zsh +# Declare the variable +typeset -A ZSH_HIGHLIGHT_PATTERNS + +# To have commands starting with `rm -rf` in red: +ZSH_HIGHLIGHT_PATTERNS+=('rm -rf *' 'fg=white,bold,bg=red') +``` + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/regexp.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/regexp.md new file mode 100644 index 00000000..b1bed914 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/regexp.md @@ -0,0 +1,65 @@ +zsh-syntax-highlighting / highlighters / regexp +------------------------------------------------ + +This is the `regexp` highlighter, that highlights user-defined regular +expressions. It's similar to the `pattern` highlighter, but allows more complex +patterns. + +### How to tweak it + +To use this highlighter, associate regular expressions with styles in the +`ZSH_HIGHLIGHT_REGEXP` associative array, for example in `~/.zshrc`: + +```zsh +typeset -A ZSH_HIGHLIGHT_REGEXP +ZSH_HIGHLIGHT_REGEXP+=('^rm .*' fg=red,bold) +``` + +This will highlight lines that start with a call to the `rm` command. + +The regular expressions flavour used is [PCRE][pcresyntax] when the +`RE_MATCH_PCRE` option is set and POSIX Extended Regular Expressions (ERE), +as implemented by the platform's C library, otherwise. For details on the +latter, see [the `zsh/regex` module's documentation][MAN_ZSH_REGEX] and the +`regcomp(3)` and `re_format(7)` manual pages on your system. + +For instance, to highlight `sudo` only as a complete word, i.e., `sudo cmd`, +but not `sudoedit`, one might use: + +* When the `RE_MATCH_PCRE` is set: + + ```zsh + typeset -A ZSH_HIGHLIGHT_REGEXP + ZSH_HIGHLIGHT_REGEXP+=('\bsudo\b' fg=123,bold) + ``` + +* When the `RE_MATCH_PCRE` is unset, on platforms with GNU `libc` (e.g., many GNU/Linux distributions): + + ```zsh + typeset -A ZSH_HIGHLIGHT_REGEXP + ZSH_HIGHLIGHT_REGEXP+=('\' fg=123,bold) + ``` + +* When the `RE_MATCH_PCRE` is unset, on BSD-based platforms (e.g., macOS): + + ```zsh + typeset -A ZSH_HIGHLIGHT_REGEXP + ZSH_HIGHLIGHT_REGEXP+=('[[:<:]]sudo[[:>:]]' fg=123,bold) + ``` + +Note, however, that PCRE and POSIX ERE have a large common subset: +for instance, the regular expressions `[abc]`, `a*`, and `(a|b)` have the same +meaning in both flavours. + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +See also: [regular expressions tutorial][perlretut], zsh regexp operator `=~` +in [the `zshmisc(1)` manual page][zshmisc-Conditional-Expressions] + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting +[perlretut]: http://perldoc.perl.org/perlretut.html +[zshmisc-Conditional-Expressions]: https://zsh.sourceforge.io/Doc/Release/Conditional-Expressions.html#Conditional-Expressions +[MAN_ZSH_REGEX]: https://zsh.sourceforge.io/Doc/Release/Zsh-Modules.html#The-zsh_002fregex-Module +[pcresyntax]: https://www.pcre.org/original/doc/html/pcresyntax.html diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/root.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/root.md new file mode 100644 index 00000000..8197e4bd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/docs/highlighters/root.md @@ -0,0 +1,25 @@ +zsh-syntax-highlighting / highlighters / root +--------------------------------------------- + +This is the `root` highlighter, that highlights the whole line if the current +user is root. + + +### How to tweak it + +This highlighter defines the following styles: + +* `root` - the style for the whole line if the current user is root. + +To override one of those styles, change its entry in `ZSH_HIGHLIGHT_STYLES`, +for example in `~/.zshrc`: + +```zsh +ZSH_HIGHLIGHT_STYLES[root]='bg=red' +``` + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/README.md new file mode 100644 index 00000000..8490ddf4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/README.md @@ -0,0 +1,8 @@ +zsh-syntax-highlighting / highlighters +====================================== + +Navigate into the individual highlighters' documentation to see +what styles (`$ZSH_HIGHLIGHT_STYLES` keys) each highlighter defines. + +Refer to the [documentation on highlighters](../docs/highlighters.md) for further +information. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/README.md new file mode 100644 index 00000000..0101699e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/README.md @@ -0,0 +1,31 @@ +zsh-syntax-highlighting / highlighters / brackets +------------------------------------------------- + +This is the `brackets` highlighter, that highlights brackets and parentheses, and +matches them. + + +### How to tweak it + +This highlighter defines the following styles: + +* `bracket-error` - unmatched brackets +* `bracket-level-N` - brackets with nest level N +* `cursor-matchingbracket` - the matching bracket, if cursor is on a bracket + +To override one of those styles, change its entry in `ZSH_HIGHLIGHT_STYLES`, +for example in `~/.zshrc`: + +```zsh +# To define styles for nested brackets up to level 4 +ZSH_HIGHLIGHT_STYLES[bracket-level-1]='fg=blue,bold' +ZSH_HIGHLIGHT_STYLES[bracket-level-2]='fg=red,bold' +ZSH_HIGHLIGHT_STYLES[bracket-level-3]='fg=yellow,bold' +ZSH_HIGHLIGHT_STYLES[bracket-level-4]='fg=magenta,bold' +``` + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/brackets-highlighter.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/brackets-highlighter.zsh new file mode 100644 index 00000000..bc388fdb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/brackets-highlighter.zsh @@ -0,0 +1,107 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + + +# Define default styles. +: ${ZSH_HIGHLIGHT_STYLES[bracket-error]:=fg=red,bold} +: ${ZSH_HIGHLIGHT_STYLES[bracket-level-1]:=fg=blue,bold} +: ${ZSH_HIGHLIGHT_STYLES[bracket-level-2]:=fg=green,bold} +: ${ZSH_HIGHLIGHT_STYLES[bracket-level-3]:=fg=magenta,bold} +: ${ZSH_HIGHLIGHT_STYLES[bracket-level-4]:=fg=yellow,bold} +: ${ZSH_HIGHLIGHT_STYLES[bracket-level-5]:=fg=cyan,bold} +: ${ZSH_HIGHLIGHT_STYLES[cursor-matchingbracket]:=standout} + +# Whether the brackets highlighter should be called or not. +_zsh_highlight_highlighter_brackets_predicate() +{ + [[ $WIDGET == zle-line-finish ]] || _zsh_highlight_cursor_moved || _zsh_highlight_buffer_modified +} + +# Brackets highlighting function. +_zsh_highlight_highlighter_brackets_paint() +{ + local char style + local -i bracket_color_size=${#ZSH_HIGHLIGHT_STYLES[(I)bracket-level-*]} buflen=${#BUFFER} level=0 matchingpos pos + local -A levelpos lastoflevel matching + + # Find all brackets and remember which one is matching + pos=0 + for char in ${(s..)BUFFER} ; do + (( ++pos )) + case $char in + ["([{"]) + levelpos[$pos]=$((++level)) + lastoflevel[$level]=$pos + ;; + [")]}"]) + if (( level > 0 )); then + matchingpos=$lastoflevel[$level] + levelpos[$pos]=$((level--)) + if _zsh_highlight_brackets_match $matchingpos $pos; then + matching[$matchingpos]=$pos + matching[$pos]=$matchingpos + fi + else + levelpos[$pos]=-1 + fi + ;; + esac + done + + # Now highlight all found brackets + for pos in ${(k)levelpos}; do + if (( $+matching[$pos] )); then + if (( bracket_color_size )); then + _zsh_highlight_add_highlight $((pos - 1)) $pos bracket-level-$(( (levelpos[$pos] - 1) % bracket_color_size + 1 )) + fi + else + _zsh_highlight_add_highlight $((pos - 1)) $pos bracket-error + fi + done + + # If cursor is on a bracket, then highlight corresponding bracket, if any. + if [[ $WIDGET != zle-line-finish ]]; then + pos=$((CURSOR + 1)) + if (( $+levelpos[$pos] )) && (( $+matching[$pos] )); then + local -i otherpos=$matching[$pos] + _zsh_highlight_add_highlight $((otherpos - 1)) $otherpos cursor-matchingbracket + fi + fi +} + +# Helper function to differentiate type +_zsh_highlight_brackets_match() +{ + case $BUFFER[$1] in + \() [[ $BUFFER[$2] == \) ]];; + \[) [[ $BUFFER[$2] == \] ]];; + \{) [[ $BUFFER[$2] == \} ]];; + *) false;; + esac +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/cursor-matchingbracket-line-finish.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/cursor-matchingbracket-line-finish.zsh new file mode 100644 index 00000000..b2acd31d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/cursor-matchingbracket-line-finish.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +WIDGET=zle-line-finish + +BUFFER=': $foo[bar]' +CURSOR=6 # cursor is zero-based + +expected_region_highlight=( +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/cursor-matchingbracket.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/cursor-matchingbracket.zsh new file mode 100644 index 00000000..e05b4e90 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/cursor-matchingbracket.zsh @@ -0,0 +1,47 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +unsorted=1 + +ZSH_HIGHLIGHT_STYLES[bracket-level-1]= +ZSH_HIGHLIGHT_STYLES[bracket-level-2]= +ZSH_HIGHLIGHT_STYLES[bracket-level-3]= + +BUFFER=': ((( )))' +CURSOR=2 # cursor is zero-based + +expected_region_highlight=( + "3 3 bracket-level-1" + "4 4 bracket-level-2" + "5 5 bracket-level-3" + "7 7 bracket-level-3" + "8 8 bracket-level-2" + "9 9 bracket-level-1" + "9 9 cursor-matchingbracket" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/empty-styles.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/empty-styles.zsh new file mode 100644 index 00000000..e60657bc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/empty-styles.zsh @@ -0,0 +1,33 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=': (x)' + +expected_region_highlight=( +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/loop-styles.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/loop-styles.zsh new file mode 100644 index 00000000..e5cfcdf0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/loop-styles.zsh @@ -0,0 +1,53 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +unsorted=1 + +ZSH_HIGHLIGHT_STYLES[bracket-level-1]= +ZSH_HIGHLIGHT_STYLES[bracket-level-2]= +ZSH_HIGHLIGHT_STYLES[bracket-level-3]= + +BUFFER=': ({[({[(x)]})]})' + +expected_region_highlight=( + "3 3 bracket-level-1" + "4 4 bracket-level-2" + "5 5 bracket-level-3" + "6 6 bracket-level-1" + "7 7 bracket-level-2" + "8 8 bracket-level-3" + "9 9 bracket-level-1" + "11 11 bracket-level-1" + "12 12 bracket-level-3" + "13 13 bracket-level-2" + "14 14 bracket-level-1" + "15 15 bracket-level-3" + "16 16 bracket-level-2" + "17 17 bracket-level-1" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/mismatch-patentheses.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/mismatch-patentheses.zsh new file mode 100644 index 00000000..5cc588fa --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/mismatch-patentheses.zsh @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +unsorted=1 + +ZSH_HIGHLIGHT_STYLES[bracket-level-1]= +ZSH_HIGHLIGHT_STYLES[bracket-level-2]= + +BUFFER='echo ({x}]' + +expected_region_highlight=( + "6 6 bracket-error" # ( + "7 7 bracket-level-2" # { + "9 9 bracket-level-2" # } + "10 10 bracket-error" # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/near-quotes.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/near-quotes.zsh new file mode 100644 index 00000000..49f002be --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/near-quotes.zsh @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +unsorted=1 + +ZSH_HIGHLIGHT_STYLES[bracket-level-1]= +ZSH_HIGHLIGHT_STYLES[bracket-level-2]= + +BUFFER=': {"{x}"}' + +expected_region_highlight=( + "3 3 bracket-level-1" + "5 5 bracket-level-2" + "7 7 bracket-level-2" + "9 9 bracket-level-1" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/nested-parentheses.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/nested-parentheses.zsh new file mode 100644 index 00000000..21a20fb3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/nested-parentheses.zsh @@ -0,0 +1,45 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +unsorted=1 + +ZSH_HIGHLIGHT_STYLES[bracket-level-1]= +ZSH_HIGHLIGHT_STYLES[bracket-level-2]= +ZSH_HIGHLIGHT_STYLES[bracket-level-3]= + +BUFFER='echo $(echo ${(z)array})' + +expected_region_highlight=( + "7 7 bracket-level-1" # ( + "14 14 bracket-level-2" # { + "15 15 bracket-level-3" # ( + "17 17 bracket-level-3" # ) + "23 23 bracket-level-2" # } + "24 24 bracket-level-1" # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/only-error.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/only-error.zsh new file mode 100644 index 00000000..00fe557c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/only-error.zsh @@ -0,0 +1,34 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=': x)' + +expected_region_highlight=( + "4 4 bracket-error" # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/quoted-patentheses.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/quoted-patentheses.zsh new file mode 100644 index 00000000..81ee04f2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/quoted-patentheses.zsh @@ -0,0 +1,34 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='echo "foo ( bar"' + +expected_region_highlight=( +"11 11 bracket-error" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/simple-parentheses.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/simple-parentheses.zsh new file mode 100644 index 00000000..2ccfbab0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/simple-parentheses.zsh @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +unsorted=1 + +ZSH_HIGHLIGHT_STYLES[bracket-level-1]= +ZSH_HIGHLIGHT_STYLES[bracket-level-2]= + +BUFFER='echo ({x})' + +expected_region_highlight=( + "6 6 bracket-level-1" # ( + "7 7 bracket-level-2" # { + "9 9 bracket-level-2" # } + "10 10 bracket-level-1" # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/unclosed-patentheses.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/unclosed-patentheses.zsh new file mode 100644 index 00000000..d3f6560d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/unclosed-patentheses.zsh @@ -0,0 +1,41 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +unsorted=1 + +ZSH_HIGHLIGHT_STYLES[bracket-level-1]= +ZSH_HIGHLIGHT_STYLES[bracket-level-2]= + +BUFFER='echo ({x}' + +expected_region_highlight=( + "6 6 bracket-error" # ( + "7 7 bracket-level-2" # { + "9 9 bracket-level-2" # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/unclosed-patentheses2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/unclosed-patentheses2.zsh new file mode 100644 index 00000000..2c489c30 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/brackets/test-data/unclosed-patentheses2.zsh @@ -0,0 +1,40 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +unsorted=1 + +ZSH_HIGHLIGHT_STYLES[bracket-level-1]= + +BUFFER='echo {x})' + +expected_region_highlight=( + "6 6 bracket-level-1" # { + "8 8 bracket-level-1" # } + "9 9 bracket-error" # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/cursor/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/cursor/README.md new file mode 100644 index 00000000..3f87d422 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/cursor/README.md @@ -0,0 +1,24 @@ +zsh-syntax-highlighting / highlighters / cursor +----------------------------------------------- + +This is the `cursor` highlighter, that highlights the cursor. + + +### How to tweak it + +This highlighter defines the following styles: + +* `cursor` - the style for the current cursor position + +To override one of those styles, change its entry in `ZSH_HIGHLIGHT_STYLES`, +for example in `~/.zshrc`: + +```zsh +ZSH_HIGHLIGHT_STYLES[cursor]='bg=blue' +``` + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/cursor/cursor-highlighter.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/cursor/cursor-highlighter.zsh new file mode 100644 index 00000000..81633a3c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/cursor/cursor-highlighter.zsh @@ -0,0 +1,47 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2011 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + + +# Define default styles. +: ${ZSH_HIGHLIGHT_STYLES[cursor]:=standout} + +# Whether the cursor highlighter should be called or not. +_zsh_highlight_highlighter_cursor_predicate() +{ + # remove cursor highlighting when the line is finished + [[ $WIDGET == zle-line-finish ]] || _zsh_highlight_cursor_moved +} + +# Cursor highlighting function. +_zsh_highlight_highlighter_cursor_paint() +{ + [[ $WIDGET == zle-line-finish ]] && return + + _zsh_highlight_add_highlight $CURSOR $(( $CURSOR + 1 )) cursor +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/line/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/line/README.md new file mode 100644 index 00000000..f76639ee --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/line/README.md @@ -0,0 +1,24 @@ +zsh-syntax-highlighting / highlighters / line +--------------------------------------------- + +This is the `line` highlighter, that highlights the whole line. + + +### How to tweak it + +This highlighter defines the following styles: + +* `line` - the style for the whole line + +To override one of those styles, change its entry in `ZSH_HIGHLIGHT_STYLES`, +for example in `~/.zshrc`: + +```zsh +ZSH_HIGHLIGHT_STYLES[line]='bold' +``` + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/line/line-highlighter.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/line/line-highlighter.zsh new file mode 100644 index 00000000..f922dc9b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/line/line-highlighter.zsh @@ -0,0 +1,44 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2011 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + + +# Define default styles. +: ${ZSH_HIGHLIGHT_STYLES[line]:=} + +# Whether the root highlighter should be called or not. +_zsh_highlight_highlighter_line_predicate() +{ + _zsh_highlight_buffer_modified +} + +# root highlighting function. +_zsh_highlight_highlighter_line_paint() +{ + _zsh_highlight_add_highlight 0 $#BUFFER line +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/README.md new file mode 100644 index 00000000..4a27653f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/README.md @@ -0,0 +1,121 @@ +zsh-syntax-highlighting / highlighters / main +--------------------------------------------- + +This is the `main` highlighter, that highlights: + +* Commands +* Options +* Arguments +* Paths +* Strings + +This highlighter is active by default. + + +### How to tweak it + +This highlighter defines the following styles: + +* `unknown-token` - unknown tokens / errors +* `reserved-word` - shell reserved words (`if`, `for`) +* `alias` - aliases +* `suffix-alias` - suffix aliases (requires zsh 5.1.1 or newer) +* `global-alias` - global aliases +* `builtin` - shell builtin commands (`shift`, `pwd`, `zstyle`) +* `function` - function names +* `command` - command names +* `precommand` - precommand modifiers (e.g., `noglob`, `builtin`) +* `commandseparator` - command separation tokens (`;`, `&&`) +* `hashed-command` - hashed commands +* `autodirectory` - a directory name in command position when the `AUTO_CD` option is set +* `path` - existing filenames +* `path_pathseparator` - path separators in filenames (`/`); if unset, `path` is used (default) +* `path_prefix` - prefixes of existing filenames +* `path_prefix_pathseparator` - path separators in prefixes of existing filenames (`/`); if unset, `path_prefix` is used (default) +* `globbing` - globbing expressions (`*.txt`) +* `history-expansion` - history expansion expressions (`!foo` and `^foo^bar`) +* `command-substitution` - command substitutions (`$(echo foo)`) +* `command-substitution-unquoted` - an unquoted command substitution (`$(echo foo)`) +* `command-substitution-quoted` - a quoted command substitution (`"$(echo foo)"`) +* `command-substitution-delimiter` - command substitution delimiters (`$(` and `)`) +* `command-substitution-delimiter-unquoted` - an unquoted command substitution delimiters (`$(` and `)`) +* `command-substitution-delimiter-quoted` - a quoted command substitution delimiters (`"$(` and `)"`) +* `process-substitution` - process substitutions (`<(echo foo)`) +* `process-substitution-delimiter` - process substitution delimiters (`<(` and `)`) +* `arithmetic-expansion` - arithmetic expansion `$(( 42 ))`) +* `single-hyphen-option` - single-hyphen options (`-o`) +* `double-hyphen-option` - double-hyphen options (`--option`) +* `back-quoted-argument` - backtick command substitution (`` `foo` ``) +* `back-quoted-argument-unclosed` - unclosed backtick command substitution (`` `foo ``) +* `back-quoted-argument-delimiter` - backtick command substitution delimiters (`` ` ``) +* `single-quoted-argument` - single-quoted arguments (`` 'foo' ``) +* `single-quoted-argument-unclosed` - unclosed single-quoted arguments (`` 'foo ``) +* `double-quoted-argument` - double-quoted arguments (`` "foo" ``) +* `double-quoted-argument-unclosed` - unclosed double-quoted arguments (`` "foo ``) +* `dollar-quoted-argument` - dollar-quoted arguments (`` $'foo' ``) +* `dollar-quoted-argument-unclosed` - unclosed dollar-quoted arguments (`` $'foo ``) +* `rc-quote` - two single quotes inside single quotes when the `RC_QUOTES` option is set (`` 'foo''bar' ``) +* `dollar-double-quoted-argument` - parameter expansion inside double quotes (`$foo` inside `""`) +* `back-double-quoted-argument` - backslash escape sequences inside double-quoted arguments (`\"` in `"foo\"bar"`) +* `back-dollar-quoted-argument` - backslash escape sequences inside dollar-quoted arguments (`\x` in `$'\x48'`) +* `assign` - parameter assignments (`x=foo` and `x=( )`) +* `redirection` - redirection operators (`<`, `>`, etc) +* `comment` - comments, when `setopt INTERACTIVE_COMMENTS` is in effect (`echo # foo`) +* `comment` - elided parameters in command position (`$x ls` when `$x` is unset or empty) +* `named-fd` - named file descriptor (the `fd` in `echo foo {fd}>&2`) +* `numeric-fd` - numeric file descriptor (the `2` in `echo foo {fd}>&2`) +* `arg0` - a command word other than one of those enumerated above (other than a command, precommand, alias, function, or shell builtin command). +* `default` - everything else + +To override one of those styles, change its entry in `ZSH_HIGHLIGHT_STYLES`, +for example in `~/.zshrc`: + +```zsh +# Declare the variable +typeset -A ZSH_HIGHLIGHT_STYLES + +# To differentiate aliases from other command types +ZSH_HIGHLIGHT_STYLES[alias]='fg=magenta,bold' + +# To have paths colored instead of underlined +ZSH_HIGHLIGHT_STYLES[path]='fg=cyan' + +# To disable highlighting of globbing expressions +ZSH_HIGHLIGHT_STYLES[globbing]='none' +``` + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +#### Parameters + +To avoid partial path lookups on a path, add the path to the `ZSH_HIGHLIGHT_DIRS_BLACKLIST` array. + +```zsh +ZSH_HIGHLIGHT_DIRS_BLACKLIST+=(/mnt/slow_share) +``` + +### Useless trivia + +#### Forward compatibility. + +zsh-syntax-highlighting attempts to be forward-compatible with zsh. +Specifically, we attempt to facilitate highlighting _command word_ types that +had not yet been invented when this version of zsh-syntax-highlighting was +released. + +A _command word_ is something like a function name, external command name, et +cetera. (See +[Simple Commands & Pipelines in `zshmisc(1)`][zshmisc-Simple-Commands-And-Pipelines] +for a formal definition.) + +If a new _kind_ of command word is ever added to zsh — something conceptually +different than "function" and "alias" and "external command" — then command words +of that (new) kind will be highlighted by the style `arg0_$kind`, +where `$kind` is the output of `type -w` on the new kind of command word. If that +style is not defined, then the style `arg0` will be used instead. + +[zshmisc-Simple-Commands-And-Pipelines]: https://zsh.sourceforge.io/Doc/Release/Shell-Grammar.html#Simple-Commands-_0026-Pipelines + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/main-highlighter.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/main-highlighter.zsh new file mode 100644 index 00000000..f6910517 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/main-highlighter.zsh @@ -0,0 +1,1846 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + + +# Define default styles. +: ${ZSH_HIGHLIGHT_STYLES[default]:=none} +: ${ZSH_HIGHLIGHT_STYLES[unknown-token]:=fg=red,bold} +: ${ZSH_HIGHLIGHT_STYLES[reserved-word]:=fg=yellow} +: ${ZSH_HIGHLIGHT_STYLES[suffix-alias]:=fg=green,underline} +: ${ZSH_HIGHLIGHT_STYLES[global-alias]:=fg=cyan} +: ${ZSH_HIGHLIGHT_STYLES[precommand]:=fg=green,underline} +: ${ZSH_HIGHLIGHT_STYLES[commandseparator]:=none} +: ${ZSH_HIGHLIGHT_STYLES[autodirectory]:=fg=green,underline} +: ${ZSH_HIGHLIGHT_STYLES[path]:=underline} +: ${ZSH_HIGHLIGHT_STYLES[path_pathseparator]:=} +: ${ZSH_HIGHLIGHT_STYLES[path_prefix_pathseparator]:=} +: ${ZSH_HIGHLIGHT_STYLES[globbing]:=fg=blue} +: ${ZSH_HIGHLIGHT_STYLES[history-expansion]:=fg=blue} +: ${ZSH_HIGHLIGHT_STYLES[command-substitution]:=none} +: ${ZSH_HIGHLIGHT_STYLES[command-substitution-delimiter]:=fg=magenta} +: ${ZSH_HIGHLIGHT_STYLES[process-substitution]:=none} +: ${ZSH_HIGHLIGHT_STYLES[process-substitution-delimiter]:=fg=magenta} +: ${ZSH_HIGHLIGHT_STYLES[single-hyphen-option]:=none} +: ${ZSH_HIGHLIGHT_STYLES[double-hyphen-option]:=none} +: ${ZSH_HIGHLIGHT_STYLES[back-quoted-argument]:=none} +: ${ZSH_HIGHLIGHT_STYLES[back-quoted-argument-delimiter]:=fg=magenta} +: ${ZSH_HIGHLIGHT_STYLES[single-quoted-argument]:=fg=yellow} +: ${ZSH_HIGHLIGHT_STYLES[double-quoted-argument]:=fg=yellow} +: ${ZSH_HIGHLIGHT_STYLES[dollar-quoted-argument]:=fg=yellow} +: ${ZSH_HIGHLIGHT_STYLES[rc-quote]:=fg=cyan} +: ${ZSH_HIGHLIGHT_STYLES[dollar-double-quoted-argument]:=fg=cyan} +: ${ZSH_HIGHLIGHT_STYLES[back-double-quoted-argument]:=fg=cyan} +: ${ZSH_HIGHLIGHT_STYLES[back-dollar-quoted-argument]:=fg=cyan} +: ${ZSH_HIGHLIGHT_STYLES[assign]:=none} +: ${ZSH_HIGHLIGHT_STYLES[redirection]:=fg=yellow} +: ${ZSH_HIGHLIGHT_STYLES[comment]:=fg=black,bold} +: ${ZSH_HIGHLIGHT_STYLES[named-fd]:=none} +: ${ZSH_HIGHLIGHT_STYLES[numeric-fd]:=none} +: ${ZSH_HIGHLIGHT_STYLES[arg0]:=fg=green} + +# Whether the highlighter should be called or not. +_zsh_highlight_highlighter_main_predicate() +{ + # may need to remove path_prefix highlighting when the line ends + [[ $WIDGET == zle-line-finish ]] || _zsh_highlight_buffer_modified +} + +# Helper to deal with tokens crossing line boundaries. +_zsh_highlight_main_add_region_highlight() { + integer start=$1 end=$2 + shift 2 + + if (( $#in_alias )); then + [[ $1 == unknown-token ]] && alias_style=unknown-token + return + fi + if (( in_param )); then + if [[ $1 == unknown-token ]]; then + param_style=unknown-token + fi + if [[ -n $param_style ]]; then + return + fi + param_style=$1 + return + fi + + # The calculation was relative to $buf but region_highlight is relative to $BUFFER. + (( start += buf_offset )) + (( end += buf_offset )) + + list_highlights+=($start $end $1) +} + +_zsh_highlight_main_add_many_region_highlights() { + for 1 2 3; do + _zsh_highlight_main_add_region_highlight $1 $2 $3 + done +} + +_zsh_highlight_main_calculate_fallback() { + local -A fallback_of; fallback_of=( + alias arg0 + suffix-alias arg0 + global-alias dollar-double-quoted-argument + builtin arg0 + function arg0 + command arg0 + precommand arg0 + hashed-command arg0 + autodirectory arg0 + arg0_\* arg0 + + # TODO: Maybe these? — + # named-fd file-descriptor + # numeric-fd file-descriptor + + path_prefix path + # The path separator fallback won't ever be used, due to the optimisation + # in _zsh_highlight_main_highlighter_highlight_path_separators(). + path_pathseparator path + path_prefix_pathseparator path_prefix + + single-quoted-argument{-unclosed,} + double-quoted-argument{-unclosed,} + dollar-quoted-argument{-unclosed,} + back-quoted-argument{-unclosed,} + + command-substitution{-quoted,,-unquoted,} + command-substitution-delimiter{-quoted,,-unquoted,} + + command-substitution{-delimiter,} + process-substitution{-delimiter,} + back-quoted-argument{-delimiter,} + ) + local needle=$1 value + reply=($1) + while [[ -n ${value::=$fallback_of[(k)$needle]} ]]; do + unset "fallback_of[$needle]" # paranoia against infinite loops + reply+=($value) + needle=$value + done +} + +# Get the type of a command. +# +# Uses the zsh/parameter module if available to avoid forks, and a +# wrapper around 'type -w' as fallback. +# +# If $2 is 0, do not consider aliases. +# +# The result will be stored in REPLY. +_zsh_highlight_main__type() { + integer -r aliases_allowed=${2-1} + # We won't cache replies of anything that exists as an alias at all, to + # ensure the cached value is correct regardless of $aliases_allowed. + # + # ### We probably _should_ cache them in a cache that's keyed on the value of + # ### $aliases_allowed, on the assumption that aliases are the common case. + integer may_cache=1 + + # Cache lookup + if (( $+_zsh_highlight_main__command_type_cache )); then + REPLY=$_zsh_highlight_main__command_type_cache[(e)$1] + if [[ -n "$REPLY" ]]; then + return + fi + fi + + # Main logic + if (( $#options_to_set )); then + setopt localoptions $options_to_set; + fi + unset REPLY + if zmodload -e zsh/parameter; then + if (( $+aliases[(e)$1] )); then + may_cache=0 + fi + if (( ${+galiases[(e)$1]} )) && (( aliases_allowed )); then + REPLY='global alias' + elif (( $+aliases[(e)$1] )) && (( aliases_allowed )); then + REPLY=alias + elif [[ $1 == *.* && -n ${1%.*} ]] && (( $+saliases[(e)${1##*.}] )); then + REPLY='suffix alias' + elif (( $reswords[(Ie)$1] )); then + REPLY=reserved + elif (( $+functions[(e)$1] )); then + REPLY=function + elif (( $+builtins[(e)$1] )); then + REPLY=builtin + elif (( $+commands[(e)$1] )); then + REPLY=command + # None of the special hashes had a match, so fall back to 'type -w', for + # forward compatibility with future versions of zsh that may add new command + # types. + # + # zsh 5.2 and older have a bug whereby running 'type -w ./sudo' implicitly + # runs 'hash ./sudo=/usr/local/bin/./sudo' (assuming /usr/local/bin/sudo + # exists and is in $PATH). Avoid triggering the bug, at the expense of + # falling through to the $() below, incurring a fork. (Issue #354.) + # + # The first disjunct mimics the isrelative() C call from the zsh bug. + elif { [[ $1 != */* ]] || is-at-least 5.3 } && + # Add a subshell to avoid a zsh upstream bug; see issue #606. + # ### Remove the subshell when we stop supporting zsh 5.7.1 (I assume 5.8 will have the bugfix). + ! (builtin type -w -- "$1") >/dev/null 2>&1; then + REPLY=none + fi + fi + if ! (( $+REPLY )); then + # zsh/parameter not available or had no matches. + # + # Note that 'type -w' will run 'rehash' implicitly. + # + # We 'unalias' in a subshell, so the parent shell is not affected. + # + # The colon command is there just to avoid a command substitution that + # starts with an arithmetic expression [«((…))» as the first thing inside + # «$(…)»], which is area that has had some parsing bugs before 5.6 + # (approximately). + REPLY="${$(:; (( aliases_allowed )) || unalias -- "$1" 2>/dev/null; LC_ALL=C builtin type -w -- "$1" 2>/dev/null)##*: }" + if [[ $REPLY == 'alias' ]]; then + may_cache=0 + fi + fi + + # Cache population + if (( may_cache )) && (( $+_zsh_highlight_main__command_type_cache )); then + _zsh_highlight_main__command_type_cache[(e)$1]=$REPLY + fi + [[ -n $REPLY ]] + return $? +} + +# Checks whether $1 is something that can be run. +# +# Return 0 if runnable, 1 if not runnable, 2 if trouble. +_zsh_highlight_main__is_runnable() { + if _zsh_highlight_main__type "$1"; then + [[ $REPLY != none ]] + else + return 2 + fi +} + +# Check whether the first argument is a redirection operator token. +# Report result via the exit code. +_zsh_highlight_main__is_redirection() { + # A redirection operator token: + # - starts with an optional single-digit number; + # - then, has a '<' or '>' character; + # - is not a process substitution [<(...) or >(...)]. + # - is not a numeric glob <-> + [[ $1 == (<0-9>|)(\<|\>)* ]] && [[ $1 != (\<|\>)$'\x28'* ]] && [[ $1 != *'<'*'-'*'>'* ]] +} + +# Resolve alias. +# +# Takes a single argument. +# +# The result will be stored in REPLY. +_zsh_highlight_main__resolve_alias() { + if zmodload -e zsh/parameter; then + REPLY=${aliases[$arg]} + else + REPLY="${"$(alias -- $arg)"#*=}" + fi +} + +# Return true iff $1 is a global alias +_zsh_highlight_main__is_global_alias() { + if zmodload -e zsh/parameter; then + (( ${+galiases[$arg]} )) + elif [[ $arg == '='* ]]; then + # avoid running into «alias -L '=foo'» erroring out with 'bad assignment' + return 1 + else + alias -L -g -- "$1" >/dev/null + fi +} + +# Check that the top of $braces_stack has the expected value. If it does, set +# the style according to $2; otherwise, set style=unknown-token. +# +# $1: character expected to be at the top of $braces_stack +# $2: optional assignment to style it if matches +# return value is 0 if there is a match else 1 +_zsh_highlight_main__stack_pop() { + if [[ $braces_stack[1] == $1 ]]; then + braces_stack=${braces_stack:1} + if (( $+2 )); then + style=$2 + fi + return 0 + else + style=unknown-token + return 1 + fi +} + +# Main syntax highlighting function. +_zsh_highlight_highlighter_main_paint() +{ + setopt localoptions extendedglob + + # At the PS3 prompt and in vared, highlight nothing. + # + # (We can't check this in _zsh_highlight_highlighter_main_predicate because + # if the predicate returns false, the previous value of region_highlight + # would be reused.) + if [[ $CONTEXT == (select|vared) ]]; then + return + fi + + typeset -a ZSH_HIGHLIGHT_TOKENS_COMMANDSEPARATOR + typeset -a ZSH_HIGHLIGHT_TOKENS_CONTROL_FLOW + local -a options_to_set reply # used in callees + local REPLY + + # $flags_with_argument is a set of letters, corresponding to the option letters + # that would be followed by a colon in a getopts specification. + local flags_with_argument + # $flags_sans_argument is a set of letters, corresponding to the option letters + # that wouldn't be followed by a colon in a getopts specification. + local flags_sans_argument + # $flags_solo is a set of letters, corresponding to option letters that, if + # present, mean the precommand will not be acting as a precommand, i.e., will + # not be followed by a :start: word. + local flags_solo + # $precommand_options maps precommand name to values of $flags_with_argument, + # $flags_sans_argument, and flags_solo for that precommand, joined by a + # colon. (The value is NOT a getopt(3) spec, although it resembles one.) + # + # Currently, setting $flags_sans_argument is only important for commands that + # have a non-empty $flags_with_argument; see test-data/precommand4.zsh. + local -A precommand_options + precommand_options=( + # Precommand modifiers as of zsh 5.6.2 cf. zshmisc(1). + '-' '' + 'builtin' '' + 'command' :pvV + 'exec' a:cl + 'noglob' '' + # 'time' and 'nocorrect' shouldn't be added here; they're reserved words, not precommands. + + # miscellaneous commands + 'doas' aCu:Lns # as of OpenBSD's doas(1) dated September 4, 2016 + 'nice' n: # as of current POSIX spec + 'pkexec' '' # doesn't take short options; immune to #121 because it's usually not passed --option flags + # Not listed: -h, which has two different meanings. + 'sudo' Cgprtu:AEHPSbilns:eKkVv # as of sudo 1.8.21p2 + 'stdbuf' ioe: + 'eatmydata' '' + 'catchsegv' '' + 'nohup' '' + 'setsid' :wc + 'env' u:i + 'ionice' cn:t:pPu # util-linux 2.33.1-0.1 + 'strace' IbeaosXPpEuOS:ACdfhikqrtTvVxyDc # strace 4.26-0.2 + 'proxychains' f:q # proxychains 4.4.0 + 'torsocks' idq:upaP # Torsocks 2.3.0 + 'torify' idq:upaP # Torsocks 2.3.0 + 'ssh-agent' aEPt:csDd:k # As of OpenSSH 8.1p1 + 'tabbed' gnprtTuU:cdfhs:v # suckless-tools v44 + 'chronic' :ev # moreutils 0.62-1 + 'ifne' :n # moreutils 0.62-1 + 'grc' :se # grc - a "generic colouriser" (that's their spelling, not mine) + 'cpulimit' elp:ivz # cpulimit 0.2 + ) + # Commands that would need to skip one positional argument: + # flock + # ssh + # _wanted (skip two) + + if [[ $zsyh_user_options[ignorebraces] == on || ${zsyh_user_options[ignoreclosebraces]:-off} == on ]]; then + local right_brace_is_recognised_everywhere=false + else + local right_brace_is_recognised_everywhere=true + fi + + if [[ $zsyh_user_options[pathdirs] == on ]]; then + options_to_set+=( PATH_DIRS ) + fi + + ZSH_HIGHLIGHT_TOKENS_COMMANDSEPARATOR=( + '|' '||' ';' '&' '&&' + $'\n' # ${(z)} returns ';' but we convert it to $'\n' + '|&' + '&!' '&|' + # ### 'case' syntax, but followed by a pattern, not by a command + # ';;' ';&' ';|' + ) + + # Tokens that, at (naively-determined) "command position", are followed by + # a de jure command position. All of these are reserved words. + ZSH_HIGHLIGHT_TOKENS_CONTROL_FLOW=( + $'\x7b' # block + $'\x28' # subshell + '()' # anonymous function + 'while' + 'until' + 'if' + 'then' + 'elif' + 'else' + 'do' + 'time' + 'coproc' + '!' # reserved word; unrelated to $histchars[1] + ) + + if (( $+X_ZSH_HIGHLIGHT_DIRS_BLACKLIST )); then + print >&2 'zsh-syntax-highlighting: X_ZSH_HIGHLIGHT_DIRS_BLACKLIST is deprecated. Please use ZSH_HIGHLIGHT_DIRS_BLACKLIST.' + ZSH_HIGHLIGHT_DIRS_BLACKLIST=($X_ZSH_HIGHLIGHT_DIRS_BLACKLIST) + unset X_ZSH_HIGHLIGHT_DIRS_BLACKLIST + fi + + _zsh_highlight_main_highlighter_highlight_list -$#PREBUFFER '' 1 "$PREBUFFER$BUFFER" + + # end is a reserved word + local start end_ style + for start end_ style in $reply; do + (( start >= end_ )) && { print -r -- >&2 "zsh-syntax-highlighting: BUG: _zsh_highlight_highlighter_main_paint: start($start) >= end($end_)"; return } + (( end_ <= 0 )) && continue + (( start < 0 )) && start=0 # having start<0 is normal with e.g. multiline strings + _zsh_highlight_main_calculate_fallback $style + _zsh_highlight_add_highlight $start $end_ $reply + done +} + +# Try to expand $1, if it's possible to do so safely. +# +# Uses two parameters from the caller: $parameter_name_pattern and $res. +# +# If expansion was done, set $reply to the expansion and return true. +# Otherwise, return false. +_zsh_highlight_main_highlighter__try_expand_parameter() +{ + local arg="$1" + unset reply + { + # ### For now, expand just '$foo' or '${foo}', possibly with braces, but with + # ### no other features of the parameter expansion syntax. (No ${(x)foo}, + # ### no ${foo[x]}, no ${foo:-x}.) + { + local -a match mbegin mend + local MATCH; integer MBEGIN MEND + local parameter_name + local -a words + if [[ $arg[1] != '$' ]]; then + return 1 + fi + if [[ ${arg[2]} == '{' ]] && [[ ${arg[-1]} == '}' ]]; then + parameter_name=${${arg:2}%?} + else + parameter_name=${arg:1} + fi + if [[ $res == none ]] && + [[ ${parameter_name} =~ ^${~parameter_name_pattern}$ ]] && + [[ ${(tP)MATCH} != *special* ]] + then + # Set $arg and update $res. + case ${(tP)MATCH} in + (*array*|*assoc*) + words=( ${(P)MATCH} ) + ;; + ("") + # not set + words=( ) + ;; + (*) + # scalar, presumably + if [[ $zsyh_user_options[shwordsplit] == on ]]; then + words=( ${(P)=MATCH} ) + else + words=( ${(P)MATCH} ) + fi + ;; + esac + reply=( "${words[@]}" ) + else + return 1 + fi + } + } +} + +# $1 is the offset of $4 from the parent buffer. Added to the returned highlights. +# $2 is the initial braces_stack (for a closing paren). +# $3 is 1 if $4 contains the end of $BUFFER, else 0. +# $4 is the buffer to highlight. +# Returns: +# $REPLY: $buf[REPLY] is the last character parsed. +# $reply is an array of region_highlight additions. +# exit code is 0 if the braces_stack is empty, 1 otherwise. +_zsh_highlight_main_highlighter_highlight_list() +{ + integer start_pos end_pos=0 buf_offset=$1 has_end=$3 + # alias_style is the style to apply to an alias once $#in_alias == 0 + # Usually 'alias' but set to 'unknown-token' if any word expanded from + # the alias would be highlighted as unknown-token + # param_style is analogous for parameter expansions + local alias_style param_style last_arg arg buf=$4 highlight_glob=true saw_assignment=false style + local in_array_assignment=false # true between 'a=(' and the matching ')' + # in_alias is an array of integers with each element equal to the number + # of shifts needed until arg=args[1] pops an arg from the next level up + # alias or from BUFFER. + # in_param is analogous for parameter expansions + integer in_param=0 len=$#buf + local -a in_alias match mbegin mend list_highlights + # seen_alias is a map of aliases already seen to avoid loops like alias a=b b=a + local -A seen_alias + # Pattern for parameter names + readonly parameter_name_pattern='([A-Za-z_][A-Za-z0-9_]*|[0-9]+)' + list_highlights=() + + # "R" for round + # "Q" for square + # "Y" for curly + # "T" for [[ ]] + # "S" for $( ), =( ), <( ), >( ) + # "D" for do/done + # "$" for 'end' (matches 'foreach' always; also used with cshjunkiequotes in repeat/while) + # "?" for 'if'/'fi'; also checked by 'elif'/'else' + # ":" for 'then' + local braces_stack=$2 + + # State machine + # + # The states are: + # - :start: Command word + # - :start_of_pipeline: Start of a 'pipeline' as defined in zshmisc(1). + # Only valid when :start: is present + # - :sudo_opt: A leading-dash option to a precommand, whether it takes an + # argument or not. (Example: sudo's "-u" or "-i".) + # - :sudo_arg: The argument to a precommand's leading-dash option, + # when given as a separate word; i.e., "foo" in "-u foo" (two + # words) but not in "-ufoo" (one word). + # Note: :sudo_opt: and :sudo_arg: are used for any precommand + # declared in ${precommand_options}, not just for sudo(8). + # The naming is historical. + # - :regular: "Not a command word", and command delimiters are permitted. + # Mainly used to detect premature termination of commands. + # - :always: The word 'always' in the «{ foo } always { bar }» syntax. + # + # When the kind of a word is not yet known, $this_word / $next_word may contain + # multiple states. For example, after "sudo -i", the next word may be either + # another --flag or a command name, hence the state would include both ':start:' + # and ':sudo_opt:'. + # + # The tokens are always added with both leading and trailing colons to serve as + # word delimiters (an improvised array); [[ $x == *':foo:'* ]] and x=${x//:foo:/} + # will DTRT regardless of how many elements or repetitions $x has. + # + # Handling of redirections: upon seeing a redirection token, we must stall + # the current state --- that is, the value of $this_word --- for two iterations + # (one for the redirection operator, one for the word following it representing + # the redirection target). Therefore, we set $in_redirection to 2 upon seeing a + # redirection operator, decrement it each iteration, and stall the current state + # when it is non-zero. Thus, upon reaching the next word (the one that follows + # the redirection operator and target), $this_word will still contain values + # appropriate for the word immediately following the word that preceded the + # redirection operator. + # + # The "the previous word was a redirection operator" state is not communicated + # to the next iteration via $next_word/$this_word as usual, but via + # $in_redirection. The value of $next_word from the iteration that processed + # the operator is discarded. + # + # $in_redirection is currently used for: + # - comments + # - aliases + # - redirections + # - parameter elision in command position + # - 'repeat' loops + # + local this_word next_word=':start::start_of_pipeline:' + integer in_redirection + # Processing buffer + local proc_buf="$buf" + local -a args + if [[ $zsyh_user_options[interactivecomments] == on ]]; then + args=(${(zZ+c+)buf}) + else + args=(${(z)buf}) + fi + + # Special case: $(<*) isn't globbing. + if [[ $braces_stack == 'S' ]] && (( $+args[3] && ! $+args[4] )) && [[ $args[3] == $'\x29' ]] && + [[ $args[1] == *'<'* ]] && _zsh_highlight_main__is_redirection $args[1]; then + highlight_glob=false + fi + + while (( $#args )); do + last_arg=$arg + arg=$args[1] + shift args + if (( $#in_alias )); then + (( in_alias[1]-- )) + # Remove leading 0 entries + in_alias=($in_alias[$in_alias[(i)<1->],-1]) + if (( $#in_alias == 0 )); then + seen_alias=() + # start_pos and end_pos are of the alias (previous $arg) here + _zsh_highlight_main_add_region_highlight $start_pos $end_pos $alias_style + else + # We can't unset keys that contain special characters (] \ and some others). + # More details: https://www.zsh.org/workers/43269 + (){ + local alias_name + for alias_name in ${(k)seen_alias[(R)<$#in_alias->]}; do + seen_alias=("${(@kv)seen_alias[(I)^$alias_name]}") + done + } + fi + fi + if (( in_param )); then + (( in_param-- )) + if (( in_param == 0 )); then + # start_pos and end_pos are of the '$foo' word (previous $arg) here + _zsh_highlight_main_add_region_highlight $start_pos $end_pos $param_style + param_style="" + fi + fi + + # Initialize this_word and next_word. + if (( in_redirection == 0 )); then + this_word=$next_word + next_word=':regular:' + elif (( !in_param )); then + # Stall $next_word. + (( --in_redirection )) + fi + + # Initialize per-"simple command" [zshmisc(1)] variables: + # + # $style how to highlight $arg + # $in_array_assignment boolean flag for "between '(' and ')' of array assignment" + # $highlight_glob boolean flag for "'noglob' is in effect" + # $saw_assignment boolean flag for "was preceded by an assignment" + # + style=unknown-token + if [[ $this_word == *':start:'* ]]; then + in_array_assignment=false + if [[ $arg == 'noglob' ]]; then + highlight_glob=false + fi + fi + + if (( $#in_alias == 0 && in_param == 0 )); then + # Compute the new $start_pos and $end_pos, skipping over whitespace in $buf. + [[ "$proc_buf" = (#b)(#s)(''([ $'\t']|[\\]$'\n')#)(?|)* ]] + # The first, outer parenthesis + integer offset="${#match[1]}" + (( start_pos = end_pos + offset )) + (( end_pos = start_pos + $#arg )) + + # The zsh lexer considers ';' and newline to be the same token, so + # ${(z)} converts all newlines to semicolons. Convert them back here to + # make later processing simpler. + [[ $arg == ';' && ${match[3]} == $'\n' ]] && arg=$'\n' + + # Compute the new $proc_buf. We advance it + # (chop off characters from the beginning) + # beyond what end_pos points to, by skipping + # as many characters as end_pos was advanced. + # + # end_pos was advanced by $offset (via start_pos) + # and by $#arg. Note the `start_pos=$end_pos` + # below. + # + # As for the [,len]. We could use [,len-start_pos+offset] + # here, but to make it easier on eyes, we use len and + # rely on the fact that Zsh simply handles that. The + # length of proc_buf is len-start_pos+offset because + # we're chopping it to match current start_pos, so its + # length matches the previous value of start_pos. + # + # Why [,-1] is slower than [,length] isn't clear. + proc_buf="${proc_buf[offset + $#arg + 1,len]}" + fi + + # Handle the INTERACTIVE_COMMENTS option. + # + # We use the (Z+c+) flag so the entire comment is presented as one token in $arg. + if [[ $zsyh_user_options[interactivecomments] == on && $arg[1] == $histchars[3] ]]; then + if [[ $this_word == *(':regular:'|':start:')* ]]; then + style=comment + else + style=unknown-token # prematurely terminated + fi + _zsh_highlight_main_add_region_highlight $start_pos $end_pos $style + # Stall this arg + in_redirection=1 + continue + fi + + if [[ $this_word == *':start:'* ]] && ! (( in_redirection )); then + # Expand aliases. + # An alias is ineligible for expansion while it's being expanded (see #652/#653). + _zsh_highlight_main__type "$arg" "$(( ! ${+seen_alias[$arg]} ))" + local res="$REPLY" + if [[ $res == "alias" ]]; then + # Mark insane aliases as unknown-token (cf. #263). + if [[ $arg == ?*=* ]]; then + _zsh_highlight_main_add_region_highlight $start_pos $end_pos unknown-token + continue + fi + seen_alias[$arg]=$#in_alias + _zsh_highlight_main__resolve_alias $arg + local -a alias_args + # Elision is desired in case alias x='' + if [[ $zsyh_user_options[interactivecomments] == on ]]; then + alias_args=(${(zZ+c+)REPLY}) + else + alias_args=(${(z)REPLY}) + fi + args=( $alias_args $args ) + if (( $#in_alias == 0 )); then + alias_style=alias + else + # Transfer the count of this arg to the new element about to be appended. + (( in_alias[1]-- )) + fi + # Add one because we will in_alias[1]-- on the next loop iteration so + # this iteration should be considered in in_alias as well + in_alias=( $(($#alias_args + 1)) $in_alias ) + (( in_redirection++ )) # Stall this arg + continue + else + _zsh_highlight_main_highlighter_expand_path $arg + _zsh_highlight_main__type "$REPLY" 0 + res="$REPLY" + fi + fi + + # Analyse the current word. + if _zsh_highlight_main__is_redirection $arg ; then + if (( in_redirection == 1 )); then + # Two consecutive redirection operators is an error. + _zsh_highlight_main_add_region_highlight $start_pos $end_pos unknown-token + else + in_redirection=2 + _zsh_highlight_main_add_region_highlight $start_pos $end_pos redirection + fi + continue + elif [[ $arg == '{'${~parameter_name_pattern}'}' ]] && _zsh_highlight_main__is_redirection $args[1]; then + # named file descriptor: {foo}>&2 + in_redirection=3 + _zsh_highlight_main_add_region_highlight $start_pos $end_pos named-fd + continue + fi + + # Expand parameters. + if (( ! in_param )) && _zsh_highlight_main_highlighter__try_expand_parameter "$arg"; then + # That's not entirely correct --- if the parameter's value happens to be a reserved + # word, the parameter expansion will be highlighted as a reserved word --- but that + # incorrectness is outweighed by the usability improvement of permitting the use of + # parameters that refer to commands, functions, and builtins. + () { + local -a words; words=( "${reply[@]}" ) + if (( $#words == 0 )) && (( ! in_redirection )); then + # Parameter elision is happening + (( ++in_redirection )) + _zsh_highlight_main_add_region_highlight $start_pos $end_pos comment + continue + else + (( in_param = 1 + $#words )) + args=( $words $args ) + arg=$args[1] + _zsh_highlight_main__type "$arg" 0 + res=$REPLY + fi + } + fi + + # Parse the sudo command line + if (( ! in_redirection )); then + if [[ $this_word == *':sudo_opt:'* ]]; then + if [[ -n $flags_with_argument ]] && + { + # Trenary + if [[ -n $flags_sans_argument ]] + then [[ $arg == '-'[$flags_sans_argument]#[$flags_with_argument] ]] + else [[ $arg == '-'[$flags_with_argument] ]] + fi + } then + # Flag that requires an argument + this_word=${this_word//:start:/} + next_word=':sudo_arg:' + elif [[ -n $flags_with_argument ]] && + { + # Trenary + if [[ -n $flags_sans_argument ]] + then [[ $arg == '-'[$flags_sans_argument]#[$flags_with_argument]* ]] + else [[ $arg == '-'[$flags_with_argument]* ]] + fi + } then + # Argument attached in the same word + this_word=${this_word//:start:/} + next_word+=':start:' + next_word+=':sudo_opt:' + elif [[ -n $flags_sans_argument ]] && + [[ $arg == '-'[$flags_sans_argument]# ]]; then + # Flag that requires no argument + this_word=':sudo_opt:' + next_word+=':start:' + next_word+=':sudo_opt:' + elif [[ -n $flags_solo ]] && + { + # Trenary + if [[ -n $flags_sans_argument ]] + then [[ $arg == '-'[$flags_sans_argument]#[$flags_solo]* ]] + else [[ $arg == '-'[$flags_solo]* ]] + fi + } then + # Solo flags + this_word=':sudo_opt:' + next_word=':regular:' # no :start:, nor :sudo_opt: since we don't know whether the solo flag takes an argument or not + elif [[ $arg == '-'* ]]; then + # Unknown flag. We don't know whether it takes an argument or not, + # so modify $next_word as we do for flags that require no argument. + # With that behaviour, if the flag in fact takes no argument we'll + # highlight the inner command word correctly, and if it does take an + # argument we'll highlight the command word correctly if the argument + # was given in the same shell word as the flag (as in '-uphy1729' or + # '--user=phy1729' without spaces). + this_word=':sudo_opt:' + next_word+=':start:' + next_word+=':sudo_opt:' + else + # Not an option flag; nothing to do. (If the command line is + # syntactically valid, ${this_word//:sudo_opt:/} should be + # non-empty now.) + this_word=${this_word//:sudo_opt:/} + fi + elif [[ $this_word == *':sudo_arg:'* ]]; then + next_word+=':sudo_opt:' + next_word+=':start:' + fi + fi + + # The Great Fork: is this a command word? Is this a non-command word? + if [[ -n ${(M)ZSH_HIGHLIGHT_TOKENS_COMMANDSEPARATOR:#"$arg"} ]] && + [[ $braces_stack != *T* || $arg != ('||'|'&&') ]]; then + + # First, determine the style of the command separator itself. + if _zsh_highlight_main__stack_pop T || _zsh_highlight_main__stack_pop Q; then + # Missing closing square bracket(s) + style=unknown-token + elif $in_array_assignment; then + case $arg in + # Literal newlines are just fine. + ($'\n') style=commandseparator;; + # Semicolons are parsed the same way as literal newlines. Nevertheless, + # highlight them as errors since they're probably unintended. Compare + # issue #691. + (';') style=unknown-token;; + # Other command separators aren't allowed. + (*) style=unknown-token;; + esac + elif [[ $this_word == *':regular:'* ]]; then + style=commandseparator + elif [[ $this_word == *':start:'* ]] && [[ $arg == $'\n' ]]; then + style=commandseparator + elif [[ $this_word == *':start:'* ]] && [[ $arg == ';' ]] && (( $#in_alias )); then + style=commandseparator + else + # Empty commands (semicolon follows nothing) are valid syntax. + # However, in interactive use they are likely to be erroneous; + # therefore, we highlight them as errors. + # + # Alias definitions are exempted from this check to allow multiline aliases + # with explicit (redundant) semicolons: «alias foo=$'bar;\nbaz'» (issue #677). + # + # See also #691 about possibly changing the style used here. + style=unknown-token + fi + + # Second, determine the style of next_word. + if [[ $arg == $'\n' ]] && $in_array_assignment; then + # literal newline inside an array assignment + next_word=':regular:' + elif [[ $arg == ';' ]] && $in_array_assignment; then + # literal semicolon inside an array assignment + next_word=':regular:' + else + next_word=':start:' + highlight_glob=true + saw_assignment=false + (){ + local alias_name + for alias_name in ${(k)seen_alias[(R)<$#in_alias->]}; do + # We can't unset keys that contain special characters (] \ and some others). + # More details: https://www.zsh.org/workers/43269 + seen_alias=("${(@kv)seen_alias[(I)^$alias_name]}") + done + } + if [[ $arg != '|' && $arg != '|&' ]]; then + next_word+=':start_of_pipeline:' + fi + fi + + elif ! (( in_redirection)) && [[ $this_word == *':always:'* && $arg == 'always' ]]; then + # try-always construct + style=reserved-word # de facto a reserved word, although not de jure + highlight_glob=true + saw_assignment=false + next_word=':start::start_of_pipeline:' # only left brace is allowed, apparently + elif ! (( in_redirection)) && [[ $this_word == *':start:'* ]]; then # $arg is the command word + if (( ${+precommand_options[$arg]} )) && _zsh_highlight_main__is_runnable $arg; then + style=precommand + () { + set -- "${(@s.:.)precommand_options[$arg]}" + flags_with_argument=$1 + flags_sans_argument=$2 + flags_solo=$3 + } + next_word=${next_word//:regular:/} + next_word+=':sudo_opt:' + next_word+=':start:' + if [[ $arg == 'exec' || $arg == 'env' ]]; then + # To allow "exec 2>&1;" and "env | grep" where there's no command word + next_word+=':regular:' + fi + else + case $res in + (reserved) # reserved word + style=reserved-word + # Match braces and handle special cases. + case $arg in + (time|nocorrect) + next_word=${next_word//:regular:/} + next_word+=':start:' + ;; + ($'\x7b') + braces_stack='Y'"$braces_stack" + ;; + ($'\x7d') + # We're at command word, so no need to check $right_brace_is_recognised_everywhere + _zsh_highlight_main__stack_pop 'Y' reserved-word + if [[ $style == reserved-word ]]; then + next_word+=':always:' + fi + ;; + ($'\x5b\x5b') + braces_stack='T'"$braces_stack" + ;; + ('do') + braces_stack='D'"$braces_stack" + ;; + ('done') + _zsh_highlight_main__stack_pop 'D' reserved-word + ;; + ('if') + braces_stack=':?'"$braces_stack" + ;; + ('then') + _zsh_highlight_main__stack_pop ':' reserved-word + ;; + ('elif') + if [[ ${braces_stack[1]} == '?' ]]; then + braces_stack=':'"$braces_stack" + else + style=unknown-token + fi + ;; + ('else') + if [[ ${braces_stack[1]} == '?' ]]; then + : + else + style=unknown-token + fi + ;; + ('fi') + _zsh_highlight_main__stack_pop '?' + ;; + ('foreach') + braces_stack='$'"$braces_stack" + ;; + ('end') + _zsh_highlight_main__stack_pop '$' reserved-word + ;; + ('repeat') + # skip the repeat-count word + in_redirection=2 + # The redirection mechanism assumes $this_word describes the word + # following the redirection. Make it so. + # + # That word can be a command word with shortloops (`repeat 2 ls`) + # or a command separator (`repeat 2; ls` or `repeat 2; do ls; done`). + # + # The repeat-count word will be handled like a redirection target. + this_word=':start::regular:' + ;; + ('!') + if [[ $this_word != *':start_of_pipeline:'* ]]; then + style=unknown-token + else + # '!' reserved word at start of pipeline; style already set above + fi + ;; + esac + if $saw_assignment && [[ $style != unknown-token ]]; then + style=unknown-token + fi + ;; + ('suffix alias') + style=suffix-alias + ;; + ('global alias') + style=global-alias + ;; + (alias) :;; + (builtin) style=builtin + [[ $arg == $'\x5b' ]] && braces_stack='Q'"$braces_stack" + ;; + (function) style=function;; + (command) style=command;; + (hashed) style=hashed-command;; + (none) if (( ! in_param )) && _zsh_highlight_main_highlighter_check_assign; then + _zsh_highlight_main_add_region_highlight $start_pos $end_pos assign + local i=$(( arg[(i)=] + 1 )) + saw_assignment=true + if [[ $arg[i] == '(' ]]; then + in_array_assignment=true + _zsh_highlight_main_add_region_highlight start_pos+i-1 start_pos+i reserved-word + else + # assignment to a scalar parameter. + # (For array assignments, the command doesn't start until the ")" token.) + # + # Discard :start_of_pipeline:, if present, as '!' is not valid + # after assignments. + next_word+=':start:' + if (( i <= $#arg )); then + () { + local highlight_glob=false + [[ $zsyh_user_options[globassign] == on ]] && highlight_glob=true + _zsh_highlight_main_highlighter_highlight_argument $i + } + fi + fi + continue + elif (( ! in_param )) && + [[ $arg[0,1] = $histchars[0,1] ]] && (( $#arg[0,2] == 2 )); then + style=history-expansion + elif (( ! in_param )) && + [[ $arg[0,1] == $histchars[2,2] ]]; then + style=history-expansion + elif (( ! in_param )) && + ! $saw_assignment && + [[ $arg[1,2] == '((' ]]; then + # Arithmetic evaluation. + # + # Note: prior to zsh-5.1.1-52-g4bed2cf (workers/36669), the ${(z)...} + # splitter would only output the '((' token if the matching '))' had + # been typed. Therefore, under those versions of zsh, BUFFER="(( 42" + # would be highlighted as an error until the matching "))" are typed. + # + # We highlight just the opening parentheses, as a reserved word; this + # is how [[ ... ]] is highlighted, too. + _zsh_highlight_main_add_region_highlight $start_pos $((start_pos + 2)) reserved-word + if [[ $arg[-2,-1] == '))' ]]; then + _zsh_highlight_main_add_region_highlight $((end_pos - 2)) $end_pos reserved-word + fi + continue + elif (( ! in_param )) && + [[ $arg == '()' ]]; then + # anonymous function + style=reserved-word + elif (( ! in_param )) && + ! $saw_assignment && + [[ $arg == $'\x28' ]]; then + # subshell + style=reserved-word + braces_stack='R'"$braces_stack" + elif (( ! in_param )) && + [[ $arg == $'\x29' ]]; then + # end of subshell or command substitution + if _zsh_highlight_main__stack_pop 'S'; then + REPLY=$start_pos + reply=($list_highlights) + return 0 + fi + _zsh_highlight_main__stack_pop 'R' reserved-word + else + if _zsh_highlight_main_highlighter_check_path $arg 1; then + style=$REPLY + else + style=unknown-token + fi + fi + ;; + (*) _zsh_highlight_main_add_region_highlight $start_pos $end_pos arg0_$res + continue + ;; + esac + fi + if [[ -n ${(M)ZSH_HIGHLIGHT_TOKENS_CONTROL_FLOW:#"$arg"} ]]; then + next_word=':start::start_of_pipeline:' + fi + elif _zsh_highlight_main__is_global_alias "$arg"; then # $arg is a global alias that isn't in command position + style=global-alias + else # $arg is a non-command word + case $arg in + ($'\x29') + # subshell or end of array assignment + if $in_array_assignment; then + _zsh_highlight_main_add_region_highlight $start_pos $end_pos assign + _zsh_highlight_main_add_region_highlight $start_pos $end_pos reserved-word + in_array_assignment=false + next_word+=':start:' + continue + elif (( in_redirection )); then + style=unknown-token + else + if _zsh_highlight_main__stack_pop 'S'; then + REPLY=$start_pos + reply=($list_highlights) + return 0 + fi + _zsh_highlight_main__stack_pop 'R' reserved-word + fi + ;; + ($'\x28\x29') + # possibly a function definition + if (( in_redirection )) || $in_array_assignment; then + style=unknown-token + else + if [[ $zsyh_user_options[multifuncdef] == on ]] || false # TODO: or if the previous word was a command word + then + next_word+=':start::start_of_pipeline:' + fi + style=reserved-word + fi + ;; + (*) if false; then + elif [[ $arg = $'\x7d' ]] && $right_brace_is_recognised_everywhere; then + # Parsing rule: { + # + # Additionally, `tt(})' is recognized in any position if neither the + # tt(IGNORE_BRACES) option nor the tt(IGNORE_CLOSE_BRACES) option is set. + if (( in_redirection )) || $in_array_assignment; then + style=unknown-token + else + _zsh_highlight_main__stack_pop 'Y' reserved-word + if [[ $style == reserved-word ]]; then + next_word+=':always:' + fi + fi + elif [[ $arg[0,1] = $histchars[0,1] ]] && (( $#arg[0,2] == 2 )); then + style=history-expansion + elif [[ $arg == $'\x5d\x5d' ]] && _zsh_highlight_main__stack_pop 'T' reserved-word; then + : + elif [[ $arg == $'\x5d' ]] && _zsh_highlight_main__stack_pop 'Q' builtin; then + : + else + _zsh_highlight_main_highlighter_highlight_argument 1 $(( 1 != in_redirection )) + continue + fi + ;; + esac + fi + _zsh_highlight_main_add_region_highlight $start_pos $end_pos $style + done + (( $#in_alias )) && in_alias=() _zsh_highlight_main_add_region_highlight $start_pos $end_pos $alias_style + (( in_param == 1 )) && in_param=0 _zsh_highlight_main_add_region_highlight $start_pos $end_pos $param_style + [[ "$proc_buf" = (#b)(#s)(([[:space:]]|\\$'\n')#) ]] + REPLY=$(( end_pos + ${#match[1]} - 1 )) + reply=($list_highlights) + return $(( $#braces_stack > 0 )) +} + +# Check if $arg is variable assignment +_zsh_highlight_main_highlighter_check_assign() +{ + setopt localoptions extended_glob + [[ $arg == [[:alpha:]_][[:alnum:]_]#(|\[*\])(|[+])=* ]] || + [[ $arg == [0-9]##(|[+])=* ]] +} + +_zsh_highlight_main_highlighter_highlight_path_separators() +{ + local pos style_pathsep + style_pathsep=$1_pathseparator + reply=() + [[ -z "$ZSH_HIGHLIGHT_STYLES[$style_pathsep]" || "$ZSH_HIGHLIGHT_STYLES[$1]" == "$ZSH_HIGHLIGHT_STYLES[$style_pathsep]" ]] && return 0 + for (( pos = start_pos; $pos <= end_pos; pos++ )) ; do + if [[ $BUFFER[pos] == / ]]; then + reply+=($((pos - 1)) $pos $style_pathsep) + fi + done +} + +# Check if $1 is a path. +# If yes, return 0 and in $REPLY the style to use. +# Else, return non-zero (and the contents of $REPLY is undefined). +# +# $2 should be non-zero iff we're in command position. +_zsh_highlight_main_highlighter_check_path() +{ + _zsh_highlight_main_highlighter_expand_path "$1" + local expanded_path="$REPLY" tmp_path + integer in_command_position=$2 + + if [[ $zsyh_user_options[autocd] == on ]]; then + integer autocd=1 + else + integer autocd=0 + fi + + if (( in_command_position )); then + # ### Currently, this value is never returned: either it's overwritten + # ### below, or the return code is non-zero + REPLY=arg0 + else + REPLY=path + fi + + if [[ ${1[1]} == '=' && $1 == ??* && ${1[2]} != $'\x28' && $zsyh_user_options[equals] == 'on' && $expanded_path[1] != '/' ]]; then + REPLY=unknown-token # will error out if executed + return 0 + fi + + [[ -z $expanded_path ]] && return 1 + + # Check if this is a blacklisted path + if [[ $expanded_path[1] == / ]]; then + tmp_path=$expanded_path + else + tmp_path=$PWD/$expanded_path + fi + tmp_path=$tmp_path:a + + while [[ $tmp_path != / ]]; do + [[ -n ${(M)ZSH_HIGHLIGHT_DIRS_BLACKLIST:#$tmp_path} ]] && return 1 + tmp_path=$tmp_path:h + done + + if (( in_command_position )); then + if [[ -x $expanded_path ]]; then + if (( autocd )); then + if [[ -d $expanded_path ]]; then + REPLY=autodirectory + fi + return 0 + elif [[ ! -d $expanded_path ]]; then + # ### This seems unreachable for the current callers + return 0 + fi + fi + else + if [[ -L $expanded_path || -e $expanded_path ]]; then + return 0 + fi + fi + + # Search the path in CDPATH + if [[ $expanded_path != /* ]] && (( autocd || ! in_command_position )); then + # TODO: When we've dropped support for pre-5.0.6 zsh, use the *(Y1) glob qualifier here. + local cdpath_dir + for cdpath_dir in $cdpath ; do + if [[ -d "$cdpath_dir/$expanded_path" && -x "$cdpath_dir/$expanded_path" ]]; then + if (( in_command_position && autocd )); then + REPLY=autodirectory + fi + return 0 + fi + done + fi + + # If dirname($1) doesn't exist, neither does $1. + [[ ! -d ${expanded_path:h} ]] && return 1 + + # If this word ends the buffer, check if it's the prefix of a valid path. + if (( has_end && (len == end_pos) )) && + (( ! $#in_alias )) && + [[ $WIDGET != zle-line-finish ]]; then + # TODO: When we've dropped support for pre-5.0.6 zsh, use the *(Y1) glob qualifier here. + local -a tmp + if (( in_command_position )); then + # We include directories even when autocd is enabled, because those + # directories might contain executable files: e.g., BUFFER="/bi" en route + # to typing "/bin/sh". + tmp=( ${expanded_path}*(N-*,N-/) ) + else + tmp=( ${expanded_path}*(N) ) + fi + (( ${+tmp[1]} )) && REPLY=path_prefix && return 0 + fi + + # It's not a path. + return 1 +} + +# Highlight an argument and possibly special chars in quotes starting at $1 in $arg +# This command will at least highlight $1 to end_pos with the default style +# If $2 is set to 0, the argument cannot be highlighted as an option. +# +# This function currently assumes it's never called for the command word. +_zsh_highlight_main_highlighter_highlight_argument() +{ + local base_style=default i=$1 option_eligible=${2:-1} path_eligible=1 ret start style + local -a highlights + + local -a match mbegin mend + local MATCH; integer MBEGIN MEND + + case "$arg[i]" in + '%') + if [[ $arg[i+1] == '?' ]]; then + (( i += 2 )) + fi + ;; + '-') + if (( option_eligible )); then + if [[ $arg[i+1] == - ]]; then + base_style=double-hyphen-option + else + base_style=single-hyphen-option + fi + path_eligible=0 + fi + ;; + '=') + if [[ $arg[i+1] == $'\x28' ]]; then + (( i += 2 )) + _zsh_highlight_main_highlighter_highlight_list $(( start_pos + i - 1 )) S $has_end $arg[i,-1] + ret=$? + (( i += REPLY )) + highlights+=( + $(( start_pos + $1 - 1 )) $(( start_pos + i )) process-substitution + $(( start_pos + $1 - 1 )) $(( start_pos + $1 + 1 )) process-substitution-delimiter + $reply + ) + if (( ret == 0 )); then + highlights+=($(( start_pos + i - 1 )) $(( start_pos + i )) process-substitution-delimiter) + fi + fi + esac + + # This loop is a hot path. Keep it fast! + (( --i )) + while (( ++i <= $#arg )); do + i=${arg[(ib.i.)[\\\'\"\`\$\<\>\*\?]]} + case "$arg[$i]" in + "") break;; + "\\") (( i += 1 )); continue;; + "'") + _zsh_highlight_main_highlighter_highlight_single_quote $i + (( i = REPLY )) + highlights+=($reply) + ;; + '"') + _zsh_highlight_main_highlighter_highlight_double_quote $i + (( i = REPLY )) + highlights+=($reply) + ;; + '`') + _zsh_highlight_main_highlighter_highlight_backtick $i + (( i = REPLY )) + highlights+=($reply) + ;; + '$') + if [[ $arg[i+1] != "'" ]]; then + path_eligible=0 + fi + if [[ $arg[i+1] == "'" ]]; then + _zsh_highlight_main_highlighter_highlight_dollar_quote $i + (( i = REPLY )) + highlights+=($reply) + continue + elif [[ $arg[i+1] == $'\x28' ]]; then + if [[ $arg[i+2] == $'\x28' ]] && _zsh_highlight_main_highlighter_highlight_arithmetic $i; then + # Arithmetic expansion + (( i = REPLY )) + highlights+=($reply) + continue + fi + start=$i + (( i += 2 )) + _zsh_highlight_main_highlighter_highlight_list $(( start_pos + i - 1 )) S $has_end $arg[i,-1] + ret=$? + (( i += REPLY )) + highlights+=( + $(( start_pos + start - 1)) $(( start_pos + i )) command-substitution-unquoted + $(( start_pos + start - 1)) $(( start_pos + start + 1)) command-substitution-delimiter-unquoted + $reply + ) + if (( ret == 0 )); then + highlights+=($(( start_pos + i - 1)) $(( start_pos + i )) command-substitution-delimiter-unquoted) + fi + continue + fi + while [[ $arg[i+1] == [=~#+'^'] ]]; do + (( i += 1 )) + done + if [[ $arg[i+1] == [*@#?$!-] ]]; then + (( i += 1 )) + fi;; + [\<\>]) + if [[ $arg[i+1] == $'\x28' ]]; then # \x28 = open paren + start=$i + (( i += 2 )) + _zsh_highlight_main_highlighter_highlight_list $(( start_pos + i - 1 )) S $has_end $arg[i,-1] + ret=$? + (( i += REPLY )) + highlights+=( + $(( start_pos + start - 1)) $(( start_pos + i )) process-substitution + $(( start_pos + start - 1)) $(( start_pos + start + 1 )) process-substitution-delimiter + $reply + ) + if (( ret == 0 )); then + highlights+=($(( start_pos + i - 1)) $(( start_pos + i )) process-substitution-delimiter) + fi + continue + fi + ;| + *) + if $highlight_glob && + [[ $zsyh_user_options[multios] == on || $in_redirection -eq 0 ]] && + [[ ${arg[$i]} =~ ^[*?] || ${arg:$i-1} =~ ^\<[0-9]*-[0-9]*\> ]]; then + highlights+=($(( start_pos + i - 1 )) $(( start_pos + i + $#MATCH - 1)) globbing) + (( i += $#MATCH - 1 )) + path_eligible=0 + else + continue + fi + ;; + esac + done + + if (( path_eligible )); then + if (( in_redirection )) && [[ $last_arg == *['<>']['&'] && $arg[$1,-1] == (<0->|p|-) ]]; then + if [[ $arg[$1,-1] == (p|-) ]]; then + base_style=redirection + else + base_style=numeric-fd + fi + # This function is currently never called for the command word, so $2 is hard-coded as 0. + elif _zsh_highlight_main_highlighter_check_path $arg[$1,-1] 0; then + base_style=$REPLY + _zsh_highlight_main_highlighter_highlight_path_separators $base_style + highlights+=($reply) + fi + fi + + highlights=($(( start_pos + $1 - 1 )) $end_pos $base_style $highlights) + _zsh_highlight_main_add_many_region_highlights $highlights +} + +# Quote Helper Functions +# +# $arg is expected to be set to the current argument +# $start_pos is expected to be set to the start of $arg in $BUFFER +# $1 is the index in $arg which starts the quote +# $REPLY is returned as the end of quote index in $arg +# $reply is returned as an array of region_highlight additions + +# Highlight single-quoted strings +_zsh_highlight_main_highlighter_highlight_single_quote() +{ + local arg1=$1 i q=\' style + i=$arg[(ib:arg1+1:)$q] + reply=() + + if [[ $zsyh_user_options[rcquotes] == on ]]; then + while [[ $arg[i+1] == "'" ]]; do + reply+=($(( start_pos + i - 1 )) $(( start_pos + i + 1 )) rc-quote) + (( i++ )) + i=$arg[(ib:i+1:)$q] + done + fi + + if [[ $arg[i] == "'" ]]; then + style=single-quoted-argument + else + # If unclosed, i points past the end + (( i-- )) + style=single-quoted-argument-unclosed + fi + reply=($(( start_pos + arg1 - 1 )) $(( start_pos + i )) $style $reply) + REPLY=$i +} + +# Highlight special chars inside double-quoted strings +_zsh_highlight_main_highlighter_highlight_double_quote() +{ + local -a breaks match mbegin mend saved_reply + local MATCH; integer last_break=$(( start_pos + $1 - 1 )) MBEGIN MEND + local i j k ret style + reply=() + + for (( i = $1 + 1 ; i <= $#arg ; i += 1 )) ; do + (( j = i + start_pos - 1 )) + (( k = j + 1 )) + case "$arg[$i]" in + ('"') break;; + ('`') saved_reply=($reply) + _zsh_highlight_main_highlighter_highlight_backtick $i + (( i = REPLY )) + reply=($saved_reply $reply) + continue + ;; + ('$') style=dollar-double-quoted-argument + # Look for an alphanumeric parameter name. + if [[ ${arg:$i} =~ ^([A-Za-z_][A-Za-z0-9_]*|[0-9]+) ]] ; then + (( k += $#MATCH )) # highlight the parameter name + (( i += $#MATCH )) # skip past it + elif [[ ${arg:$i} =~ ^[{]([A-Za-z_][A-Za-z0-9_]*|[0-9]+)[}] ]] ; then + (( k += $#MATCH )) # highlight the parameter name and braces + (( i += $#MATCH )) # skip past it + elif [[ $arg[i+1] == '$' ]]; then + # $$ - pid + (( k += 1 )) # highlight both dollar signs + (( i += 1 )) # don't consider the second one as introducing another parameter expansion + elif [[ $arg[i+1] == [-#*@?] ]]; then + # $#, $*, $@, $?, $- - like $$ above + (( k += 1 )) # highlight both dollar signs + (( i += 1 )) # don't consider the second one as introducing another parameter expansion + elif [[ $arg[i+1] == $'\x28' ]]; then + saved_reply=($reply) + if [[ $arg[i+2] == $'\x28' ]] && _zsh_highlight_main_highlighter_highlight_arithmetic $i; then + # Arithmetic expansion + (( i = REPLY )) + reply=($saved_reply $reply) + continue + fi + + breaks+=( $last_break $(( start_pos + i - 1 )) ) + (( i += 2 )) + _zsh_highlight_main_highlighter_highlight_list $(( start_pos + i - 1 )) S $has_end $arg[i,-1] + ret=$? + (( i += REPLY )) + last_break=$(( start_pos + i )) + reply=( + $saved_reply + $j $(( start_pos + i )) command-substitution-quoted + $j $(( j + 2 )) command-substitution-delimiter-quoted + $reply + ) + if (( ret == 0 )); then + reply+=($(( start_pos + i - 1 )) $(( start_pos + i )) command-substitution-delimiter-quoted) + fi + continue + else + continue + fi + ;; + "\\") style=back-double-quoted-argument + if [[ \\\`\"\$${histchars[1]} == *$arg[$i+1]* ]]; then + (( k += 1 )) # Color following char too. + (( i += 1 )) # Skip parsing the escaped char. + else + continue + fi + ;; + ($histchars[1]) # ! - may be a history expansion + if [[ $arg[i+1] != ('='|$'\x28'|$'\x7b'|[[:blank:]]) ]]; then + style=history-expansion + else + continue + fi + ;; + *) continue ;; + + esac + reply+=($j $k $style) + done + + if [[ $arg[i] == '"' ]]; then + style=double-quoted-argument + else + # If unclosed, i points past the end + (( i-- )) + style=double-quoted-argument-unclosed + fi + (( last_break != start_pos + i )) && breaks+=( $last_break $(( start_pos + i )) ) + saved_reply=($reply) + reply=() + for 1 2 in $breaks; do + (( $1 != $2 )) && reply+=($1 $2 $style) + done + reply+=($saved_reply) + REPLY=$i +} + +# Highlight special chars inside dollar-quoted strings +_zsh_highlight_main_highlighter_highlight_dollar_quote() +{ + local -a match mbegin mend + local MATCH; integer MBEGIN MEND + local i j k style + local AA + integer c + reply=() + + for (( i = $1 + 2 ; i <= $#arg ; i += 1 )) ; do + (( j = i + start_pos - 1 )) + (( k = j + 1 )) + case "$arg[$i]" in + "'") break;; + "\\") style=back-dollar-quoted-argument + for (( c = i + 1 ; c <= $#arg ; c += 1 )); do + [[ "$arg[$c]" != ([0-9xXuUa-fA-F]) ]] && break + done + AA=$arg[$i+1,$c-1] + # Matching for HEX and OCT values like \0xA6, \xA6 or \012 + if [[ "$AA" =~ "^(x|X)[0-9a-fA-F]{1,2}" + || "$AA" =~ "^[0-7]{1,3}" + || "$AA" =~ "^u[0-9a-fA-F]{1,4}" + || "$AA" =~ "^U[0-9a-fA-F]{1,8}" + ]]; then + (( k += $#MATCH )) + (( i += $#MATCH )) + else + if (( $#arg > $i+1 )) && [[ $arg[$i+1] == [xXuU] ]]; then + # \x not followed by hex digits is probably an error + style=unknown-token + fi + (( k += 1 )) # Color following char too. + (( i += 1 )) # Skip parsing the escaped char. + fi + ;; + *) continue ;; + + esac + reply+=($j $k $style) + done + + if [[ $arg[i] == "'" ]]; then + style=dollar-quoted-argument + else + # If unclosed, i points past the end + (( i-- )) + style=dollar-quoted-argument-unclosed + fi + reply=($(( start_pos + $1 - 1 )) $(( start_pos + i )) $style $reply) + REPLY=$i +} + +# Highlight backtick substitutions +_zsh_highlight_main_highlighter_highlight_backtick() +{ + # buf is the contents of the backticks with a layer of backslashes removed. + # last is the index of arg for the start of the string to be copied into buf. + # It is either one past the beginning backtick or one past the last backslash. + # offset is a count of consumed \ (the delta between buf and arg). + # offsets is an array indexed by buf offset of when the delta between buf and arg changes. + # It is sparse, so search backwards to the last value + local buf highlight style=back-quoted-argument-unclosed style_end + local -i arg1=$1 end_ i=$1 last offset=0 start subshell_has_end=0 + local -a highlight_zone highlights offsets + reply=() + + last=$(( arg1 + 1 )) + # Remove one layer of backslashes and find the end + while i=$arg[(ib:i+1:)[\\\\\`]]; do # find the next \ or ` + if (( i > $#arg )); then + buf=$buf$arg[last,i] + offsets[i-arg1-offset]='' # So we never index past the end + (( i-- )) + subshell_has_end=$(( has_end && (start_pos + i == len) )) + break + fi + + if [[ $arg[i] == '\' ]]; then + (( i++ )) + # POSIX XCU 2.6.3 + if [[ $arg[i] == ('$'|'`'|'\') ]]; then + buf=$buf$arg[last,i-2] + (( offset++ )) + # offsets is relative to buf, so adjust by -arg1 + offsets[i-arg1-offset]=$offset + else + buf=$buf$arg[last,i-1] + fi + else # it's an unquoted ` and this is the end + style=back-quoted-argument + style_end=back-quoted-argument-delimiter + buf=$buf$arg[last,i-1] + offsets[i-arg1-offset]='' # So we never index past the end + break + fi + last=$i + done + + _zsh_highlight_main_highlighter_highlight_list 0 '' $subshell_has_end $buf + + # Munge the reply to account for removed backslashes + for start end_ highlight in $reply; do + start=$(( start_pos + arg1 + start + offsets[(Rb:start:)?*] )) + end_=$(( start_pos + arg1 + end_ + offsets[(Rb:end_:)?*] )) + highlights+=($start $end_ $highlight) + if [[ $highlight == back-quoted-argument-unclosed && $style == back-quoted-argument ]]; then + # An inner backtick command substitution is unclosed, but this level is closed + style_end=unknown-token + fi + done + + reply=( + $(( start_pos + arg1 - 1 )) $(( start_pos + i )) $style + $(( start_pos + arg1 - 1 )) $(( start_pos + arg1 )) back-quoted-argument-delimiter + $highlights + ) + if (( $#style_end )); then + reply+=($(( start_pos + i - 1)) $(( start_pos + i )) $style_end) + fi + REPLY=$i +} + +# Highlight special chars inside arithmetic expansions +_zsh_highlight_main_highlighter_highlight_arithmetic() +{ + local -a saved_reply + local style + integer i j k paren_depth ret + reply=() + + for (( i = $1 + 3 ; i <= end_pos - start_pos ; i += 1 )) ; do + (( j = i + start_pos - 1 )) + (( k = j + 1 )) + case "$arg[$i]" in + [\'\"\\@{}]) + style=unknown-token + ;; + '(') + (( paren_depth++ )) + continue + ;; + ')') + if (( paren_depth )); then + (( paren_depth-- )) + continue + fi + [[ $arg[i+1] == ')' ]] && { (( i++ )); break; } + # Special case ) at the end of the buffer to avoid flashing command substitution for a character + (( has_end && (len == k) )) && break + # This is a single paren and there are no open parens, so this isn't an arithmetic expansion + return 1 + ;; + '`') + saved_reply=($reply) + _zsh_highlight_main_highlighter_highlight_backtick $i + (( i = REPLY )) + reply=($saved_reply $reply) + continue + ;; + '$' ) + if [[ $arg[i+1] == $'\x28' ]]; then + saved_reply=($reply) + if [[ $arg[i+2] == $'\x28' ]] && _zsh_highlight_main_highlighter_highlight_arithmetic $i; then + # Arithmetic expansion + (( i = REPLY )) + reply=($saved_reply $reply) + continue + fi + + (( i += 2 )) + _zsh_highlight_main_highlighter_highlight_list $(( start_pos + i - 1 )) S $has_end $arg[i,end_pos] + ret=$? + (( i += REPLY )) + reply=( + $saved_reply + $j $(( start_pos + i )) command-substitution-quoted + $j $(( j + 2 )) command-substitution-delimiter-quoted + $reply + ) + if (( ret == 0 )); then + reply+=($(( start_pos + i - 1 )) $(( start_pos + i )) command-substitution-delimiter) + fi + continue + else + continue + fi + ;; + ($histchars[1]) # ! - may be a history expansion + if [[ $arg[i+1] != ('='|$'\x28'|$'\x7b'|[[:blank:]]) ]]; then + style=history-expansion + else + continue + fi + ;; + *) + continue + ;; + + esac + reply+=($j $k $style) + done + + if [[ $arg[i] != ')' ]]; then + # If unclosed, i points past the end + (( i-- )) + fi + style=arithmetic-expansion + reply=($(( start_pos + $1 - 1)) $(( start_pos + i )) arithmetic-expansion $reply) + REPLY=$i +} + + +# Called with a single positional argument. +# Perform filename expansion (tilde expansion) on the argument and set $REPLY to the expanded value. +# +# Does not perform filename generation (globbing). +_zsh_highlight_main_highlighter_expand_path() +{ + (( $# == 1 )) || print -r -- >&2 "zsh-syntax-highlighting: BUG: _zsh_highlight_main_highlighter_expand_path: called without argument" + + # The $~1 syntax normally performs filename generation, but not when it's on the right-hand side of ${x:=y}. + setopt localoptions nonomatch + unset REPLY + : ${REPLY:=${(Q)${~1}}} +} + +# ------------------------------------------------------------------------------------------------- +# Main highlighter initialization +# ------------------------------------------------------------------------------------------------- + +_zsh_highlight_main__precmd_hook() { + # Unset the WARN_NESTED_VAR option, taking care not to error if the option + # doesn't exist (zsh older than zsh-5.3.1-test-2). + setopt localoptions + if eval '[[ -o warnnestedvar ]]' 2>/dev/null; then + unsetopt warnnestedvar + fi + + _zsh_highlight_main__command_type_cache=() +} + +autoload -Uz add-zsh-hook +if add-zsh-hook precmd _zsh_highlight_main__precmd_hook 2>/dev/null; then + # Initialize command type cache + typeset -gA _zsh_highlight_main__command_type_cache +else + print -r -- >&2 'zsh-syntax-highlighting: Failed to load add-zsh-hook. Some speed optimizations will not be used.' + # Make sure the cache is unset + unset _zsh_highlight_main__command_type_cache +fi +typeset -ga ZSH_HIGHLIGHT_DIRS_BLACKLIST diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position1.zsh new file mode 100644 index 00000000..cfc12a5f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position1.zsh @@ -0,0 +1,35 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'/' + +expected_region_highlight=( + '1 1 path_prefix' # / +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position1b.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position1b.zsh new file mode 100644 index 00000000..88fe60c9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position1b.zsh @@ -0,0 +1,36 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +setopt autocd +BUFFER=$'/' + +expected_region_highlight=( + '1 1 autodirectory' # / +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position2.zsh new file mode 100644 index 00000000..5033d2c4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position2.zsh @@ -0,0 +1,35 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'/bi' + +expected_region_highlight=( + '1 3 path_prefix' # /bi +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position3.zsh new file mode 100644 index 00000000..415e3167 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position3.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'/bin; /bin' + +expected_region_highlight=( + '1 4 unknown-token' # /bin (in middle) + '5 5 commandseparator' # ; + '7 10 path_prefix' # /bin (at end) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position3b.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position3b.zsh new file mode 100644 index 00000000..0e65c98a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position3b.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +setopt autocd +BUFFER=$'/bin; /bin' + +expected_region_highlight=( + '1 4 autodirectory' # /bin (in middle) + '5 5 commandseparator' # ; + '7 10 autodirectory' # /bin (at end) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position4.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position4.zsh new file mode 100644 index 00000000..9e935bf1 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position4.zsh @@ -0,0 +1,35 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'/bin/s' + +expected_region_highlight=( + '1 6 path_prefix' # /bin/s +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position5.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position5.zsh new file mode 100644 index 00000000..e428b1a0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/abspath-in-command-position5.zsh @@ -0,0 +1,35 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'/bin/sh' + +expected_region_highlight=( + '1 7 command' # /bin/sh +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-assignment1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-assignment1.zsh new file mode 100644 index 00000000..0c101c8e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-assignment1.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Issue #263 (more-pathological case): aliases[x=y]=z works; the ${(z)} splitter considers +# that a single word; but it's not looked up as an alias. Hence, highlight it as an error. +aliases[x=y]='lorem ipsum dolor sit amet' +BUFFER='x=y ls' + +expected_region_highlight=( + "1 3 unknown-token" # x=y + "5 6 default" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-basic.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-basic.zsh new file mode 100644 index 00000000..7af8b7cd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-basic.zsh @@ -0,0 +1,35 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias foo="echo hello world" +BUFFER="foo" + +expected_region_highlight+=( + "1 3 alias" # foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-brackets.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-brackets.zsh new file mode 100644 index 00000000..ede6c9a9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-brackets.zsh @@ -0,0 +1,41 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2021 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Have to use cat here as it must be a command that exists. +# Otherwise, the test would fail with the first token being recognized +# as an "unknown-token". +alias ]=cat + +BUFFER='] /' + +expected_region_highlight=( + '1 1 alias' # ] + '3 3 path' # / +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-command-substitution.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-command-substitution.zsh new file mode 100644 index 00000000..a7b77dfa --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-command-substitution.zsh @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Alias must be at least 4 characters to test the regression +# cf. 139ea2b189819c43cc251825981c116959b15cc3 +alias foobar='echo "$(echo foobar)"' +BUFFER='foobar' + +expected_region_highlight=( + "1 6 alias" # foobar +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-comment1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-comment1.zsh new file mode 100644 index 00000000..bae7ef6f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-comment1.zsh @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# see alias-comment2.zsh and comment-followed.zsh +setopt interactivecomments +alias x=$'# foo\npwd' +BUFFER='x' + +expected_region_highlight=( + '1 1 alias' # x +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-comment2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-comment2.zsh new file mode 100644 index 00000000..5a498229 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-comment2.zsh @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# see alias-comment1.zsh +setopt NO_interactivecomments +alias x=$'# foo\npwd' +BUFFER='x' + +expected_region_highlight=( + '1 1 unknown-token' # x (#) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-complex.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-complex.zsh new file mode 100644 index 00000000..5ad7c0a9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-complex.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias x='echo && ls; >' + +BUFFER='x file echo' + +expected_region_highlight=( + '1 1 alias' # x + '3 6 default' # file + '8 11 builtin' # echo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-empty.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-empty.zsh new file mode 100644 index 00000000..535fccc9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-empty.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias x='' + +BUFFER='x echo foo' + +expected_region_highlight=( + '1 1 alias' # x + '3 6 builtin' # echo + '8 10 default' # foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-eponymous1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-eponymous1.zsh new file mode 100644 index 00000000..2642e14f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-eponymous1.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias ls='command ls' + +BUFFER='ls' + +expected_region_highlight=( + "1 2 alias" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-eponymous2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-eponymous2.zsh new file mode 100644 index 00000000..dcd85653 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-eponymous2.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias ls=tmp tmp='command ls' + +BUFFER='ls' + +expected_region_highlight=( + "1 2 alias" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-in-cmdsubst.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-in-cmdsubst.zsh new file mode 100644 index 00000000..b3cf777a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-in-cmdsubst.zsh @@ -0,0 +1,43 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias p='print -r --' + +BUFFER=$'s=$(p foo)' + +expected_region_highlight=( + '1 10 assign' # s=$(p foo) + '3 10 default' # $(p foo) + '3 10 command-substitution-unquoted' # $(p foo) + '3 4 command-substitution-delimiter-unquoted' # $( + '5 5 alias' # p + '7 9 default' # foo + '10 10 command-substitution-delimiter-unquoted' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-loop.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-loop.zsh new file mode 100644 index 00000000..83992dbf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-loop.zsh @@ -0,0 +1,44 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +function b() {} # beware of ALIAS_FUNC_DEF +alias a=b b=c c=b + +BUFFER='a foo; :' + +expected_region_highlight=( + # An alias is ineligible for expansion whilst it's being expanded. + # Therefore, the "b" in the expansion of the alias "c" is not considered + # as an alias. + '1 1 alias' # a + '3 5 default' # foo + '6 6 commandseparator' # ; + '8 8 builtin' # : +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-loop2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-loop2.zsh new file mode 100644 index 00000000..29e04ace --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-loop2.zsh @@ -0,0 +1,35 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias ls="ls" +BUFFER="ls" + +expected_region_highlight+=( + "1 2 alias" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-nested-precommand.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-nested-precommand.zsh new file mode 100644 index 00000000..6d4172bc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-nested-precommand.zsh @@ -0,0 +1,43 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias a=b b=sudo +sudo(){} + +BUFFER='a -u phy1729 echo; :' + +expected_region_highlight=( + '1 1 alias' # a + '3 4 single-hyphen-option' # -u + '6 12 default' # phy1729 + '14 17 builtin' # echo + '18 18 commandseparator' # ; + '20 20 builtin' # : +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-nested.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-nested.zsh new file mode 100644 index 00000000..b24b4967 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-nested.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias a=b b=: + +BUFFER='a foo; :' + +expected_region_highlight=( + '1 1 alias' # a + '3 5 default' # foo + '6 6 commandseparator' # ; + '8 8 builtin' # : +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-parameter.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-parameter.zsh new file mode 100644 index 00000000..21bc6b32 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-parameter.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias '$foo'='echo alias' +local foo; foo=(echo param) + +BUFFER='$foo' + +expected_region_highlight=( + '1 4 alias' # $foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-precommand-option-argument1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-precommand-option-argument1.zsh new file mode 100644 index 00000000..2d1f35c6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-precommand-option-argument1.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# See also param-precommand-option-argument1.zsh +alias sudo_u='sudo -u' +sudo(){} + +BUFFER='sudo_u phy1729 echo foo' + +expected_region_highlight=( + '1 6 alias' # sudo_u + '8 14 default' # phy1729 + '17 19 command "issue #540"' # echo (not builtin) + '21 23 default' # foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-precommand-option-argument2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-precommand-option-argument2.zsh new file mode 100644 index 00000000..fbc6eec7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-precommand-option-argument2.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias sudo_b='sudo -b' +alias sudo_b_u='sudo_b -u' +sudo(){} + +BUFFER='sudo_b_u phy1729 echo foo' + +expected_region_highlight=( + '1 8 alias' # sudo_b_u + '10 16 default' # phy1729 + '18 21 command "issue #540"' # echo (not builtin) + '23 25 default' # foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-precommand-option-argument3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-precommand-option-argument3.zsh new file mode 100644 index 00000000..373f12b6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-precommand-option-argument3.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# See also param-precommand-option-argument3.zsh +alias sudo_u='sudo -u' +sudo(){} + +BUFFER='sudo_u phy1729 ls foo' + +expected_region_highlight=( + '1 6 alias' # sudo_u + '8 14 default' # phy1729 + '16 17 command' # ls + '19 21 default' # foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-precommand-option-argument4.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-precommand-option-argument4.zsh new file mode 100644 index 00000000..d47dccb8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-precommand-option-argument4.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias sudo_b='sudo -b' +alias sudo_b_u='sudo_b -u' +sudo(){} + +BUFFER='sudo_b_u phy1729 ls foo' + +expected_region_highlight=( + '1 8 alias' # sudo_b_u + '10 16 default' # phy1729 + '18 19 command' # ls + '21 23 default' # foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-quoted.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-quoted.zsh new file mode 100644 index 00000000..e42e2f0a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-quoted.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) YYYY zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias a=: ls='ls -l' +BUFFER='"a" foo; \ls' + +expected_region_highlight=( + '1 3 unknown-token' # "a" + '5 7 default' # foo + '8 8 commandseparator' # ; + '10 12 command' # \ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-redirect.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-redirect.zsh new file mode 100644 index 00000000..acc3dcbe --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-redirect.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias x=\> +BUFFER='x foo echo bar' + +expected_region_highlight=( + '1 1 alias' # x + '3 5 default' # foo + '7 10 builtin' # echo + '12 14 default' # bar +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse1.zsh new file mode 100644 index 00000000..1fd61a0b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse1.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias a=: b='a | a' + +BUFFER='b | b' + +expected_region_highlight=( + '1 1 alias' # b + '3 3 commandseparator' # | + '5 5 alias' # b +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse2.zsh new file mode 100644 index 00000000..37251fb9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse2.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias a=: b='a && a' + +BUFFER='b && b' + +expected_region_highlight=( + '1 1 alias' # b + '3 4 commandseparator' # && + '6 6 alias' # b +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse3.zsh new file mode 100644 index 00000000..5d7150a1 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse3.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias a=: b='a; a' + +BUFFER='b; b' + +expected_region_highlight=( + '1 1 alias' # b + '2 2 commandseparator' # ; + '4 4 alias' # b +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse4.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse4.zsh new file mode 100644 index 00000000..7ad7038c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse4.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias a=: b='a $(a)' + +BUFFER='b $(b)' + +expected_region_highlight=( + '1 1 alias' # b + '3 6 default' # $(b) + '3 6 command-substitution-unquoted' # $(b) + '3 4 command-substitution-delimiter-unquoted' # $( + '5 5 alias' # b + '6 6 command-substitution-delimiter-unquoted' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse5.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse5.zsh new file mode 100644 index 00000000..881401b2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-reuse5.zsh @@ -0,0 +1,43 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias a=: b='a < <(a)' + +BUFFER='b < <(b)' + +expected_region_highlight=( + '1 1 alias' # b + '3 3 redirection' # < + '5 8 default' # <(b) + '5 8 process-substitution' # <(b) + '5 6 process-substitution-delimiter' # <( + '7 7 alias' # b + '8 8 process-substitution-delimiter' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-self.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-self.zsh new file mode 100644 index 00000000..c6f12b1a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-self.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias echo='echo foo' + +BUFFER='echo bar' + +expected_region_highlight=( + '1 4 alias' # echo + '6 8 default' # bar +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-self2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-self2.zsh new file mode 100644 index 00000000..fd6ae03f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-self2.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias cat='cat | cat' + +BUFFER='cat' + +expected_region_highlight=( + '1 3 alias' # cat +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-to-dir.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-to-dir.zsh new file mode 100644 index 00000000..30390d42 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-to-dir.zsh @@ -0,0 +1,36 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias x=/ +BUFFER=$'x' + +expected_region_highlight=( + '1 1 unknown-token' # x (/) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-to-dir1b.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-to-dir1b.zsh new file mode 100644 index 00000000..62ec5213 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-to-dir1b.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +setopt autocd +alias x=/ +BUFFER=$'x' + +expected_region_highlight=( + '1 1 alias' # x +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-unknown-token1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-unknown-token1.zsh new file mode 100644 index 00000000..9c996bfe --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-unknown-token1.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias a=b b=foo + +BUFFER='a ' + +expected_region_highlight=( + '1 1 unknown-token' # a +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-unknown-token2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-unknown-token2.zsh new file mode 100644 index 00000000..ab9facd6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias-unknown-token2.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias a='() { ls "$@" ; foo }' + +BUFFER='a ' + +expected_region_highlight=( + '1 1 unknown-token' # a +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias.zsh new file mode 100644 index 00000000..4cafa804 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/alias.zsh @@ -0,0 +1,53 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias alias1="ls" +alias -s alias2="echo" +function alias1() {} # to check that it's highlighted as an alias, not as a function + +BUFFER='x.alias2; alias1; alias2' + +# Set expected_region_highlight as a function of zsh version. +# +# Highlight of suffix alias requires zsh-5.1.1 or newer; see issue #126, +# and commit 36403 to zsh itself. Therefore, check if the requisite zsh +# functionality is present, and skip verifying suffix-alias highlighting +# if it isn't. +expected_region_highlight=() +if zmodload -e zsh/parameter || [[ "$(type -w x.alias2)" == *suffix* ]]; then + expected_region_highlight+=( + "1 8 suffix-alias" # x.alias2 + ) +fi +expected_region_highlight+=( + "9 9 commandseparator" # ; + "11 16 alias" # alias1 + "17 17 commandseparator" # ; + "19 24 unknown-token" # alias2 +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/always1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/always1.zsh new file mode 100644 index 00000000..ae40a72f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/always1.zsh @@ -0,0 +1,41 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='{ ls } always { pwd }' + +expected_region_highlight=( + '1 1 reserved-word' # { + '3 4 command' # ls + '6 6 reserved-word' # } + '8 13 reserved-word' # always + '15 15 reserved-word' # { + '17 19 builtin' # pwd + '21 21 reserved-word' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/always2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/always2.zsh new file mode 100644 index 00000000..991137c2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/always2.zsh @@ -0,0 +1,43 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'{\nls\n} always { pwd }' + +expected_region_highlight=( + '1 1 reserved-word' # { + '2 2 commandseparator' # \n + '3 4 command' # ls + '5 5 commandseparator' # \n + '6 6 reserved-word' # } + '8 13 reserved-word' # always + '15 15 reserved-word' # { + '17 19 builtin' # pwd + '21 21 reserved-word' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/always3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/always3.zsh new file mode 100644 index 00000000..d41beeb5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/always3.zsh @@ -0,0 +1,43 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +setopt ignorebraces +BUFFER='echo { foo } always { bar }' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 6 default' # { + '8 10 default' # foo + '12 12 default' # } + '14 19 default' # always + '21 21 default' # { + '23 25 default' # bar + '27 27 default' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/anonymous-function.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/anonymous-function.zsh new file mode 100644 index 00000000..9d67fb1d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/anonymous-function.zsh @@ -0,0 +1,44 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='() echo hello; () { echo world } "argument"' + +expected_region_highlight=( + "1 2 reserved-word" # () + "4 7 builtin" # echo + "9 13 default" # hello + "14 14 commandseparator" # ; + "16 17 reserved-word" # () + "19 19 reserved-word" # { + "21 24 builtin" # echo + "26 30 default" # world + "32 32 reserved-word" # } + "34 43 default" # "argument" + "34 43 double-quoted-argument" # "argument" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arg0-colon.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arg0-colon.zsh new file mode 100644 index 00000000..8955bd28 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arg0-colon.zsh @@ -0,0 +1,35 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=''\''x: /' + +expected_region_highlight=( + '1 5 unknown-token' # \'x: / +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arith-cmdsubst-mess.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arith-cmdsubst-mess.zsh new file mode 100644 index 00000000..82268ac1 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arith-cmdsubst-mess.zsh @@ -0,0 +1,46 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': $((ls); (ls))' + +expected_region_highlight=( + '1 1 builtin' # : + '3 15 default' # $((ls); (ls)) + '3 15 command-substitution-unquoted' # $((ls); (ls)) + '3 4 command-substitution-delimiter-unquoted' # $( + '5 5 reserved-word' # ( + '6 7 command' # ls + '8 8 reserved-word' # ) + '9 9 commandseparator' # ; + '11 11 reserved-word' # ( + '12 13 command' # ls + '14 14 reserved-word' # ) + '15 15 command-substitution-delimiter-unquoted' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arith1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arith1.zsh new file mode 100644 index 00000000..0462f738 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arith1.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': $(( 6 * 9 ))' + +expected_region_highlight=( + '1 1 builtin' # : + '3 14 default' # $(( 6 * 9 )) + '3 14 arithmetic-expansion' # $(( 6 * 9 )) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arith2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arith2.zsh new file mode 100644 index 00000000..af981d7c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arith2.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': "$(( 6 * 9 ))"' + +expected_region_highlight=( + '1 1 builtin' # : + '3 16 default' # "$(( 6 * 9 ))" + '3 16 double-quoted-argument' # "$(( 6 * 9 ))" + '4 15 arithmetic-expansion' # $(( 6 * 9 )) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-command-substitution.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-command-substitution.zsh new file mode 100644 index 00000000..07db0fb2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-command-substitution.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': $(( $(echo 2) + 2 ))' + +expected_region_highlight=( + '1 1 builtin' # : + '3 22 default' # $(( $(echo 2) + 2 )) + '3 22 arithmetic-expansion' # $(( $(echo 2) + 2 )) + '7 15 command-substitution-quoted' # $(echo 2) + '7 8 command-substitution-delimiter-quoted' # $( + '9 12 builtin' # echo + '14 14 default' # 2 + '15 15 command-substitution-delimiter' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-doubled-parens.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-doubled-parens.zsh new file mode 100644 index 00000000..d582d67c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-doubled-parens.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': $(( ((42)) ))' + +expected_region_highlight=( + '1 1 builtin' # : + '3 15 default' # $(( ((42)) )) + '3 15 arithmetic-expansion' # $(( ((42)) )) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-empty.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-empty.zsh new file mode 100644 index 00000000..bd759966 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-empty.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': "foo"$(())"bar"' + +expected_region_highlight=( + '1 1 builtin' # : + '3 17 default' # "foo"$(())"bar" + '3 7 double-quoted-argument' # "foo" + '8 12 arithmetic-expansion' # $(()) + '13 17 double-quoted-argument' # "bar" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-evaluation.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-evaluation.zsh new file mode 100644 index 00000000..e0eb6e75 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-evaluation.zsh @@ -0,0 +1,40 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Must be at command word, since the word following 'if' isn't currently considered +# a command word (issue #207). +# +# An opening '((' without matching '))' is highlighted correctly under zsh-5.1.1-52-g4bed2cf +# or newer, only (issue #188). +BUFFER='(( x == 42 ))' + +expected_region_highlight=( + "1 2 reserved-word" # (( + "12 13 reserved-word" # )) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-hist-expn.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-hist-expn.zsh new file mode 100644 index 00000000..79af7233 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-hist-expn.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': $(( \!\! ))' + +expected_region_highlight=( + '1 1 builtin' # : + '3 11 default' # $(( !! )) + '3 11 arithmetic-expansion' # $(( !! )) + '7 8 history-expansion "issue #713"' # !! +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-invalid-chars.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-invalid-chars.zsh new file mode 100644 index 00000000..9ace4383 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-invalid-chars.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': $(( 0 * 1\'\'000 ))' + +expected_region_highlight=( + '1 1 builtin' # : + '3 19 default' # $(( 0 * 1\'\'000 )) + '3 19 arithmetic-expansion' # $(( 0 * 1\'\'000 )) + '12 12 unknown-token' # \' + '13 13 unknown-token' # \' +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-multiplication.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-multiplication.zsh new file mode 100644 index 00000000..65df0c9f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-multiplication.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': foo*$(( 42 * 1729 ))*bar' + +expected_region_highlight=( + '1 1 builtin' # : + '3 26 default' # foo*$(( 42 * 1729 ))*bar + '6 6 globbing' # * + '7 22 arithmetic-expansion' # $(( 42 * 1729 )) + '23 23 globbing' # * +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-nested.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-nested.zsh new file mode 100644 index 00000000..d734cd34 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-nested.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': $(( $(( 1 + 2 )) * 3 ))' + +expected_region_highlight=( + '1 1 builtin' # : + '3 25 default' # $(( $(( 1 + 2 )) * 3 )) + '3 25 arithmetic-expansion' # $(( $(( 1 + 2 )) * 3 )) + '7 18 arithmetic-expansion' # $(( 1 + 2 )) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-quoted.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-quoted.zsh new file mode 100644 index 00000000..917ddf78 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-quoted.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': "$(( 1 + 1 ))"' + +expected_region_highlight=( + '1 1 builtin' # : + '3 16 default' # "$(( 1 + 1 ))" + '3 16 double-quoted-argument' # "$(( 1 + 1 ))" + '4 15 arithmetic-expansion' # $(( 1 + 1 )) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-unclosed.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-unclosed.zsh new file mode 100644 index 00000000..aa4eac7a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-unclosed.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': $(( 1' + +expected_region_highlight=( + '1 1 builtin' # : + '3 7 default' # $(( 1 + '3 7 arithmetic-expansion' # $(( 1 +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-unfinished.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-unfinished.zsh new file mode 100644 index 00000000..916c3dad --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/arithmetic-unfinished.zsh @@ -0,0 +1,41 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': $(( 1729 )' + +expected_region_highlight=( + '1 1 builtin' # : + '3 12 default' # $(( 1729 ) + '3 12 arithmetic-expansion' # $(( 1729 ) +) + +if [[ ${(z):-'$('} == '$( ' ]]; then # ignore zsh 5.0.8 bug + expected_region_highlight[2]='3 13 default' # $(( 1729 ) +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/array-cmdsep1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/array-cmdsep1.zsh new file mode 100644 index 00000000..2fd55c03 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/array-cmdsep1.zsh @@ -0,0 +1,45 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'a=( foo | bar )' +bar(){} + +expected_region_highlight=( + '1 3 assign' # a=( + '3 3 reserved-word' # ( + '5 7 default' # foo + '9 9 unknown-token' # | + # zsh reports a parse error at this point. Nevertheless, we test how we + # highlight the remainder of $BUFFER. Currently we recover by treating the pipe + # as a command separator. That's not the only reasonable behaviour, though; if + # we change the behaviour, we should adjust the following expectations accordingly. + '11 13 function' # bar + '15 15 unknown-token' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/array-cmdsep2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/array-cmdsep2.zsh new file mode 100644 index 00000000..0bda6761 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/array-cmdsep2.zsh @@ -0,0 +1,41 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'a=( foo ; bar )' + +expected_region_highlight=( + '1 3 assign' # a=( + '3 3 reserved-word' # ( + '5 7 default' # foo + '9 9 unknown-token' # ; (not commandseparator; see highlighter source code) + '11 13 default' # bar + '15 15 assign' # ) + '15 15 reserved-word' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/array-cmdsep3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/array-cmdsep3.zsh new file mode 100644 index 00000000..b4b3687c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/array-cmdsep3.zsh @@ -0,0 +1,41 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'a=( foo \n bar )' + +expected_region_highlight=( + '1 3 assign' # a=( + '3 3 reserved-word' # ( + '5 7 default' # foo + '9 9 commandseparator' # \n + '11 13 default' # bar + '15 15 assign' # ) + '15 15 reserved-word' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-append.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-append.zsh new file mode 100644 index 00000000..feb68e53 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-append.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='a+=(lorem ipsum)' + +expected_region_highlight=( + "1 4 assign" # a+=( + "4 4 reserved-word" # ( + "5 9 default" # lorem + "11 15 default" # ipsum + "16 16 assign" # ) + "16 16 reserved-word" # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-argv.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-argv.zsh new file mode 100644 index 00000000..ec5acc24 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-argv.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +touch foo +BUFFER='42=foo 43+=bar' + +expected_region_highlight=( + "1 6 assign" # 42=foo + "4 6 path" # foo + "8 14 assign" # 43+=bar + "12 14 default" # bar +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-array.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-array.zsh new file mode 100644 index 00000000..ef0a6669 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-array.zsh @@ -0,0 +1,41 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='(A=(hello world))' + +expected_region_highlight=( + "1 1 reserved-word" # ( + "2 4 assign" # A=( + "4 4 reserved-word" # ( + "5 9 default" # hello + "11 15 default" # world + "16 16 assign" # ) + "16 16 reserved-word" # ) + "17 17 reserved-word" # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-array2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-array2.zsh new file mode 100644 index 00000000..2d487211 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-array2.zsh @@ -0,0 +1,40 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='A=(hello world) ls' + +expected_region_highlight=( + "1 3 assign" # A=( + "3 3 reserved-word" # ( + "4 8 default" # hello + "10 14 default" # world + "15 15 assign" # ) + "15 15 reserved-word" # ) + "17 18 command" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-array3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-array3.zsh new file mode 100644 index 00000000..5eb645e6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-array3.zsh @@ -0,0 +1,41 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='A=(hello world) b=42' + +expected_region_highlight=( + "1 3 assign" # A=( + "3 3 reserved-word" # ( + "4 8 default" # hello + "10 14 default" # world + "15 15 assign" # ) + "15 15 reserved-word" # ) + "17 20 assign" # b=42 + "19 20 default" # 42 +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-invalid-command.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-invalid-command.zsh new file mode 100644 index 00000000..557327e8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-invalid-command.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'x=y nosuchcommand' + +expected_region_highlight=( + '1 3 assign' # x=y + '3 3 default' # y + '5 17 unknown-token' # nosuchcommand +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-not-array.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-not-array.zsh new file mode 100644 index 00000000..651ab80a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-not-array.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='a=foo( bar ) :' + +expected_region_highlight=( + '1 12 assign' # a=foo( bar ) + '3 12 default' # foo( bar ) + '14 14 builtin' # : +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-not-array2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-not-array2.zsh new file mode 100644 index 00000000..dfda106e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-not-array2.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='a=foo\( :' + +expected_region_highlight=( + '1 7 assign' # a=foo\( + '3 7 default' # foo\( + '9 9 builtin' # : +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-quoted-cmdsubst.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-quoted-cmdsubst.zsh new file mode 100644 index 00000000..d4a62dfa --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-quoted-cmdsubst.zsh @@ -0,0 +1,45 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'x="$(ls x y z)"' + +expected_region_highlight=( + '1 15 assign' # x="$(ls x y z)" + '3 15 default' # "$(ls x y z)" + '3 3 double-quoted-argument' # " + '15 15 double-quoted-argument' # " + '4 14 command-substitution-quoted' # $(ls x y z) + '4 5 command-substitution-delimiter-quoted' # $( + '6 7 command' # ls + '9 9 default' # x + '11 11 default' # y + '13 13 default' # z + '14 14 command-substitution-delimiter-quoted' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-semicolon.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-semicolon.zsh new file mode 100644 index 00000000..f748c94e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-semicolon.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='A=1; echo hello world' + +expected_region_highlight=( + "1 3 assign" # A=1 + "3 3 default" # 1 + "4 4 commandseparator" # ; + "6 9 builtin" # echo + "11 15 default" # hello + "17 21 default" # world +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-subshell.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-subshell.zsh new file mode 100644 index 00000000..20228893 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-subshell.zsh @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='(A=1)' + +expected_region_highlight=( + "1 1 reserved-word" # ( + "2 4 assign" # A=1 + "4 4 default" # 1 + "5 5 reserved-word" # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-value-quote1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-value-quote1.zsh new file mode 100644 index 00000000..b6d04fe0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-value-quote1.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'s="foo\'bar"' + +expected_region_highlight=( + '1 11 assign' # s="foo'bar" + '3 11 default' # "foo'bar" + '3 11 double-quoted-argument' # "foo'bar" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-value-quote2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-value-quote2.zsh new file mode 100644 index 00000000..3c5f93b4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign-value-quote2.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'s="foo \'\' bar"' + +expected_region_highlight=( + '1 14 assign' # s="foo '' bar" + '3 14 default' # "foo '' bar" + '3 14 double-quoted-argument' # "foo '' bar" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign.zsh new file mode 100644 index 00000000..c6e8532d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assign.zsh @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='A=1 b=("foo" bar)' + +expected_region_highlight=( + "1 3 assign" # A=1 + "3 3 default" # 1 + "5 7 assign" # b=( + "7 7 reserved-word" # ( + "8 12 default" # "foo" + "8 12 double-quoted-argument" # "foo" + "14 16 default" # bar + "17 17 assign" # ) + "17 17 reserved-word" # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword1.zsh new file mode 100644 index 00000000..b271d4aa --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword1.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'foo=bar { :; }' + +expected_region_highlight=( + '1 7 assign' # foo=bar + '5 7 default' # bar + '9 9 unknown-token' # { + '11 11 builtin' # : + '12 12 commandseparator' # ; + '14 14 reserved-word' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword2.zsh new file mode 100644 index 00000000..247e41eb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword2.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'foo=bar ( :; )' + +expected_region_highlight=( + '1 7 assign' # foo=bar + '5 7 default' # bar + '9 9 unknown-token' # ( + '11 11 builtin' # : + '12 12 commandseparator' # ; + '14 14 unknown-token' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword3.zsh new file mode 100644 index 00000000..52041895 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword3.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'foo=bar (( foo ))' + +expected_region_highlight=( + '1 7 assign' # foo=bar + '5 7 default' # bar + '9 17 unknown-token' # (( foo )) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword4.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword4.zsh new file mode 100644 index 00000000..cc3d5231 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword4.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'foo=bar [[ -n foo ]]' + +expected_region_highlight=( + '1 7 assign' # foo=bar + '5 7 default' # bar + '9 10 unknown-token' # [[ + '12 13 single-hyphen-option' # -n + '15 17 default' # foo + '19 20 reserved-word' # ]] +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword5.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword5.zsh new file mode 100644 index 00000000..33f1ed14 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-before-resword5.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'foo=bar \! :' + +expected_region_highlight=( + '1 7 assign' # foo=bar + '5 7 default' # bar + '9 9 unknown-token' # \! + '11 11 builtin' # : +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-quoted.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-quoted.zsh new file mode 100644 index 00000000..18638adb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/assignment-quoted.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'1="foo"' + +expected_region_highlight=( + '1 7 assign' # 1="foo" + '3 7 default' # "foo" + '3 7 double-quoted-argument' # "foo" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/back-quoted-argument.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/back-quoted-argument.zsh new file mode 100644 index 00000000..d504a2c7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/back-quoted-argument.zsh @@ -0,0 +1,58 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='echo `echo \`42\`` "is `echo equal` to" `echo 6 times 9' + +expected_region_highlight=( + "1 4 builtin" # echo + "6 18 default" # `echo \`42\`` + "6 18 back-quoted-argument" # `echo \`42\`` + "6 6 back-quoted-argument-delimiter" # ` + "7 10 builtin" # echo + "12 17 default" # \`42\` + "12 17 back-quoted-argument" # \`42\` + "12 13 back-quoted-argument-delimiter" # \` + "14 15 unknown-token" # 42 + "16 17 back-quoted-argument-delimiter" # \` + "18 18 back-quoted-argument-delimiter" # ` + "20 39 default" # "is `echo equal` to" + "20 39 double-quoted-argument" # "is `echo equal` to" + "24 35 back-quoted-argument" # `echo equal` + "24 24 back-quoted-argument-delimiter" # ` + "25 28 builtin" # echo + "30 34 default" # equal + "35 35 back-quoted-argument-delimiter" # ` + "41 55 default" # `echo 6 times 9 + "41 55 back-quoted-argument-unclosed" # `echo 6 times 9 + "41 41 back-quoted-argument-delimiter" # ` + "42 45 builtin" # echo + "47 47 default" # 6 + "49 53 default" # times + "55 55 default" # 9 +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/back-quoted-open.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/back-quoted-open.zsh new file mode 100644 index 00000000..f188d811 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/back-quoted-open.zsh @@ -0,0 +1,41 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +touch foo +BUFFER=$': `ls fo' + +expected_region_highlight=( + '1 1 builtin' # : + '3 8 default' # `ls fo + '3 8 back-quoted-argument-unclosed' # `ls fo + '3 3 back-quoted-argument-delimiter' # ` + '4 5 command' # ls + '7 8 path_prefix' # fo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/backslash-continuation.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/backslash-continuation.zsh new file mode 100644 index 00000000..ebcf2e17 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/backslash-continuation.zsh @@ -0,0 +1,35 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +PREBUFFER=$'echo \\\n' +BUFFER='noglob' + +expected_region_highlight=( + "1 6 default" # 'noglob' highlighted as a string, not as a precomand +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/backslash-continuation2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/backslash-continuation2.zsh new file mode 100644 index 00000000..9e2ca623 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/backslash-continuation2.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'echo foo\\\nbar"baz"' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 18 default "issue #705"' # foo\\\nbar"baz" + '14 18 double-quoted-argument "issue #705"' # "baz" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/backslash-space.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/backslash-space.zsh new file mode 100644 index 00000000..0d8a63c1 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/backslash-space.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'echo \\ \'foo\' ; ls' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 12 default' # \ \'foo\' + '8 12 single-quoted-argument' # 'foo' + '14 14 commandseparator' # ; + '16 17 command' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/backslash.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/backslash.zsh new file mode 100644 index 00000000..ea0977f6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/backslash.zsh @@ -0,0 +1,34 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'\\' + +expected_region_highlight=( + '1 1 unknown-token' # \\ +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/bang-assign-array.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/bang-assign-array.zsh new file mode 100644 index 00000000..a54cf2d0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/bang-assign-array.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'foo=(bar abaz) \! ls' + +expected_region_highlight=( + '1 5 assign' # foo=( + '5 5 reserved-word' # ( + '6 8 default' # bar + '10 13 default' # abaz + '14 14 assign' # ) + '14 14 reserved-word' # ) + '16 16 unknown-token' # \! + '18 19 command' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/bang-assign-scalar.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/bang-assign-scalar.zsh new file mode 100644 index 00000000..e9190500 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/bang-assign-scalar.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'foo=bar \! ls' + +expected_region_highlight=( + '1 7 assign' # foo=bar + '5 7 default' # bar + '9 9 unknown-token' # \! + '11 12 command' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/bang-pipeline.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/bang-pipeline.zsh new file mode 100644 index 00000000..fef25f10 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/bang-pipeline.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'\! ls | \! ls' + +expected_region_highlight=( + '1 1 reserved-word' # \! + '3 4 command' # ls + '6 6 commandseparator' # | + '8 8 unknown-token' # \! + '10 11 command' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/block-assignment-no-command.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/block-assignment-no-command.zsh new file mode 100644 index 00000000..ec52c987 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/block-assignment-no-command.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2022 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'{ a=42 }' + +expected_region_highlight=( + '1 1 reserved-word' # { + '3 6 assign' # a=42 + '5 6 default' # 42 + '8 8 reserved word "issue #854"' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/braces1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/braces1.zsh new file mode 100644 index 00000000..3c5b1f0f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/braces1.zsh @@ -0,0 +1,41 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'() { echo }\n}' +# no special setopts + +expected_region_highlight=( + '1 2 reserved-word' # () + '4 4 reserved-word' # { + '6 9 builtin' # echo + '11 11 reserved-word' # } + '12 12 commandseparator' # \n + '13 13 unknown-token' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/braces2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/braces2.zsh new file mode 100644 index 00000000..a3ea7c95 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/braces2.zsh @@ -0,0 +1,41 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'() { echo }\n}' +setopt ignorebraces + +expected_region_highlight=( + '1 2 reserved-word' # () + '4 4 reserved-word' # { + '6 9 builtin' # echo + '11 11 default' # } + '12 12 commandseparator' # \n + '13 13 reserved-word' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-matching1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-matching1.zsh new file mode 100644 index 00000000..7cc6de54 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-matching1.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='[[ -n foo ]]' + +expected_region_highlight=( + '1 2 reserved-word' # [[ + '4 5 single-hyphen-option' # -n + '7 9 default' # foo + '11 12 reserved-word' # ]] +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-matching2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-matching2.zsh new file mode 100644 index 00000000..19c7f0d7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-matching2.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='[ -n foo ]' + +expected_region_highlight=( + '1 1 builtin' # [ + '3 4 single-hyphen-option' # -n + '6 8 default' # foo + '10 10 builtin' # ] +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch1.zsh new file mode 100644 index 00000000..5e6e80f2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch1.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='() { echo foo )' + +expected_region_highlight=( + '1 2 reserved-word' # () + '4 4 reserved-word' # { + '6 9 builtin' # echo + '11 13 default' # foo + '15 15 unknown-token' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch10-if-negative.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch10-if-negative.zsh new file mode 100644 index 00000000..9d0b53c6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch10-if-negative.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='elif true; then echo two; fi' + +expected_region_highlight=( + '1 4 unknown-token' # elif + '6 9 builtin' # true + '10 10 commandseparator' # ; + '12 15 unknown-token' # then + '17 20 builtin' # echo + '22 24 default' # two + '25 25 commandseparator' # ; + '27 28 unknown-token' # fi +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch2.zsh new file mode 100644 index 00000000..2d98ac21 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch2.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='() ( echo foo }' + +expected_region_highlight=( + '1 2 reserved-word' # () + '4 4 reserved-word' # ( + '6 9 builtin' # echo + '11 13 default' # foo + '15 15 unknown-token' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch3.zsh new file mode 100644 index 00000000..e33040a8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch3.zsh @@ -0,0 +1,36 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='echo )' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 6 unknown-token' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch4.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch4.zsh new file mode 100644 index 00000000..a9b15dcd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch4.zsh @@ -0,0 +1,36 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='echo }' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 6 unknown-token' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch5.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch5.zsh new file mode 100644 index 00000000..21e8bb2b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch5.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='echo { }' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 6 default' # { + '8 8 unknown-token' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch6.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch6.zsh new file mode 100644 index 00000000..9df83883 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch6.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='(repeat 1; do)' + +expected_region_highlight=( + '1 1 reserved-word' # ( + '2 7 reserved-word' # repeat + '9 9 default' # 1 + '10 10 commandseparator' # ; + '12 13 reserved-word' # do + '14 14 unknown-token' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch7.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch7.zsh new file mode 100644 index 00000000..1caa936c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch7.zsh @@ -0,0 +1,45 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2012 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='for n in *; do echo $n; end' + +expected_region_highlight=( + '1 3 reserved-word' # for + '5 5 default' # n + '7 8 default' # in + '10 10 default' # * + '10 10 globbing' # * + '11 11 commandseparator' # ; + '13 14 reserved-word' # do + '16 19 builtin' # echo + '21 22 default' # $n + '23 23 commandseparator' # ; + '25 27 unknown-token' # end +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch8-if-positive.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch8-if-positive.zsh new file mode 100644 index 00000000..d6838f00 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch8-if-positive.zsh @@ -0,0 +1,53 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='if false; then echo one; elif true; then echo two; else echo three; fi' + +expected_region_highlight=( + '1 2 reserved-word' # if + '4 8 builtin' # false + '9 9 commandseparator' # ; + '11 14 reserved-word' # then + '16 19 builtin' # echo + '21 23 default' # one + '24 24 commandseparator' # ; + '26 29 reserved-word' # elif + '31 34 builtin' # true + '35 35 commandseparator' # ; + '37 40 reserved-word' # then + '42 45 builtin' # echo + '47 49 default' # two + '50 50 commandseparator' # ; + '52 55 reserved-word' # else + '57 60 builtin' # echo + '62 66 default' # three + '67 67 commandseparator' # ; + '69 70 reserved-word' # fi +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch8.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch8.zsh new file mode 100644 index 00000000..07a42e36 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch8.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='(ls&)' + +expected_region_highlight=( + '1 1 reserved-word' # ( + '2 3 command' # ls + '4 4 commandseparator' # & + '5 5 reserved-word' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch9-if-positive.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch9-if-positive.zsh new file mode 100644 index 00000000..87c1ba79 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-mismatch9-if-positive.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='if false; then echo one; fi' + +expected_region_highlight=( + '1 2 reserved-word' # if + '4 8 builtin' # false + '9 9 commandseparator' # ; + '11 14 reserved-word' # then + '16 19 builtin' # echo + '21 23 default' # one + '24 24 commandseparator' # ; + '26 27 reserved-word' # fi +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-premature-termination.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-premature-termination.zsh new file mode 100644 index 00000000..fa813da9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/brackets-premature-termination.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='[[ -n foo; echo ]]' + +expected_region_highlight=( + '1 2 reserved-word' # [[ + '4 5 single-hyphen-option' # -n + '7 9 default' # foo + '10 10 unknown-token' # ; + '12 15 builtin' # echo + '17 18 default' # ]] +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/cdpath-abspath.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/cdpath-abspath.zsh new file mode 100644 index 00000000..64707b2f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/cdpath-abspath.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +cdpath=( $PWD ) +mkdir foo foo/bar + +BUFFER="/foo" + +expected_region_highlight=( + '1 4 unknown-token' # x (/) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/cmdpos-elision-partial.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/cmdpos-elision-partial.zsh new file mode 100644 index 00000000..6eda0d74 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/cmdpos-elision-partial.zsh @@ -0,0 +1,44 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Test elision of some, but not all of the words +# See issue #667 for the case of eliding all words +local -a x; x=(sudo "") + +sudo(){} +BUFFER=$'$x -u phy1729 ls' + +expected_region_highlight=( + '1 2 precommand' # $x + # The "" is elided. If it weren't elided, the «ls» would be highlighted as an ordinary argument. + '4 5 single-hyphen-option' # -u + '7 13 default' # phy1729 + '15 16 command' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/command-substitution-adjacent.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/command-substitution-adjacent.zsh new file mode 100644 index 00000000..3d5c0b9e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/command-substitution-adjacent.zsh @@ -0,0 +1,45 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='echo "$(echo)$(echo)' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 20 default' # "$(echo)$(echo) + '6 6 double-quoted-argument-unclosed' # " + '7 13 command-substitution-quoted' # $(echo) + '7 8 command-substitution-delimiter-quoted' # $( + '9 12 builtin' # echo + '13 13 command-substitution-delimiter-quoted' # ) + '14 20 command-substitution-quoted' # $(echo) + '14 15 command-substitution-delimiter-quoted' # $( + '16 19 builtin' # echo + '20 20 command-substitution-delimiter-quoted' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/command-substitution-in-assignment.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/command-substitution-in-assignment.zsh new file mode 100644 index 00000000..fafda49c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/command-substitution-in-assignment.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'foo=$(echo bar) :' + +expected_region_highlight=( + '1 15 assign' # foo=$(echo bar) + '5 15 default' # $(echo bar) + '5 15 command-substitution-unquoted' # $(echo bar) + '5 6 command-substitution-delimiter-unquoted' # $( + '7 10 builtin' # echo + '12 14 default' # bar + '15 15 command-substitution-delimiter-unquoted' # ) + '17 17 builtin' # : +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/command-substitution-unclosed.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/command-substitution-unclosed.zsh new file mode 100644 index 00000000..3229dfcf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/command-substitution-unclosed.zsh @@ -0,0 +1,45 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': foo$(echo bar' + +expected_region_highlight=( + '1 1 builtin' # : + '3 15 default' # foo$(echo bar + '6 15 command-substitution-unquoted' # $(echo bar + '6 7 command-substitution-delimiter-unquoted' # $( + '8 11 builtin' # echo + '13 15 default' # bar +) + +if [[ ${(z):-'$('} == '$( ' ]]; then # ignore zsh 5.0.8 bug + expected_region_highlight[2]='3 16 default' # foo$(echo bar + expected_region_highlight[3]='6 16 command-substitution-unquoted' # $(echo bar +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/commandseparator.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/commandseparator.zsh new file mode 100644 index 00000000..f504847c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/commandseparator.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=':; pwd &! ls' + +expected_region_highlight=( + "1 1 builtin" # : + "2 2 commandseparator" # ; + "4 6 builtin" # pwd + "8 9 commandseparator" # &! + "11 12 command" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/comment-followed.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/comment-followed.zsh new file mode 100644 index 00000000..044f2830 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/comment-followed.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# see alias-comment1.zsh +setopt interactivecomments +BUFFER=$'# foo\ntrue' + +expected_region_highlight=( + '1 5 comment' # # foo + '6 6 commandseparator' # \n + '7 10 builtin' # true +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/comment-leading.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/comment-leading.zsh new file mode 100644 index 00000000..b4c99105 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/comment-leading.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +setopt interactive_comments + +BUFFER='# echo foo' + +expected_region_highlight=( + "1 10 comment" # # echo foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/comment-off.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/comment-off.zsh new file mode 100644 index 00000000..0381bdb0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/comment-off.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +unsetopt interactive_comments + +BUFFER='# echo foo' + +expected_region_highlight=( + "1 1 unknown-token" # # + "3 6 default" # " echo foo" + "8 10 default" # " echo foo" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/comments.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/comments.zsh new file mode 100644 index 00000000..f3cc57e4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/comments.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +setopt interactive_comments + +BUFFER='echo "foo #bar" #baz # quux' + +expected_region_highlight=( + "1 4 builtin" # echo + "6 15 default" # "foo #bar" + "6 15 double-quoted-argument" # "foo #bar" + "17 27 comment" # #baz # quux +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/commmand-parameter.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/commmand-parameter.zsh new file mode 100644 index 00000000..48d20ba8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/commmand-parameter.zsh @@ -0,0 +1,45 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +local x=/usr/bin/env +local y=sudo +local -a z; z=(zsh -f) +sudo(){} + +BUFFER='$x "argument"; $y; $z' + +expected_region_highlight=( + "1 2 command" # $x + "4 13 default" # "argument" + "4 13 double-quoted-argument" # "argument" + "14 14 commandseparator" # ; + "16 17 precommand" # $y (sudo) + "18 18 unknown-token" # ; + "20 21 command" # $z - 'zsh' being the command +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/control-flow.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/control-flow.zsh new file mode 100644 index 00000000..a610bdc3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/control-flow.zsh @@ -0,0 +1,57 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='while if echo Hello; then ls /; else ls; fi; do stat "x"; done; repeat 10 ls' + +expected_region_highlight+=( + "1 5 reserved-word" # while + "7 8 reserved-word" # if + "10 13 builtin" # echo + "15 19 default" # Hello + "20 20 commandseparator" # ; + "22 25 reserved-word" # then + "27 28 command" # ls + "30 30 path" # / + "31 31 commandseparator" # ; + "33 36 reserved-word" # else + "38 39 command" # ls + "40 40 commandseparator" # ; + "42 43 reserved-word" # fi + "44 44 commandseparator" # ; + "46 47 reserved-word" # do + "49 52 command" # stat + "54 56 default" # "x" + "54 56 double-quoted-argument" # "x" + "57 57 commandseparator" # ; + "59 62 reserved-word" # done + "63 63 commandseparator" # ; + "65 70 reserved-word" # repeat + "72 73 default" # 10 + "75 76 command" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/control-flow2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/control-flow2.zsh new file mode 100644 index 00000000..acf99e1d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/control-flow2.zsh @@ -0,0 +1,40 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='repeat 42; do ls; done' + +expected_region_highlight+=( + "1 6 reserved-word" # repeat + "8 9 default" # 42 + "10 10 commandseparator" # ; + "12 13 reserved-word" # do + "15 16 command" # ls + "17 17 commandseparator" # ; + "19 22 reserved-word" # done +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/control-flow3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/control-flow3.zsh new file mode 100644 index 00000000..58f507f9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/control-flow3.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='repeat 42; ls; pwd' + +expected_region_highlight+=( + "1 6 reserved-word" # repeat + "8 9 default" # 42 + "10 10 commandseparator" # ; + "12 13 command" # ls + "14 14 commandseparator" # ; + "16 18 builtin" # pwd +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/cthulhu.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/cthulhu.zsh new file mode 100644 index 00000000..c8119a84 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/cthulhu.zsh @@ -0,0 +1,70 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# 0000000 0 01111111111222222 222233333 3 333344 4 4 444444555555555 5 6 6666 6 6 6667777777777888 8 8 88888999 9 9999 9 9 00 00 0000001111 +# 1234567 8 90123456789012345 678901234 5 678901 2 3 456789012345678 9 0 1234 5 6 7890123456789012 3 4 56789012 3 4567 8 9 01 23 4567890123 +BUFFER=$'echo Ph\\\'ng`echo lui "mg"\\`echo lw\\\'nafh \\\\\\`echo Cthu"lhu\\\\\\` R\\\\\'ly$(echo eh wag\\\\\\`echo h\\\'nag\\\\\\`\'l\' fht)agn`' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 113 default' # Ph\'ng`echo lui "mg"\`echo lw\'nafh \\\`echo Cthu"lhu\\\` R\\'ly$(echo eh wag\\\`echo h\'nag\\\`'l' fht)agn` + '12 113 back-quoted-argument' # `echo lui "mg"\`echo lw\'nafh \\\`echo Cthu"lhu\\\` R\\'ly$(echo eh wag\\\`echo h\'nag\\\`'l' fht)agn` + '12 12 back-quoted-argument-delimiter' # ` + '13 16 builtin' # echo + '18 20 default' # lui + '22 112 default' # "mg"\`echo lw\'nafh \\\`echo Cthu"lhu\\\` R\\'ly$(echo eh wag\\\`echo h\'nag\\\`'l' fht)agn + '22 25 double-quoted-argument' # "mg" + '26 112 back-quoted-argument-unclosed' # \`echo lw\'nafh \\\`echo Cthu"lhu\\\` R\\'ly$(echo eh wag\\\`echo h\'nag\\\`'l' fht)agn + '26 27 back-quoted-argument-delimiter' # \` + '28 31 builtin' # echo + '33 40 default' # lw\'nafh + '42 62 default' # \\\`echo Cthu"lhu\\\` + '42 62 back-quoted-argument' # \\\`echo Cthu"lhu\\\` + '42 45 back-quoted-argument-delimiter' # \\\` + '46 49 builtin' # echo + '51 58 default' # Cthu"lhu + '55 58 double-quoted-argument-unclosed' # "lhu + '59 62 back-quoted-argument-delimiter' # \\\` + '64 112 default' # R\\'ly$(echo eh wag\\\`echo h\'nag\\\`'l' fht)agn + '70 109 command-substitution-unquoted' # $(echo eh wag\\\`echo h\'nag\\\`'l' fht) + '70 71 command-substitution-delimiter-unquoted' # $( + '72 75 builtin' # echo + '77 78 default' # eh + '80 104 default' # wag\\\`echo h\'nag\\\`'l' + '83 101 back-quoted-argument' # \\\`echo h\'nag\\\` + '83 86 back-quoted-argument-delimiter' # \\\` + '87 90 builtin' # echo + '92 97 default' # h\'nag + '98 101 back-quoted-argument-delimiter' # \\\` + '102 104 single-quoted-argument' # 'l' + '106 108 default' # fht + '109 109 command-substitution-delimiter-unquoted' # ) + '113 113 unknown-token' # ` +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dinbrack1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dinbrack1.zsh new file mode 100644 index 00000000..e2279d6b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dinbrack1.zsh @@ -0,0 +1,41 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'[[ foo && bar || baz ]]' + +expected_region_highlight=( + '1 2 reserved-word' # [[ + '4 6 default' # foo + '8 9 default' # && + '11 13 default' # bar + '15 16 default' # || + '18 20 default' # baz + '22 23 reserved-word' # ]] +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dirs_blacklist.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dirs_blacklist.zsh new file mode 100644 index 00000000..2d0222f0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dirs_blacklist.zsh @@ -0,0 +1,40 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +mkdir foo +touch foo/bar +BUFFER=": foo/bar $PWD/foo foo/b" +ZSH_HIGHLIGHT_DIRS_BLACKLIST=($PWD/foo $PWD/bar) + +expected_region_highlight=( + '1 1 builtin' # : + '3 9 default' # foo/bar + "11 $(( 14 + $#PWD )) default" # $PWD/foo + "$(( 16 + $#PWD )) $(( 20 + $#PWD )) default" # foo/b +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-dollar.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-dollar.zsh new file mode 100644 index 00000000..e3f387ce --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-dollar.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=': "$$ $$foo"' + +expected_region_highlight=( + '1 1 builtin' # : + '3 12 default' # "$$ $$foo" + '3 12 double-quoted-argument' # "$$ $$foo" + '4 5 dollar-double-quoted-argument' # $$ + '7 8 dollar-double-quoted-argument' # $$ +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-noise.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-noise.zsh new file mode 100644 index 00000000..9bb11bd8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-noise.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=': "$- $# $* $@ $?"' + +expected_region_highlight=( + '1 1 builtin' # : + '3 18 default' # "$- $# $* $@ $?" + '3 18 double-quoted-argument' # "$- $# $* $@ $?" + '4 5 dollar-double-quoted-argument' # $- + '7 8 dollar-double-quoted-argument' # $# + '10 11 dollar-double-quoted-argument' # $* + '13 14 dollar-double-quoted-argument' # $@ + '16 17 dollar-double-quoted-argument' # $? +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-paren.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-paren.zsh new file mode 100644 index 00000000..2bbcef18 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-paren.zsh @@ -0,0 +1,49 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=': "$(:)" "foo$(:)bar' + +expected_region_highlight=( + '1 1 builtin' # : + '3 8 default' # "$(:)" + '3 3 double-quoted-argument' # "$(:)" + '8 8 double-quoted-argument' # "$(:)" + '4 7 command-substitution-quoted' # $(:) + '4 5 command-substitution-delimiter-quoted' # $( + '6 6 builtin' # : + '7 7 command-substitution-delimiter-quoted' # ) + '10 20 default' # "foo$(:)bar + '10 13 double-quoted-argument-unclosed' # "foo + '18 20 double-quoted-argument-unclosed' # bar + '14 17 command-substitution-quoted' # $(:) + '14 15 command-substitution-delimiter-quoted' # $( + '16 16 builtin' # : + '17 17 command-substitution-delimiter-quoted' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-quoted.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-quoted.zsh new file mode 100644 index 00000000..081a365b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-quoted.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=": \$'*' 'foo'" + +expected_region_highlight=( + "1 1 builtin" # : + "3 6 default" # $'*' + "3 6 dollar-quoted-argument" # $'*' - not a glob + "8 12 default" # 'foo' + "8 12 single-quoted-argument" # 'foo' +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-quoted2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-quoted2.zsh new file mode 100644 index 00000000..ed7428bd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-quoted2.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=": \$'foo\xbar\udeadbeef\uzzzz'" + +expected_region_highlight=( + "1 1 builtin" # : + "3 29 default" # $'foo\xbar\udeadbeef\uzzzz' + "3 29 dollar-quoted-argument" # $'foo\xbar\udeadbeef\uzzzz' + "8 11 back-dollar-quoted-argument" # \xba + "13 18 back-dollar-quoted-argument" # \dead + "23 24 unknown-token" # \u +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-quoted3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-quoted3.zsh new file mode 100644 index 00000000..365f3519 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/dollar-quoted3.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Similar to double-quoted2.zsh +# This test checks that the '1' gets highlighted correctly. Do not append to the BUFFER. +BUFFER=": \$'\xa1" + +expected_region_highlight=( + "1 1 builtin" # : + "3 8 default" # $'\xa1 + "3 8 dollar-quoted-argument-unclosed" # $'\xa1 + "5 8 back-dollar-quoted-argument" # \xa1 +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-hyphen-option.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-hyphen-option.zsh new file mode 100644 index 00000000..e5cacd37 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-hyphen-option.zsh @@ -0,0 +1,35 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='hello --world' + +expected_region_highlight=( + "1 5 unknown-token" # hello + "7 13 double-hyphen-option" # --world +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-quoted.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-quoted.zsh new file mode 100644 index 00000000..0a4336ca --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-quoted.zsh @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=': "foo$bar:\`:\":\$:' +BUFFER+=\\\\:\" + +expected_region_highlight=( + "1 1 builtin" # : + "3 24 default" # "foo$bar:\`:\":\$:\\:" + "3 24 double-quoted-argument" # "foo$bar:\`:\":\$:\\:" + "7 10 dollar-double-quoted-argument" # $bar + "12 13 back-double-quoted-argument" # \` + "15 16 back-double-quoted-argument" # \$ + "18 19 back-double-quoted-argument" # \" + "21 22 back-double-quoted-argument" # \\ +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-quoted2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-quoted2.zsh new file mode 100644 index 00000000..c400e543 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-quoted2.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Similar to dollar-quoted3.zsh +# This test checks that the 'r' gets highlighted correctly. Do not append to the BUFFER. +BUFFER=': "foo$bar' + +expected_region_highlight=( + "1 1 builtin" # : + "3 10 default" # "foo$bar + "3 10 double-quoted-argument-unclosed" # "foo$bar + "7 10 dollar-double-quoted-argument" # $bar +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-quoted3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-quoted3.zsh new file mode 100644 index 00000000..86e3ced6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-quoted3.zsh @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=': "$" "$42foo"' +BUFFER+=\ \"\\\'\\x\" + +expected_region_highlight=( + "1 1 builtin" # : + "3 5 default" # "$" + "3 5 double-quoted-argument" # "$" + "7 14 default" # "$42foo" + "7 14 double-quoted-argument" # "$42foo" + "8 10 dollar-double-quoted-argument" # $42 + "16 21 default" # "\'\x" + "16 21 double-quoted-argument" # "\'\x" - \' and \x are not escape sequences +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-quoted4.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-quoted4.zsh new file mode 100644 index 00000000..c59d5d8e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/double-quoted4.zsh @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=': "${foo}bar"' + +expected_region_highlight=( + "1 1 builtin" # : + "3 13 default" # "${foo}bar" + "3 13 double-quoted-argument" # "${foo}bar" + "4 9 dollar-double-quoted-argument" # ${foo} +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/empty-command-newline.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/empty-command-newline.zsh new file mode 100644 index 00000000..4b7b35c6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/empty-command-newline.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Newline after semicolon isn't unknown-token +BUFFER=$':;\n:' + +expected_region_highlight=( + '1 1 builtin' # : + '2 2 commandseparator' # ; + '3 3 commandseparator' # \n + '4 4 builtin' # : +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/empty-command.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/empty-command.zsh new file mode 100644 index 00000000..5831464d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/empty-command.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='echo; ;' + +expected_region_highlight=( + "1 4 builtin" # echo + "5 5 commandseparator" # ; + "7 7 unknown-token" # ; +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/empty-command2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/empty-command2.zsh new file mode 100644 index 00000000..dcb4e6f7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/empty-command2.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Same test data and expectations as empty-command.zsh; the only difference is: +touch ';' + +BUFFER='echo; ;' + +expected_region_highlight=( + "1 4 builtin" # echo + "5 5 commandseparator" # ; + "7 7 unknown-token" # ; +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/empty-line.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/empty-line.zsh new file mode 100644 index 00000000..a4d6685b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/empty-line.zsh @@ -0,0 +1,36 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'\\\n; ls' + +expected_region_highlight=( + '3 3 unknown-token' # ; + '5 6 command' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/equals1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/equals1.zsh new file mode 100644 index 00000000..77f46e8d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/equals1.zsh @@ -0,0 +1,36 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': =ls' + +expected_region_highlight=( + '1 1 builtin' # : + '3 5 path' # =ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/equals2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/equals2.zsh new file mode 100644 index 00000000..bd59ff75 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/equals2.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +unsetopt equals + +BUFFER=$': =nosuchcommand' + +expected_region_highlight=( + '1 1 builtin' # : + '3 16 default' # =nosuchcommand +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/equals3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/equals3.zsh new file mode 100644 index 00000000..8c107890 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/equals3.zsh @@ -0,0 +1,36 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': =nosuchcommand' + +expected_region_highlight=( + '1 1 builtin' # : + '3 16 unknown-token' # =nosuchcommand +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/equals4.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/equals4.zsh new file mode 100644 index 00000000..28bc2148 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/equals4.zsh @@ -0,0 +1,36 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': =' + +expected_region_highlight=( + '1 1 builtin' # : + '3 3 default' # = +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/escaped-single-quote.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/escaped-single-quote.zsh new file mode 100644 index 00000000..4b2fe4bc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/escaped-single-quote.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': \'foo\'\\\'\'bar\'' # <<<: 'foo'\''bar'>>> + +expected_region_highlight=( + '1 1 builtin' # : + '3 14 default' # 'foo'\''bar' + '3 7 single-quoted-argument' # 'foo' + '10 14 single-quoted-argument' # 'bar' +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/exec-redirection1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/exec-redirection1.zsh new file mode 100644 index 00000000..78a0c623 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/exec-redirection1.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='exec {foo}>&/tmp ls' + +expected_region_highlight=( + "1 4 precommand" # exec + "6 10 named-fd" # {foo} + "11 12 redirection" # >& + "13 16 path" # /tmp + "18 19 command" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/fd-target-not-filename.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/fd-target-not-filename.zsh new file mode 100644 index 00000000..5c3cd089 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/fd-target-not-filename.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +touch 2 + +BUFFER=$'echo foo>&2' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 8 default' # foo + '9 10 redirection' # >& + '11 11 numeric-fd' # 2 (not path) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/function-altsyntax.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/function-altsyntax.zsh new file mode 100644 index 00000000..0f9a8339 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/function-altsyntax.zsh @@ -0,0 +1,45 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Define named and anonymous function using the alternative syntax +BUFFER=$'function f { pwd }; function { pwd }' + +expected_region_highlight=( + '1 8 reserved-word' # function + '10 10 default' # f + '12 12 reserved-word "issue #237"' # { + '14 16 command "issue #237"' # pwd + '18 18 reserved-word "issue #237"' # } + '19 19 commandseparator' # ; + '21 28 reserved-word' # function + '30 30 reserved-word "issue #237"' # { + '32 34 command "issue #237"' # pwd + '36 36 reserved-word "issue #237"' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/function-named1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/function-named1.zsh new file mode 100644 index 00000000..c962ddbb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/function-named1.zsh @@ -0,0 +1,44 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='f() pwd; f() { balanced braces }' + +expected_region_highlight=( + '1 1 TBD "issue #223"' # f + '2 3 reserved-word' # () + '5 7 builtin' # pwd + '8 8 commandseparator' # ; + '10 10 TBD "issue #223"' # f + '11 12 reserved-word' # () + '14 14 reserved-word' # { + '16 23 unknown-token' # balanced + '25 30 default' # braces + '32 32 reserved-word' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/function-named2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/function-named2.zsh new file mode 100644 index 00000000..e12fce6a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/function-named2.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='f g h () pwd' + +expected_region_highlight=( + '1 1 TBD "issue #223"' # f + '3 3 TBD "issue #223"' # g + '5 5 TBD "issue #223"' # h + '7 8 reserved-word' # () + '10 12 builtin' # pwd +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/function.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/function.zsh new file mode 100644 index 00000000..b1be8539 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/function.zsh @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +cd() { + builtin cd "$@" +} +ls() { + command ls "$@" +} +BUFFER='cd;ls' + +expected_region_highlight=( + "1 2 function" # cd + "3 3 commandseparator" # ; + "4 5 function" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/glob.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/glob.zsh new file mode 100644 index 00000000..2ff1022e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/glob.zsh @@ -0,0 +1,41 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=': foo* bar? *baz qux\?' + +expected_region_highlight=( + "1 1 builtin" # : + "3 6 default" # foo* + "6 6 globbing" # * + "8 11 default" # bar? + "11 11 globbing" # ? + "13 16 default" # *baz + "13 13 globbing" # * + "18 22 default" # qux\? +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/global-alias1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/global-alias1.zsh new file mode 100644 index 00000000..0022de3c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/global-alias1.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias -g foo=bar + +BUFFER=$'foo foo' + +expected_region_highlight=( + '1 3 global-alias' # foo + '5 7 global-alias' # foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/globs-with-quoting.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/globs-with-quoting.zsh new file mode 100644 index 00000000..d7d74bc4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/globs-with-quoting.zsh @@ -0,0 +1,43 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': "foo"*\'bar\'?"baz?"<17-29>"qu*ux"' + +expected_region_highlight=( + '1 1 builtin' # : + '3 34 default' # "foo"*'bar'?"baz?"<17-29>"qu*ux" + '3 7 double-quoted-argument' # "foo" + '8 8 globbing' # * + '9 13 single-quoted-argument' # 'bar' + '14 14 globbing' # ? + '15 20 double-quoted-argument' # "baz?" + '21 27 globbing' # <17-29> + '28 34 double-quoted-argument' # "qu*ux" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/hashed-command.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/hashed-command.zsh new file mode 100644 index 00000000..2983ef8d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/hashed-command.zsh @@ -0,0 +1,35 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +hash zsh_syntax_highlighting_hash=/doesnotexist +BUFFER='zsh_syntax_highlighting_hash' + +expected_region_highlight=( + "1 28 hashed-command 'zsh/parameter cannot distinguish between hashed and command'" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-escaped.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-escaped.zsh new file mode 100644 index 00000000..7807cc06 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-escaped.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='echo "Hello\!"' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 14 default' # "Hello\!" + '6 14 double-quoted-argument' # "Hello\!" + '12 13 back-double-quoted-argument' # \! +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-followed.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-followed.zsh new file mode 100644 index 00000000..6421ceda --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-followed.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=': !!= "!!="' + +expected_region_highlight=( + '1 1 builtin' # : + '3 4 history-expansion "issue #713"' # !! + '7 11 default' # "!!=" + '7 11 double-quoted-argument' # "!!=" + '8 9 history-expansion "issue #713' # !! +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-no.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-no.zsh new file mode 100644 index 00000000..e082dbcf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-no.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='echo "foo != bar !{baz}"' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 24 default' # "foo != bar !{baz}" + '6 24 double-quoted-argument' # "foo != bar !{baz}" - no history expansions +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-unescaped.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-unescaped.zsh new file mode 100644 index 00000000..cfe6a11d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-unescaped.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='echo "Hello!"' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 13 default' # "Hello!" + '6 13 double-quoted-argument' # "Hello!" + '12 12 history-expansion' # ! +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-yes.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-yes.zsh new file mode 100644 index 00000000..e963c3b9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-double-quoted-yes.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='echo "foo !bar"' + +expected_region_highlight=( + '1 4 builtin' # echo + '6 15 default' # "foo !bar" + '6 15 double-quoted-argument' # "foo !bar" + '11 11 history-expansion' # ! +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-expansion.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-expansion.zsh new file mode 100644 index 00000000..05e20fc1 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-expansion.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='!foo bar !baz ! ; !' + +expected_region_highlight=( + "1 4 history-expansion" # !foo + "6 8 default" # bar + "10 13 history-expansion" # !baz + "15 15 default" # ! + "17 17 commandseparator" # ; + "19 19 reserved-word" # ! +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-expansion2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-expansion2.zsh new file mode 100644 index 00000000..386d0df9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/history-expansion2.zsh @@ -0,0 +1,34 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='^foo^bar' + +expected_region_highlight=( + "1 8 history-expansion" # ^foo^bar +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/inheritance.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/inheritance.zsh new file mode 100644 index 00000000..e851ca3e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/inheritance.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +_zsh_highlight_add_highlight() +{ + region_highlight+=("$1 $2 ${(j.,.)argv[3,-1]}") +} + +BUFFER='type' + +expected_region_highlight=( + '1 4 builtin,arg0' # type +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/jobsubst-isnt-glob.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/jobsubst-isnt-glob.zsh new file mode 100644 index 00000000..3a7e325a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/jobsubst-isnt-glob.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018.9958 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': %? %?foo' + +expected_region_highlight=( + '1 1 builtin' # : + '3 4 default' # %? + '6 10 default' # %?foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/jobsubst-isnt-glob2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/jobsubst-isnt-glob2.zsh new file mode 100644 index 00000000..51930bfb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/jobsubst-isnt-glob2.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': foo%?bar' + +expected_region_highlight=( + '1 1 builtin' # : + '3 10 default' # foo%?bar + '7 7 globbing' # ? +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/loop-newline.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/loop-newline.zsh new file mode 100644 index 00000000..d39ee112 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/loop-newline.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'for i in \\\n; do done' + +expected_region_highlight=( + '1 3 reserved-word' # for + '5 5 default' # i + '7 8 default' # in + '12 12 commandseparator' # ; + '14 15 reserved-word' # do + '17 20 reserved-word' # done +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/meta-no-eval1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/meta-no-eval1.zsh new file mode 100644 index 00000000..bb040777 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/meta-no-eval1.zsh @@ -0,0 +1,49 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': $(kill -9 $$) ${:-$(kill -9 $$)}' + +expected_region_highlight=( + '1 1 builtin' # : + '3 15 default' # $(kill -9 $$) + '3 15 command-substitution-unquoted' # $(kill -9 $$) + '3 4 command-substitution-delimiter-unquoted' # $( + '5 8 builtin' # kill + '10 11 single-hyphen-option' # -9 + '13 14 default' # $$ + '15 15 command-substitution-delimiter-unquoted' # ) + '17 34 default' # ${:-$(kill -9 $$)} + '21 33 command-substitution-unquoted' # $(kill -9 $$) + '21 22 command-substitution-delimiter-unquoted' # $( + '23 26 builtin' # kill + '28 29 single-hyphen-option' # -9 + '31 32 default' # $$ + '33 33 command-substitution-delimiter-unquoted' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/meta-no-eval2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/meta-no-eval2.zsh new file mode 100644 index 00000000..61ef0892 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/meta-no-eval2.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# We aren't testing how this is highlighted; we're testing that it's not +# evaluated. If it gets evaluated, the test suite will die. +BUFFER=$': /(e*exit 42*)' + +expected_region_highlight=( + '1 1 builtin' # : + '3 15 default' # /(e*exit 42*) + '6 6 globbing' # * + '14 14 globbing' # * +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiline-array-assignment1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiline-array-assignment1.zsh new file mode 100644 index 00000000..8906cfde --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiline-array-assignment1.zsh @@ -0,0 +1,41 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'foo=(\nbar) env' + +expected_region_highlight=( + '1 5 assign' # foo=( + '5 5 reserved-word' # ( + '6 6 commandseparator' # \n + '7 9 default' # bar + '10 10 assign' # ) + '10 10 reserved-word' # ) + '12 14 precommand' # env +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiline-string.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiline-string.zsh new file mode 100644 index 00000000..0127b4bf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiline-string.zsh @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +PREBUFFER=$'echo "foo1\n' +BUFFER='foo2" ./' + +expected_region_highlight=( + "1 5 default" # 'foo2"' + "1 5 double-quoted-argument" # 'foo2"' + "7 8 path" # './' +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiline-string2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiline-string2.zsh new file mode 100644 index 00000000..3a90dce8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiline-string2.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'echo \'foo1\n' + +expected_region_highlight=( + "1 4 builtin" # echo + "6 11 default" # 'foo1\n + "6 11 single-quoted-argument-unclosed" # 'foo1\n +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multios-negates-globbing.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multios-negates-globbing.zsh new file mode 100644 index 00000000..7ece6708 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multios-negates-globbing.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +unsetopt multios + +BUFFER=$'cat < *' + +expected_region_highlight=( + '1 3 command' # cat + '5 5 redirection' # < + '7 7 default' # * - not globbing +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multios-negates-globbing2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multios-negates-globbing2.zsh new file mode 100644 index 00000000..b6db983d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multios-negates-globbing2.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'cat < *' + +expected_region_highlight=( + '1 3 command' # cat + '5 5 redirection' # < + '7 7 default' # * + '7 7 globbing' # * +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiple-quotes.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiple-quotes.zsh new file mode 100644 index 00000000..dabf70c8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiple-quotes.zsh @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': \'foo\'bar"baz$quux/foo\\\\bar"baz$\'quux\\nfoo\\001bar\'baz' + +expected_region_highlight=( + "1 1 builtin" # : + "3 54 default" # 'foo'bar"baz$quux/foo\\bar"baz$'quux\nfoo\001'baz + "3 7 single-quoted-argument" # 'foo' + "11 29 double-quoted-argument" #"baz + "15 19 dollar-double-quoted-argument" # $quux + "24 25 back-double-quoted-argument" # \\ + "33 51 dollar-quoted-argument" # $'quux\nfoo\001bar' + "39 40 back-dollar-quoted-argument" # \n + "44 47 back-dollar-quoted-argument" # \001 +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiple-redirections.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiple-redirections.zsh new file mode 100644 index 00000000..778e7129 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/multiple-redirections.zsh @@ -0,0 +1,46 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2011 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='ps aux | grep java | sort | uniq | tail | head' + +expected_region_highlight=( + "1 2 command" # ps + "4 6 default" # aux + "8 8 commandseparator" # | + "10 13 command" # grep + "15 18 default" # java + "20 20 commandseparator" # | + "22 25 command" # sort + "27 27 commandseparator" # | + "29 32 command" # uniq + "34 34 commandseparator" # | + "36 39 command" # tail + "41 41 commandseparator" # | + "43 46 command" # head +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob-alias.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob-alias.zsh new file mode 100644 index 00000000..2f96445e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob-alias.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias x=command +BUFFER='x ls' + +expected_region_highlight=( + "1 1 alias" # x + "3 4 command" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob-always.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob-always.zsh new file mode 100644 index 00000000..6d550489 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob-always.zsh @@ -0,0 +1,45 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'{ noglob echo * } always { echo * }' + +expected_region_highlight=( + '1 1 reserved-word' # { + '3 8 precommand' # noglob + '10 13 builtin' # echo + '15 15 default' # * + '17 17 reserved-word' # } + '19 24 reserved-word' # always + '26 26 reserved-word' # { + '28 31 builtin' # echo + '33 33 default' # * + '33 33 globbing' # * + '35 35 reserved-word' # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob1.zsh new file mode 100644 index 00000000..1857db0c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob1.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=':; noglob echo *' + +expected_region_highlight=( + "1 1 builtin" # : + "2 2 commandseparator" # ; + "4 9 precommand" # noglob + "11 14 builtin" # echo + "16 16 default" # * +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob2.zsh new file mode 100644 index 00000000..3b4fcd76 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob2.zsh @@ -0,0 +1,40 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='noglob echo *; echo *' + +expected_region_highlight=( + "1 6 precommand" # noglob + "8 11 builtin" # echo + "13 13 default" # * + "14 14 commandseparator" # ; + "16 19 builtin" # echo + "21 21 default" # * + "21 21 globbing" # * +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob3.zsh new file mode 100644 index 00000000..c404aaac --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob3.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +touch \* + +BUFFER='noglob echo *' + +expected_region_highlight=( + "1 6 precommand" # noglob + "8 11 builtin" # echo + "13 13 path" # * +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob4.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob4.zsh new file mode 100644 index 00000000..cc7065f5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/noglob4.zsh @@ -0,0 +1,45 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'noglob cat <(print -r -- *)' + +expected_region_highlight=( + '1 6 precommand' # noglob + '8 10 command' # cat + '12 27 default' # <(print -r -- *) + '12 27 process-substitution' # <(print -r -- *) + '12 13 process-substitution-delimiter' # <( + '14 18 builtin' # print + '20 21 single-hyphen-option' # -r + '23 24 double-hyphen-option' # -- + '26 26 default' # * + '26 26 globbing' # * + '27 27 process-substitution-delimiter' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/null-exec.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/null-exec.zsh new file mode 100644 index 00000000..be1e3064 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/null-exec.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'exec >/dev/null;' + +expected_region_highlight=( + '1 4 precommand' # exec + '6 6 redirection' # > + '7 15 path' # /dev/null + '16 16 commandseparator' # ; +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/null-exec2-printenv.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/null-exec2-printenv.zsh new file mode 100644 index 00000000..59a2cef7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/null-exec2-printenv.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2021 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'env | grep $needle' + +expected_region_highlight=( + '1 3 precommand' # env + '5 5 commandseparator' # | + '7 10 command' # grep + '12 18 default' # $needle +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/number_range-glob.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/number_range-glob.zsh new file mode 100644 index 00000000..c8409510 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/number_range-glob.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='print <-> x<->y ' + +expected_region_highlight=( + '1 5 builtin' # print + '7 9 default' # <-> + '7 9 globbing' # <-> + '11 15 default' # x<->y + '12 14 globbing' # <-> + '17 17 redirection' # < + '18 23 default' # foo2-3 (the filename) + '24 24 redirection' # > +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/off-by-one.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/off-by-one.zsh new file mode 100644 index 00000000..872143af --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/off-by-one.zsh @@ -0,0 +1,40 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +alias a=: +f() {} + +BUFFER='a;f;' + +expected_region_highlight=( + "1 1 alias" # a + "2 2 commandseparator" # ; + "3 3 function" # f + "4 4 commandseparator" # ; +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/opt-shwordsplit1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/opt-shwordsplit1.zsh new file mode 100644 index 00000000..4a7689be --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/opt-shwordsplit1.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +setopt shwordsplit +local EDITOR='ed -s' + +ed() { command ed "$@" } + +BUFFER=$'$EDITOR' + +expected_region_highlight=( + '1 7 function' # $EDITOR +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/optimized-cmdsubst-input.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/optimized-cmdsubst-input.zsh new file mode 100644 index 00000000..ca55ef83 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/optimized-cmdsubst-input.zsh @@ -0,0 +1,43 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# See getoutput() and getoutputfile() in zsh's C source code. + +BUFFER=$': $(<*)' + +expected_region_highlight=( + '1 1 builtin' # : + '3 7 default' # $(<*) + '3 7 command-substitution-unquoted' # $(<*) + '3 4 command-substitution-delimiter-unquoted' # $( + '5 5 redirection' # < + '6 6 default' # * - not globbing! + '7 7 command-substitution-delimiter-unquoted' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/option-dollar-quote-isnt-filename.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/option-dollar-quote-isnt-filename.zsh new file mode 100644 index 00000000..897a02e6 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/option-dollar-quote-isnt-filename.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': -$\'n\'' + +touch ./-n + +expected_region_highlight=( + '1 1 builtin' # : + '3 7 single-hyphen-option' # -$'n' + '4 7 dollar-quoted-argument' # $'n' +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/option-path_dirs.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/option-path_dirs.zsh new file mode 100644 index 00000000..0300c7e5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/option-path_dirs.zsh @@ -0,0 +1,44 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +if [[ $OSTYPE == msys ]]; then + skip_test='Cannot chmod +x in msys2' +else + setopt PATH_DIRS + mkdir -p foo/bar + touch foo/bar/testing-issue-228 + chmod +x foo/bar/testing-issue-228 + path+=( "$PWD"/foo ) + + BUFFER='bar/testing-issue-228' + + expected_region_highlight=( + "1 21 command" # bar/testing-issue-228 + ) +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/option-with-quotes.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/option-with-quotes.zsh new file mode 100644 index 00000000..6286f034 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/option-with-quotes.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': --user="phy1729"' + +expected_region_highlight=( + '1 1 builtin' # : + '3 18 double-hyphen-option' # --user="phy1729" + '10 18 double-quoted-argument' # "phy1729" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/order-path-after-dollar.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/order-path-after-dollar.zsh new file mode 100644 index 00000000..773c1838 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/order-path-after-dollar.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +touch '$foo' +BUFFER=': $foo \$foo' + +expected_region_highlight=( + '1 1 builtin' # : + '3 6 default' # $foo - if we add a "unquoted parameter expansion" style then this expectation should change + '8 12 path' # \$foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/order-path-before-globbing.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/order-path-before-globbing.zsh new file mode 100644 index 00000000..8456b181 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/order-path-before-globbing.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +touch '*' +BUFFER=': * \*' + +expected_region_highlight=( + '1 1 builtin' # : + '3 3 default' # * + '3 3 globbing' # * + '5 6 path' # \* +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/param-positional-in-array-append.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/param-positional-in-array-append.zsh new file mode 100644 index 00000000..bd39e021 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/param-positional-in-array-append.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# This used to be an infinite loop. + +BUFFER=$'l+=( $1' + +expected_region_highlight=( + '1 4 assign' # l+=( + '4 4 reserved-word' # ( + '6 7 default' # $1 +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/param-precommand-option-argument1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/param-precommand-option-argument1.zsh new file mode 100644 index 00000000..84cf03ac --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/param-precommand-option-argument1.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# See also alias-precommand-option-argument1.zsh +local -a sudo_u; sudo_u=(sudo -u) +sudo(){} + +BUFFER='$sudo_u phy1729 echo foo' + +expected_region_highlight=( + '1 7 precommand' # $sudo_u + '9 15 default' # phy1729 + '18 20 command "issue #540"' # echo (not builtin) + '22 24 default' # foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/param-precommand-option-argument3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/param-precommand-option-argument3.zsh new file mode 100644 index 00000000..9a8dde28 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/param-precommand-option-argument3.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# See also alias-precommand-option-argument3.zsh +local -a sudo_u; sudo_u=(sudo -u) +sudo(){} + +BUFFER='$sudo_u phy1729 ls foo' + +expected_region_highlight=( + '1 7 precommand' # sudo_u + '9 15 default' # phy1729 + '17 18 command' # ls + '20 22 default' # foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-elision-command-word.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-elision-command-word.zsh new file mode 100644 index 00000000..25f649a2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-elision-command-word.zsh @@ -0,0 +1,36 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='$x ls' + +expected_region_highlight=( + '1 2 comment' # $x + '4 5 command' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-expansion-shwordsplit.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-expansion-shwordsplit.zsh new file mode 100644 index 00000000..0bf6f4c0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-expansion-shwordsplit.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2021 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +setopt sh_word_split +local foo='echo foo' + +BUFFER='$foo' + +expected_region_highlight=( + '1 4 builtin' # $foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-expansion-untokenized1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-expansion-untokenized1.zsh new file mode 100644 index 00000000..8b8b5e4c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-expansion-untokenized1.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +local x="()" + +BUFFER=$'$x ls' + +expected_region_highlight=( + '1 2 unknown-token' # $x + '4 5 command' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-expansion-untokenized2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-expansion-untokenized2.zsh new file mode 100644 index 00000000..d23a1f21 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-expansion-untokenized2.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +local x="^foo^bar" + +BUFFER=$'$x ls' + +expected_region_highlight=( + '1 2 unknown-token' # $x + '4 5 default' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-star.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-star.zsh new file mode 100644 index 00000000..2311be07 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-star.zsh @@ -0,0 +1,40 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='() { : $* }' + +# This tests that $* isn't highlighted as a glob. +# If we ever add a "unquoted parameter" style, the expectation may change. +expected_region_highlight=( + "1 2 reserved-word" # () + "4 4 reserved-word" # { + "6 6 builtin" # : + "8 9 default" # $* + "11 11 reserved-word" # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-to-global-alias.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-to-global-alias.zsh new file mode 100644 index 00000000..cd2283bf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-to-global-alias.zsh @@ -0,0 +1,42 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +if type x >/dev/null; then + skip_test="Test is written on the assumption that 'x' is not a valid command name, but that assumption does not hold" + return 0 +fi +alias -g x=y +local s=x + +BUFFER=$'$s' + +expected_region_highlight=( + '1 2 unknown-token' # $s +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-value-contains-command-position1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-value-contains-command-position1.zsh new file mode 100644 index 00000000..05ea1bfa --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-value-contains-command-position1.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +local foobar='x=$(ls)' + +BUFFER=$'$foobar' + +expected_region_highlight=( + # Used to highlight the "ba" as 'command' because the 'ls' showed through; issues #670 and #674 + '1 7 unknown-token' # $foobar (not an assignment) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-value-contains-command-position2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-value-contains-command-position2.zsh new file mode 100644 index 00000000..5042e899 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/parameter-value-contains-command-position2.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +local y='x=$(ls)' + +BUFFER=$'$y' + +expected_region_highlight=( + # Used to trigger a "BUG" message on stderr - issues #670 and #674 + '1 2 unknown-token' # $y (not an assignment) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/pasted-quotes.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/pasted-quotes.zsh new file mode 100644 index 00000000..f37f21b3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/pasted-quotes.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2013 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': \'foo\'bar"baz"' + +expected_region_highlight=( + '1 1 builtin' # : + '3 15 default' # \'foo\'bar"baz" + '3 7 single-quoted-argument' # \'foo\' + '11 15 double-quoted-argument' # "baz" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-broken-symlink.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-broken-symlink.zsh new file mode 100644 index 00000000..baebee36 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-broken-symlink.zsh @@ -0,0 +1,41 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +if [[ $OSTYPE == msys ]]; then + skip_test='Cannot create symlinks in msys2' +else + ln -s /nonexistent broken-symlink + BUFFER=': broken-symlink' + CURSOR=5 # to make path_prefix ineligible + + expected_region_highlight=( + "1 1 builtin" # : + "3 16 path" # broken-symlink + ) +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word.zsh new file mode 100644 index 00000000..99055da9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word.zsh @@ -0,0 +1,45 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +if [[ $OSTYPE == msys ]]; then + skip_test='Cannot chmod +x in msys2' # cargo culted from option-path_dirs.zsh +else + mkdir kappa + touch kappa.exe + chmod +x kappa.exe + cd kappa + + BUFFER='$PWD.exe; ${PWD}.exe' + + expected_region_highlight=( + "1 8 unknown-token" # $PWD.exe - not eval'd; issue #328 + "9 9 commandseparator" # ; + "11 20 unknown-token" # ${PWD}.exe + ) +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word2.zsh new file mode 100644 index 00000000..f404d5d0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word2.zsh @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +local lambda="''" +touch \$lambda +BUFFER=': \$lambda' + +expected_region_highlight=( + "1 1 builtin" # : + "3 10 path" # \$lambda +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word3.zsh new file mode 100644 index 00000000..ec981b1e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word3.zsh @@ -0,0 +1,40 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# «/usr» at this point would be highlighted as path_prefix; so should +# a parameter that expands to an equivalent string be highlighted. +# +# More complicated parameter substitutions aren't eval'd; issue #328. +BUFFER='$PWD; ${PWD}' + +expected_region_highlight=( + "1 4 unknown-token" # $PWD (without AUTO_CD) + "5 5 commandseparator" # ; + "7 12 path_prefix" # ${PWD} +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word3b.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word3b.zsh new file mode 100644 index 00000000..72a2f7c4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word3b.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +setopt autocd +BUFFER=$'$PWD; ${PWD}' + +expected_region_highlight=( + '1 4 autodirectory' # $PWD + '5 5 commandseparator' # ; + '7 12 autodirectory' # ${PWD} +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word4.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word4.zsh new file mode 100644 index 00000000..e29182cc --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-dollared-word4.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# This tests for a regression during development of issue #328: an interim version +# of that branch failed that test with "Bail out! output on stderr". +BUFFER='${' + +expected_region_highlight=( + "1 2 unknown-token" # ${ +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-mixed-quoting.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-mixed-quoting.zsh new file mode 100644 index 00000000..cbd0b38e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-mixed-quoting.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +touch foo + +BUFFER=$': \'f\'oo' + +expected_region_highlight=( + '1 1 builtin' # : + '3 7 path' # \'f\'oo + '3 5 single-quoted-argument' # \'f\' +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-separators.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-separators.zsh new file mode 100644 index 00000000..52749b79 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-separators.zsh @@ -0,0 +1,53 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# ZSH_HIGHLIGHT_STYLES is empty in tests. The path-separator code however compares its values. +# Make sure the relevant ones are set to something. +ZSH_HIGHLIGHT_STYLES[path_pathseparator]=set +ZSH_HIGHLIGHT_STYLES[path_prefix_pathseparator]=set + +mkdir A +touch A/mu +BUFFER='ls /bin/ / A/mu A/m' + +expected_region_highlight=( + "1 2 command" # ls + "4 8 path" # /bin/ + "4 4 path_pathseparator" # / + "8 8 path_pathseparator" # / + + "10 10 path" # / + "10 10 path_pathseparator" # / + + "12 15 path" # A/mu + "13 13 path_pathseparator" # / + + "17 19 path_prefix" # A/m + "18 18 path_prefix_pathseparator" # / +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-separators2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-separators2.zsh new file mode 100644 index 00000000..bc885a06 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-separators2.zsh @@ -0,0 +1,40 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# ZSH_HIGHLIGHT_STYLES is empty in tests. The path-separator code however compares its values. +# For this test, make sure both these styles are set and identical: +ZSH_HIGHLIGHT_STYLES[path]=value +ZSH_HIGHLIGHT_STYLES[path_pathseparator]=value + +BUFFER='ls /bin/' + +expected_region_highlight=( + "1 2 command" # ls + "4 8 path" # /bin/ +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-space.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-space.zsh new file mode 100644 index 00000000..87cc22f9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-space.zsh @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2011 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +mkdir A +touch "A/mu with spaces" +BUFFER='ls A/mu\ with\ spaces' + +expected_region_highlight=( + "1 2 command" # ls + "4 21 path" # A/mu\ with\ spaces +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-tilde-home.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-tilde-home.zsh new file mode 100644 index 00000000..8b1c6805 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-tilde-home.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2011 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +HOME="." +BUFFER='ls ~' + +expected_region_highlight=( + "1 2 command" # ls + "4 4 path" # ~ +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-tilde-home2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-tilde-home2.zsh new file mode 100644 index 00000000..3f7b8200 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-tilde-home2.zsh @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +HOME="/nonexistent" +BUFFER='ls ~' + +expected_region_highlight=( + "1 2 command" # ls + "4 4 default" # ~ +) + diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-tilde-home3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-tilde-home3.zsh new file mode 100644 index 00000000..5c076e88 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-tilde-home3.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +HOME="." +BUFFER='ls \~' + +expected_region_highlight=( + "1 2 command" # ls + "4 5 default" # \~ +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-tilde-named.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-tilde-named.zsh new file mode 100644 index 00000000..335b3fdf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path-tilde-named.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +mkdir mydir +touch mydir/path-tilde-named.test +hash -d D=mydir + +BUFFER='ls ~D/path-tilde-named.test' + +expected_region_highlight=( + "1 2 command" # ls + "4 27 path" # ~D/path-tilde-named.test +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path.zsh new file mode 100644 index 00000000..d387eff3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path.zsh @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2011 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +mkdir A +touch A/mu +BUFFER='ls A/mu' + +expected_region_highlight=( + "1 2 command" # ls + "4 7 path" # A/mu +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path_prefix.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path_prefix.zsh new file mode 100644 index 00000000..3303bfb4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path_prefix.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Assumes that '/bin/sh' exists and '/bin/s' does not exist. +# Related to path_prefix2.zsh + +BUFFER='ls /bin/s' + +expected_region_highlight=( + "1 2 command" # ls + "4 9 path_prefix" # /bin/s +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path_prefix2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path_prefix2.zsh new file mode 100644 index 00000000..4f40f7e9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path_prefix2.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Assumes that '/bin/sh' exists and '/bin/s' does not exist. +# Related to path_prefix.zsh + +BUFFER='ls /bin/s' +WIDGET=zle-line-finish + +expected_region_highlight=( + "1 2 command" # ls + "4 9 default" # /bin/s +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path_prefix3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path_prefix3.zsh new file mode 100644 index 00000000..9f34f943 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/path_prefix3.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Assumes that '/bin/sh' exists and '/bin/s' does not exist. +# Related to path_prefix.zsh + +PREBUFFER=$'ls \\\n' +BUFFER='/bin/s' + +expected_region_highlight=( + '1 6 path_prefix' # /bin/s +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/plain-file-in-command-position.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/plain-file-in-command-position.zsh new file mode 100644 index 00000000..141fface --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/plain-file-in-command-position.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +touch foo +chmod -x foo +BUFFER=$'./foo; ./foo' + +expected_region_highlight=( + '1 5 unknown-token' # ./foo (in middle) + '6 6 commandseparator' # ; + '8 12 unknown-token' # ./foo (at end) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-killing1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-killing1.zsh new file mode 100644 index 00000000..75983460 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-killing1.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +hash sudo=false +touch foo + +BUFFER='sudo -e ./foo' + +expected_region_highlight=( + '1 4 precommand' # sudo + '6 7 single-hyphen-option' # -e + '9 13 path' # ./foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-killing2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-killing2.zsh new file mode 100644 index 00000000..bc6fc866 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-killing2.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +hash sudo=false + +BUFFER='sudo -e /does/not/exist' + +expected_region_highlight=( + '1 4 precommand' # sudo + '6 7 single-hyphen-option' # -e + '9 23 default' # /does/not/exist +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-then-assignment.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-then-assignment.zsh new file mode 100644 index 00000000..f0bb75ff --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-then-assignment.zsh @@ -0,0 +1,37 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'nice x=y ls' + +expected_region_highlight=( + '1 4 precommand' # nice + '6 8 unknown-token "issue #641.5"' # x=y + '10 11 default "issue #641.5 (fallout)"' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-type1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-type1.zsh new file mode 100644 index 00000000..4ce817c2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-type1.zsh @@ -0,0 +1,61 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Test the behaviour of a builtin that exists as a command as well. +# The spaces in $BUFFER are to align precommand-type*.zsh test files. +BUFFER=$'test ; builtin test ; builtin command test ; nice test ' + +# Our expectations assumes that a 'test' external command exists (in addition +# to the 'test' builtin). Let's verify that, using the EQUALS option (which +# is on by default). If there's no 'test' command, the expansion will fail, +# diagnose a message on stdout, and the harness will detect a failure. +# +# This seems to work on all platforms, insofar as no one ever reported a bug +# about their system not having a 'test' binary in PATH. That said, if someone +# ever does see this test fail for this reason, we should explicitly create +# a 'test' executable in cwd and 'rehash'. +: =test + +expected_region_highlight=( + '1 4 builtin' # test + '7 7 commandseparator' # ; + + '9 15 precommand' # builtin + '17 20 builtin' # test + '23 23 commandseparator' # ; + + '25 31 precommand' # builtin + '33 39 precommand' # command + '41 44 command "issue #608"' # test + '47 47 commandseparator' # ; + + '49 52 precommand' # nice + '54 57 command "issue #608"' # test +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-type2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-type2.zsh new file mode 100644 index 00000000..bf75f4b5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-type2.zsh @@ -0,0 +1,55 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Test the behaviour of a builtin that does not exist as a command. +# The spaces in $BUFFER are to align precommand-type*.zsh test files. +BUFFER=$'zstyle; builtin zstyle; builtin command zstyle; nice zstyle' + +# Verify that no $^path/zstyle(N) binary exists. +if (disable zstyle; type zstyle >/dev/null); then + echo >&2 "precommand-type2: error: 'zstyle' exists not only as a builtin" +fi + +expected_region_highlight=( + '1 6 builtin' # zstyle + '7 7 commandseparator' # ; + + '9 15 precommand' # builtin + '17 22 builtin' # zstyle + '23 23 commandseparator' # ; + + '25 31 precommand' # builtin + '33 39 precommand' # command + '41 46 unknown-token "issue #608"' # zstyle + '47 47 commandseparator' # ; + + '49 52 precommand' # nice + '54 59 unknown-token "issue #608"' # zstyle +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-type3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-type3.zsh new file mode 100644 index 00000000..7fc7e4c5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-type3.zsh @@ -0,0 +1,55 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Test an external command that does not exist as a builtin. +# The spaces in $BUFFER are to align precommand-type*.zsh test files. +BUFFER=$'ls ; builtin ls ; builtin command ls ; nice ls ' + +# Verify that the 'ls' command isn't shadowed. +if [[ $(type -w ls) != "ls: command" ]]; then + echo >&2 "precommand-type3: error: the 'ls' command is shadowed (or possibly missing altogether)" +fi + +expected_region_highlight=( + '1 2 command' # ls + '7 7 commandseparator' # ; + + '9 15 precommand' # builtin + '17 18 unknown-token "issue #608"' # ls + '23 23 commandseparator' # ; + + '25 31 precommand' # builtin + '33 39 precommand' # command + '41 42 command' # ls + '47 47 commandseparator' # ; + + '49 52 precommand' # nice + '54 55 command' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-uninstalled.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-uninstalled.zsh new file mode 100644 index 00000000..03c8a75a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-uninstalled.zsh @@ -0,0 +1,44 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Simulate sudo not being installed. +# +# The 'hash' step is because, if sudo _really_ isn't installed, 'unhash sudo' +# would error out and break the test. +hash sudo=/usr/bin/env && unhash sudo + +local PATH + +BUFFER=$'sudo ls' + +expected_region_highlight=( + '1 4 unknown-token' # sudo + '6 7 default' # ls - not 'command', since sudo isn't installed +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-unknown-option.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-unknown-option.zsh new file mode 100644 index 00000000..6baf9ff5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand-unknown-option.zsh @@ -0,0 +1,43 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +sudo(){} + +BUFFER='sudo -ux ls; sudo -x ls' + +expected_region_highlight=( + '1 4 precommand' # sudo + '6 8 single-hyphen-option' # -ux + '10 11 command' # ls + '12 12 commandseparator' # ; + '14 17 precommand' # sudo + '19 20 single-hyphen-option' # -x + '22 23 command' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand.zsh new file mode 100644 index 00000000..a03b3317 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=': command zzzzzz' + +expected_region_highlight=( + "1 1 builtin" # : + "3 9 default" # not precommand + "11 16 default" # not unknown-token (since 'zzzzzz' is not a command) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand2.zsh new file mode 100644 index 00000000..75dceabe --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand2.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='command -v ls' + +expected_region_highlight=( + "1 7 precommand" # command + "9 10 single-hyphen-option" # -v + "12 13 command" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand3.zsh new file mode 100644 index 00000000..f8b0c780 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand3.zsh @@ -0,0 +1,41 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='nice -n10 ls; nice -n 10 ls' + +expected_region_highlight=( + "1 4 precommand" # nice + "6 9 single-hyphen-option" # -n10 + "11 12 command" # ls + "13 13 commandseparator" # ; + "15 18 precommand" # nice + "20 21 single-hyphen-option" # -n + "23 24 default" # 10 + "26 27 command" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand4.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand4.zsh new file mode 100644 index 00000000..b9e6119d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/precommand4.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +doas(){} +BUFFER=$'doas -nu phy1729 ls' + +expected_region_highlight=( + '1 4 precommand' # doas + '6 8 single-hyphen-option' # -nu + '10 16 default' # phy1729 + '18 19 command' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/prefix-redirection.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/prefix-redirection.zsh new file mode 100644 index 00000000..a0f0ed5a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/prefix-redirection.zsh @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='>/tmp >/tmp command echo >/tmp foo' + +expected_region_highlight=( + "1 1 redirection" # > + "2 5 path" # /tmp + "7 7 redirection" # > + "8 11 path" # /tmp + "13 19 precommand" # command + "21 24 builtin" # echo + "26 26 redirection" # > + "27 30 path" # /tmp + "32 34 default" # foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/process-substitution-after-redirection.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/process-substitution-after-redirection.zsh new file mode 100644 index 00000000..2d58016f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/process-substitution-after-redirection.zsh @@ -0,0 +1,46 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017, 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'< <(pwd) > >(nl)' + +expected_region_highlight=( + '1 1 redirection' # < + '3 8 default' # <(pwd) + '3 8 process-substitution' # <(pwd) + '3 4 process-substitution-delimiter' # <( + '5 7 builtin' # pwd + '8 8 process-substitution-delimiter' # ) + '10 10 redirection' # > + '12 16 default' # >(nl) + '12 16 process-substitution' # >(nl) + '12 13 process-substitution-delimiter' # >( + '14 15 command' # nl + '16 16 process-substitution-delimiter' # ) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/process-substitution-redirection-isnt-globbing.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/process-substitution-redirection-isnt-globbing.zsh new file mode 100644 index 00000000..f8dbd6ba --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/process-substitution-redirection-isnt-globbing.zsh @@ -0,0 +1,41 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': =(" foo ls' + +expected_region_highlight=( + '1 3 unknown-token' # ">" - not "redirection" + '5 7 default' # foo + '9 10 default' # ls - not "command" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/rc-quotes.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/rc-quotes.zsh new file mode 100644 index 00000000..8cd427ae --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/rc-quotes.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +setopt RC_QUOTES + +BUFFER=": 'foo''bar'baz" + +expected_region_highlight=( + "1 1 builtin" # : + "3 15 default" # 'foo''bar'baz + "3 12 single-quoted-argument" # 'foo''bar' + "7 8 rc-quote" # '' +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection-comment.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection-comment.zsh new file mode 100644 index 00000000..a019100c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection-comment.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +setopt interactive_comments + +BUFFER=': <<#foo' + +expected_region_highlight=( + "1 1 builtin" # : + "3 4 redirection" # << + "5 8 comment" # #foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection-from-param.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection-from-param.zsh new file mode 100644 index 00000000..42ae6380 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection-from-param.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +touch file +local fn=$PWD/file + +BUFFER=$'<$fn cat' + +expected_region_highlight=( + '1 1 redirection' # < + '2 4 path' # $fn + '6 8 command' # cat +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection-in-cmdsubst.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection-in-cmdsubst.zsh new file mode 100644 index 00000000..ed5eaef8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection-in-cmdsubst.zsh @@ -0,0 +1,41 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$': $( -x >> --yy' + +expected_region_highlight=( + '1 1 builtin' # : + '3 3 redirection' # > + '5 6 default' # -x + '8 9 redirection' # >> + '11 14 default' # --yy +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection-special-cases.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection-special-cases.zsh new file mode 100644 index 00000000..733cf6bd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection-special-cases.zsh @@ -0,0 +1,44 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# See xpandredir() in the zsh source. + +BUFFER=$'cat <&p; exec {myfd}>&-' + +expected_region_highlight=( + '1 3 command' # cat + '5 6 redirection' # <& + '7 7 redirection' # p + '8 8 commandseparator' # ; + '10 13 precommand' # exec + '15 20 named-fd' # {myfd} + '21 22 redirection' # >& + '23 23 redirection' # - +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection.zsh new file mode 100644 index 00000000..6a25971a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Redirection before and after the command word are implemented differently; test both. +BUFFER='<<>&!bar' + +expected_region_highlight=( + "1 3 redirection" # <<< + "4 6 default" # foo + "8 11 builtin" # echo + "13 16 redirection" # >>&! + "17 19 default" # bar +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection2.zsh new file mode 100644 index 00000000..d44c8e7a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection2.zsh @@ -0,0 +1,41 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='ls >(wc) | nl' + +expected_region_highlight=( + "1 2 command" # ls + "4 8 default" # >(wc) + "4 8 process-substitution" # >(wc) + "4 5 process-substitution-delimiter" # >( + "6 7 command" # wc + "8 8 process-substitution-delimiter" # ) + "10 10 commandseparator" # | + "12 13 command" # nl +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection3.zsh new file mode 100644 index 00000000..bf062cfb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/redirection3.zsh @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=': >>>; : <>\<<<> + "5 5 unknown-token" # > + "6 6 commandseparator" # ; + "8 8 builtin" # : + "10 11 redirection" # <> + "12 13 default" # \< + "14 16 redirection" # <<< + "17 19 default" # EOF +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/reserved-word.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/reserved-word.zsh new file mode 100644 index 00000000..aca3796d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/reserved-word.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='repeat "1" do done' + +expected_region_highlight=( + "1 6 reserved-word" # repeat + "8 10 default" # "1" + "8 10 double-quoted-argument" # "1" + "12 13 reserved-word" # do + "15 18 reserved-word" # done +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/simple-command.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/simple-command.zsh new file mode 100644 index 00000000..8bb41fd0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/simple-command.zsh @@ -0,0 +1,34 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2011 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='ls' + +expected_region_highlight=( + "1 2 command" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/simple-redirection.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/simple-redirection.zsh new file mode 100644 index 00000000..e8c25e55 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/simple-redirection.zsh @@ -0,0 +1,38 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='ps aux | grep java' + +expected_region_highlight=( + "1 2 command" # ps + "4 6 default" # aux + "8 8 commandseparator" # | + "10 13 command" # grep + "15 18 default" # java +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/subshell.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/subshell.zsh new file mode 100644 index 00000000..c068013e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/subshell.zsh @@ -0,0 +1,51 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='tar cf - * | (cd /target; tar xfp -) | { cat }' + +expected_region_highlight=( + "1 3 command" # tar + "5 6 default" # cf + "8 8 single-hyphen-option" # - + "10 10 default" # * + "10 10 globbing" # * + "12 12 commandseparator" # | + "14 14 reserved-word" # ( + "15 16 builtin" # cd + "18 24 default" # /target + "25 25 commandseparator" # ; + "27 29 command" # tar + "31 33 default" # xfp + "35 35 single-hyphen-option" # - + "36 36 reserved-word" # ) + "38 38 commandseparator" # | + "40 40 reserved-word" # { + "42 44 command" # cat + "46 46 reserved-word" # } +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-command.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-command.zsh new file mode 100644 index 00000000..941349a0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-command.zsh @@ -0,0 +1,54 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +sudo(){} + +# Tests three codepaths: +# * -i (no argument) +# * -C3 (pasted argument) +# * -u otheruser (non-pasted argument) +BUFFER='sudo -C3 -u otheruser -i ls /; sudo ; sudo -u ; sudo notacommand' + +expected_region_highlight=( + "1 4 precommand" # sudo + "6 8 single-hyphen-option" # -C3 + "10 11 single-hyphen-option" # -u + "13 21 default" # otheruser + "23 24 single-hyphen-option" # -i + "26 27 command" # ls + "29 29 path" # / + "30 30 commandseparator" # ; + "32 35 precommand" # sudo + "37 37 unknown-token" # ;, error because empty command + "39 42 precommand" # sudo + "44 45 single-hyphen-option" # -u + "47 47 unknown-token" # ;, error because incomplete command + "49 52 precommand" # sudo + "54 64 unknown-token" # notacommand - doesn't falls back to "not a command word" codepath +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-comment.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-comment.zsh new file mode 100644 index 00000000..74cd905a --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-comment.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +sudo(){} + +setopt interactive_comments +BUFFER='sudo -u # comment' + +expected_region_highlight=( + "1 4 precommand" # sudo + "6 7 single-hyphen-option" # -u + "9 17 unknown-token" # "# comment" - error because argument missed +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-longopt.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-longopt.zsh new file mode 100644 index 00000000..ef768bfb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-longopt.zsh @@ -0,0 +1,38 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +hash sudo='false' +BUFFER='sudo --askpass ls' + +expected_region_highlight=( + '1 4 precommand' # sudo + '6 14 double-hyphen-option' # --askpass + '16 17 command' # ls (we don't know whether --askpass takes an argument) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-redirection.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-redirection.zsh new file mode 100644 index 00000000..c675d7d2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-redirection.zsh @@ -0,0 +1,48 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +sudo(){} + +BUFFER='sudo -u >/tmp otheruser ls; sudo ls; sudo -i ls' + +expected_region_highlight=( + "1 4 precommand" # sudo + "6 7 single-hyphen-option" # -u + "9 9 redirection" # > + "10 13 path" # /tmp + "15 23 default" # otheruser + "25 26 command" # ls + "27 27 commandseparator" # ; + "29 32 precommand" # sudo + "34 35 command" # ls + "36 36 commandseparator" # ; + "38 41 precommand" # sudo + "43 44 single-hyphen-option" # -i + "46 47 command" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-redirection2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-redirection2.zsh new file mode 100644 index 00000000..23ada53c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-redirection2.zsh @@ -0,0 +1,41 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +sudo(){} + +BUFFER='sudo >/tmp -u otheruser ls' + +expected_region_highlight=( + "1 4 precommand" # sudo + "6 6 redirection" # > + "7 10 path" # /tmp + "12 13 single-hyphen-option" # -u + "15 23 default" # otheruser + "25 26 command" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-redirection3.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-redirection3.zsh new file mode 100644 index 00000000..80e55b55 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/sudo-redirection3.zsh @@ -0,0 +1,41 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +sudo(){} + +BUFFER='sudo 2>./. -u otheruser ls' + +expected_region_highlight=( + "1 4 precommand" # sudo + "6 7 redirection" # 2> + "8 10 path" # ./. # a 3-character path, for alignment with sudo-redirection2.zsh + "12 13 single-hyphen-option" # -u + "15 23 default" # otheruser + "25 26 command" # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/tilde-command-word.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/tilde-command-word.zsh new file mode 100644 index 00000000..67c996c9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/tilde-command-word.zsh @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +hash -d D=/usr/bin + +BUFFER='~D/env foo' + +expected_region_highlight=( + "1 6 command" # ~D/env [= /usr/bin/env + "8 10 default" # foo +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/time-and-nocorrect1.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/time-and-nocorrect1.zsh new file mode 100644 index 00000000..fb398edf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/time-and-nocorrect1.zsh @@ -0,0 +1,39 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'time ls; nocorrect ls' + +expected_region_highlight=( + '1 4 reserved-word' # time + '6 7 command' # ls + '8 8 commandseparator' # ; + '10 18 reserved-word' # nocorrect + '20 21 command' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/time-and-nocorrect2.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/time-and-nocorrect2.zsh new file mode 100644 index 00000000..5549ee92 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/time-and-nocorrect2.zsh @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2019 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER=$'time ls; nocorrect ls' +alias time=':' nocorrect=':' + +expected_region_highlight=( + '1 4 alias' # time + '6 7 default' # ls + '8 8 commandseparator' # ; + '10 18 alias' # nocorrect + '20 21 default' # ls +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/unbackslash.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/unbackslash.zsh new file mode 100644 index 00000000..c8dfbd4c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/unbackslash.zsh @@ -0,0 +1,34 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='\sh' + +expected_region_highlight=( + "1 3 command" # \sh (runs 'sh', bypassing aliases) +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/unknown-command.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/unknown-command.zsh new file mode 100644 index 00000000..e71faec5 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/unknown-command.zsh @@ -0,0 +1,34 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2011 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='azertyuiop' + +expected_region_highlight=( + "1 10 unknown-token" # azertyuiop +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/vanilla-newline.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/vanilla-newline.zsh new file mode 100644 index 00000000..bd60ad4c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/vanilla-newline.zsh @@ -0,0 +1,39 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +PREBUFFER=$'echo foo; echo bar\n\n\n' +BUFFER=' echo baz; echo qux' + +expected_region_highlight=( + "2 5 builtin" # echo + "7 9 default" # baz + "10 10 commandseparator" # semicolon + "12 15 builtin" # echo + "17 19 default" # qux +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/vi-linewise-mode.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/vi-linewise-mode.zsh new file mode 100644 index 00000000..7003c49c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/main/test-data/vi-linewise-mode.zsh @@ -0,0 +1,43 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# See issue #267 for the magic numbers +BUFFER=$'foo foo\nbar bar' +REGION_ACTIVE=2 +CURSOR=4 +MARK=12 + +expected_region_highlight=( + "1 3 unknown-token" # foo + "5 7 default" # foo + "8 8 commandseparator" # \n + "9 11 unknown-token" # bar + "13 15 default" # bar + "1 15 standout" # foo foo\nbar bar +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/pattern/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/pattern/README.md new file mode 100644 index 00000000..ecaa6a7f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/pattern/README.md @@ -0,0 +1,24 @@ +zsh-syntax-highlighting / highlighters / pattern +------------------------------------------------ + +This is the `pattern` highlighter, that highlights user-defined patterns. + + +### How to tweak it + +To use this highlighter, associate patterns with styles in the +`ZSH_HIGHLIGHT_PATTERNS` associative array, for example in `~/.zshrc`: + +```zsh +# Declare the variable +typeset -A ZSH_HIGHLIGHT_PATTERNS + +# To have commands starting with `rm -rf` in red: +ZSH_HIGHLIGHT_PATTERNS+=('rm -rf *' 'fg=white,bold,bg=red') +``` + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/pattern/pattern-highlighter.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/pattern/pattern-highlighter.zsh new file mode 100644 index 00000000..e0422d08 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/pattern/pattern-highlighter.zsh @@ -0,0 +1,60 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2011 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + + +# List of keyword and color pairs. +typeset -gA ZSH_HIGHLIGHT_PATTERNS + +# Whether the pattern highlighter should be called or not. +_zsh_highlight_highlighter_pattern_predicate() +{ + _zsh_highlight_buffer_modified +} + +# Pattern syntax highlighting function. +_zsh_highlight_highlighter_pattern_paint() +{ + setopt localoptions extendedglob + local pattern + for pattern in ${(k)ZSH_HIGHLIGHT_PATTERNS}; do + _zsh_highlight_pattern_highlighter_loop "$BUFFER" "$pattern" + done +} + +_zsh_highlight_pattern_highlighter_loop() +{ + # This does *not* do its job syntactically, sorry. + local buf="$1" pat="$2" + local -a match mbegin mend + local MATCH; integer MBEGIN MEND + if [[ "$buf" == (#b)(*)(${~pat})* ]]; then + region_highlight+=("$((mbegin[2] - 1)) $mend[2] $ZSH_HIGHLIGHT_PATTERNS[$pat], memo=zsh-syntax-highlighting") + "$0" "$match[1]" "$pat"; return $? + fi +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/pattern/test-data/rm-rf.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/pattern/test-data/rm-rf.zsh new file mode 100644 index 00000000..2f769294 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/pattern/test-data/rm-rf.zsh @@ -0,0 +1,36 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +ZSH_HIGHLIGHT_PATTERNS+=('rm -rf *' 'fg=white,bold,bg=red') + +BUFFER='rm -rf /' + +expected_region_highlight=( + "1 8 fg=white,bold,bg=red" # rm -rf / +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/README.md new file mode 100644 index 00000000..b1bed914 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/README.md @@ -0,0 +1,65 @@ +zsh-syntax-highlighting / highlighters / regexp +------------------------------------------------ + +This is the `regexp` highlighter, that highlights user-defined regular +expressions. It's similar to the `pattern` highlighter, but allows more complex +patterns. + +### How to tweak it + +To use this highlighter, associate regular expressions with styles in the +`ZSH_HIGHLIGHT_REGEXP` associative array, for example in `~/.zshrc`: + +```zsh +typeset -A ZSH_HIGHLIGHT_REGEXP +ZSH_HIGHLIGHT_REGEXP+=('^rm .*' fg=red,bold) +``` + +This will highlight lines that start with a call to the `rm` command. + +The regular expressions flavour used is [PCRE][pcresyntax] when the +`RE_MATCH_PCRE` option is set and POSIX Extended Regular Expressions (ERE), +as implemented by the platform's C library, otherwise. For details on the +latter, see [the `zsh/regex` module's documentation][MAN_ZSH_REGEX] and the +`regcomp(3)` and `re_format(7)` manual pages on your system. + +For instance, to highlight `sudo` only as a complete word, i.e., `sudo cmd`, +but not `sudoedit`, one might use: + +* When the `RE_MATCH_PCRE` is set: + + ```zsh + typeset -A ZSH_HIGHLIGHT_REGEXP + ZSH_HIGHLIGHT_REGEXP+=('\bsudo\b' fg=123,bold) + ``` + +* When the `RE_MATCH_PCRE` is unset, on platforms with GNU `libc` (e.g., many GNU/Linux distributions): + + ```zsh + typeset -A ZSH_HIGHLIGHT_REGEXP + ZSH_HIGHLIGHT_REGEXP+=('\' fg=123,bold) + ``` + +* When the `RE_MATCH_PCRE` is unset, on BSD-based platforms (e.g., macOS): + + ```zsh + typeset -A ZSH_HIGHLIGHT_REGEXP + ZSH_HIGHLIGHT_REGEXP+=('[[:<:]]sudo[[:>:]]' fg=123,bold) + ``` + +Note, however, that PCRE and POSIX ERE have a large common subset: +for instance, the regular expressions `[abc]`, `a*`, and `(a|b)` have the same +meaning in both flavours. + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +See also: [regular expressions tutorial][perlretut], zsh regexp operator `=~` +in [the `zshmisc(1)` manual page][zshmisc-Conditional-Expressions] + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting +[perlretut]: http://perldoc.perl.org/perlretut.html +[zshmisc-Conditional-Expressions]: https://zsh.sourceforge.io/Doc/Release/Conditional-Expressions.html#Conditional-Expressions +[MAN_ZSH_REGEX]: https://zsh.sourceforge.io/Doc/Release/Zsh-Modules.html#The-zsh_002fregex-Module +[pcresyntax]: https://www.pcre.org/original/doc/html/pcresyntax.html diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/regexp-highlighter.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/regexp-highlighter.zsh new file mode 100644 index 00000000..0d43aacd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/regexp-highlighter.zsh @@ -0,0 +1,62 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + + +# List of keyword and color pairs. +typeset -gA ZSH_HIGHLIGHT_REGEXP + +# Whether the pattern highlighter should be called or not. +_zsh_highlight_highlighter_regexp_predicate() +{ + _zsh_highlight_buffer_modified +} + +# Pattern syntax highlighting function. +_zsh_highlight_highlighter_regexp_paint() +{ + setopt localoptions extendedglob + local pattern + for pattern in ${(k)ZSH_HIGHLIGHT_REGEXP}; do + _zsh_highlight_regexp_highlighter_loop "$BUFFER" "$pattern" + done +} + +_zsh_highlight_regexp_highlighter_loop() +{ + local buf="$1" pat="$2" + integer OFFSET=0 + local MATCH; integer MBEGIN MEND + local -a match mbegin mend + while true; do + [[ "$buf" =~ "$pat" ]] || return; + region_highlight+=("$((MBEGIN - 1 + OFFSET)) $((MEND + OFFSET)) $ZSH_HIGHLIGHT_REGEXP[$pat], memo=zsh-syntax-highlighting") + buf="$buf[$(($MEND+1)),-1]" + OFFSET=$((MEND+OFFSET)); + done +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/test-data/complex.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/test-data/complex.zsh new file mode 100644 index 00000000..4e0089b9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/test-data/complex.zsh @@ -0,0 +1,37 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +ZSH_HIGHLIGHT_REGEXP+=('[0-9\+\-]+' 'fg=white,bold,bg=red') + +BUFFER='echo 1+9-3 7+2' + +expected_region_highlight=( + "6 10 fg=white,bold,bg=red" + "12 14 fg=white,bold,bg=red" +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/test-data/subexpression.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/test-data/subexpression.zsh new file mode 100644 index 00000000..308cb413 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/test-data/subexpression.zsh @@ -0,0 +1,36 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2018 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +BUFFER='ls foo' +ZSH_HIGHLIGHT_REGEXP=('(^| )(ls|cd)($| )' 'fg=green') + +expected_region_highlight=( + '1 3 fg=green' # "ls " +) diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/test-data/word-boundary.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/test-data/word-boundary.zsh new file mode 100644 index 00000000..1f4f6665 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/regexp/test-data/word-boundary.zsh @@ -0,0 +1,42 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +if zmodload zsh/pcre 2>/dev/null; then + setopt RE_MATCH_PCRE + + ZSH_HIGHLIGHT_REGEXP+=('\bsudo\b' 'fg=white,bold,bg=red') + + BUFFER='sudo ls' + + expected_region_highlight=( + "1 4 fg=white,bold,bg=red" + ) +else + skip_test='Test requires zsh/pcre' +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/root/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/root/README.md new file mode 100644 index 00000000..8197e4bd --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/root/README.md @@ -0,0 +1,25 @@ +zsh-syntax-highlighting / highlighters / root +--------------------------------------------- + +This is the `root` highlighter, that highlights the whole line if the current +user is root. + + +### How to tweak it + +This highlighter defines the following styles: + +* `root` - the style for the whole line if the current user is root. + +To override one of those styles, change its entry in `ZSH_HIGHLIGHT_STYLES`, +for example in `~/.zshrc`: + +```zsh +ZSH_HIGHLIGHT_STYLES[root]='bg=red' +``` + +The syntax for values is the same as the syntax of "types of highlighting" of +the zsh builtin `$zle_highlight` array, which is documented in [the `zshzle(1)` +manual page][zshzle-Character-Highlighting]. + +[zshzle-Character-Highlighting]: https://zsh.sourceforge.io/Doc/Release/Zsh-Line-Editor.html#Character-Highlighting diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/root/root-highlighter.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/root/root-highlighter.zsh new file mode 100644 index 00000000..3718c449 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/highlighters/root/root-highlighter.zsh @@ -0,0 +1,44 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2011 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + + +# Define default styles. +: ${ZSH_HIGHLIGHT_STYLES[root]:=standout} + +# Whether the root highlighter should be called or not. +_zsh_highlight_highlighter_root_predicate() +{ + _zsh_highlight_buffer_modified +} + +# root highlighting function. +_zsh_highlight_highlighter_root_paint() +{ + if (( EUID == 0 )) { _zsh_highlight_add_highlight 0 $#BUFFER root } +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after1-smaller.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after1-smaller.png new file mode 100644 index 00000000..768294c3 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after1-smaller.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after1.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after1.png new file mode 100644 index 00000000..ea378d3e Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after1.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after2-smaller.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after2-smaller.png new file mode 100644 index 00000000..8b5b1f8f Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after2-smaller.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after2.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after2.png new file mode 100644 index 00000000..ddcbfad7 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after2.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after3-smaller.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after3-smaller.png new file mode 100644 index 00000000..d6aaa7bd Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after3-smaller.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after3.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after3.png new file mode 100644 index 00000000..7a0af887 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after3.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after4-smaller.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after4-smaller.png new file mode 100644 index 00000000..fc946cf0 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/after4-smaller.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before1-smaller.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before1-smaller.png new file mode 100644 index 00000000..b29551ea Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before1-smaller.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before1.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before1.png new file mode 100644 index 00000000..80c6f54f Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before1.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before2-smaller.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before2-smaller.png new file mode 100644 index 00000000..991a716d Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before2-smaller.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before2.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before2.png new file mode 100644 index 00000000..48cfc327 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before2.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before3-smaller.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before3-smaller.png new file mode 100644 index 00000000..e525c6d4 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before3-smaller.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before3.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before3.png new file mode 100644 index 00000000..40c36015 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before3.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before4-smaller.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before4-smaller.png new file mode 100644 index 00000000..2dbd0588 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/before4-smaller.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/preview-smaller.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/preview-smaller.png new file mode 100644 index 00000000..6fb84d18 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/preview-smaller.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/preview.png b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/preview.png new file mode 100644 index 00000000..545cc511 Binary files /dev/null and b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/images/preview.png differ diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/release.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/release.md new file mode 100644 index 00000000..f8565e81 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/release.md @@ -0,0 +1,21 @@ +# Release procedure (for developers): + +- Ensure every `is-at-least` invocation passes a stable zsh release's version number as the first argument +- For minor (A.B.0) releases: + - Check whether the release uses any not-yet-released zsh features +- Check open issues and outstanding pull requests +- Confirm `make test` passes + - check with multiple zsh versions + (easiest to check GitHub Actions: https://github.com/zsh-users/zsh-syntax-highlighting/actions) +- Update changelog.md + `tig --abbrev=12 --abbrev-commit 0.4.1..upstream/master` +- Make sure there are no local commits and that `git status` is clean; + Remove `-dev` suffix from `./.version`; + Commit that using `git commit -m "Tag version $(<.version)." .version`; + Tag it using `git tag -s -m "Tag version $(<.version)" $(<.version)`; + Increment `./.version` and restore the `-dev` suffix; + Commit that using `git commit -C b5c30ae52638e81a38fe5329081c5613d7bd6ca5 .version`. +- Push with `git push && git push --tags` +- Notify downstreams (OS packages) + - anitya should autodetect the tag +- Update /topic on IRC diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/README.md b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/README.md new file mode 100644 index 00000000..cb3d943c --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/README.md @@ -0,0 +1,124 @@ +zsh-syntax-highlighting / tests +=============================== + +Utility scripts for testing zsh-syntax-highlighting highlighters. + +The tests harness expects the highlighter directory to contain a `test-data` +directory with test data files. +See the [main highlighter](../highlighters/main/test-data) for examples. + +Tests should set the following variables: + +1. +Each test should define the string `$BUFFER` that is to be highlighted and the +array parameter `$expected_region_highlight`. +The value of that parameter is a list of strings of the form `"$i $j $style"`. +or `"$i $j $style $todo"`. +Each string specifies the highlighting that `$BUFFER[$i,$j]` should have; +that is, `$i` and `$j` specify a range, 1-indexed, inclusive of both endpoints. +`$style` is a key of `$ZSH_HIGHLIGHT_STYLES`. +If `$todo` exists, the test point is marked as TODO (the failure of that test +point will not fail the test), and `$todo` is used as the explanation. + +2. +If a test sets `$skip_test` to a non-empty string, the test will be skipped +with the provided string as the reason. + +3. +If a test sets `$fail_test` to a non-empty string, the test will be skipped +with the provided string as the reason. + +4. +If a test sets `unsorted=1` the order of highlights in `$expected_region_highlight` +need not match the order in `$region_highlight`. + +5. +Normally, tests fail if `$expected_region_highlight` and `$region_highlight` +have different numbers of elements. To mark this check as expected to fail, +tests may set `$expected_mismatch` to an explanation string (like `$todo`); +this is useful when the only difference between actual and expected is that actual +has some additional, superfluous elements. This check is skipped if the +`$todo` component is present in any regular test point. + +**Note**: `$region_highlight` uses the same `"$i $j $style"` syntax but +interprets the indexes differently. + +**Note**: Tests are run with `setopt NOUNSET WARN_CREATE_GLOBAL`, so any +variables the test creates must be declared local. + +**Isolation**: Each test is run in a separate subshell, so any variables, +aliases, functions, etc., it defines will be visible to the tested code (that +computes `$region_highlight`), but will not affect subsequent tests. The +current working directory of tests is set to a newly-created empty directory, +which is automatically cleaned up after the test exits. For example: + +```zsh +setopt PATH_DIRS +mkdir -p foo/bar +touch foo/bar/testing-issue-228 +chmod +x foo/bar/testing-issue-228 +path+=( "$PWD"/foo ) + +BUFFER='bar/testing-issue-228' + +expected_region_highlight=( + "1 21 command" # bar/testing-issue-228 +) +``` + + +Writing new tests +----------------- + +An experimental tool is available to generate test files: + +```zsh +zsh -f tests/generate.zsh 'ls -x' acme newfile +``` + +This generates a `highlighters/acme/test-data/newfile.zsh` test file based on +the current highlighting of the given `$BUFFER` (in this case, `ls -x`). + +_This tool is experimental._ Its interface may change. In particular it may +grow ways to set `$PREBUFFER` to inject free-form code into the generated file. + + +Highlighting test +----------------- + +[`test-highlighting.zsh`](tests/test-highlighting.zsh) tests the correctness of +the highlighting. Usage: + +```zsh +zsh test-highlighting.zsh +``` + +All tests may be run with + +```zsh +make test +``` + +which will run all highlighting tests and report results in [TAP format][TAP]. +By default, the results of all tests will be printed; to show only "interesting" +results (tests that failed but were expected to succeed, or vice-versa), run +`make quiet-test` (or `make test QUIET=y`). + +[TAP]: http://testanything.org/ + + +Performance test +---------------- + +[`test-perfs.zsh`](tests/test-perfs.zsh) measures the time spent doing the +highlighting. Usage: + +```zsh +zsh test-perfs.zsh +``` + +All tests may be run with + +```zsh +make perf +``` diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/edit-failed-tests b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/edit-failed-tests new file mode 100755 index 00000000..e3a76685 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/edit-failed-tests @@ -0,0 +1,40 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +type perl sponge >/dev/null || { print -ru2 -- "$0: This script requires perl(1) and sponge(1) [from moreutils]"; exit 1; } + +local editor=( "${(@Q)${(z)${VISUAL:-${EDITOR:-vi}}}}" ) +() { + > "$2" perl -nE '$highlighter = $1 if /^Running test (\S*)/; say "highlighters/${highlighter}/test-data/$1.zsh" if /^## (\S*)/' "$1" + >>"$2" echo "" + >>"$2" cat <"$1" + "${editor[@]}" -- "$2" +} =(${MAKE:-make} quiet-test) =(:) +# TODO: tee(1) the quiet-test output to /dev/tty as it's happening, with colors. diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/generate.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/generate.zsh new file mode 100755 index 00000000..56960202 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/generate.zsh @@ -0,0 +1,117 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2016 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +emulate -LR zsh +setopt localoptions extendedglob + +# Required for add-zle-hook-widget. +zmodload zsh/zle + +# Argument parsing. +if (( $# * $# - 7 * $# + 12 )) || [[ $1 == -* ]]; then + print -r -- >&2 "$0: usage: $0 BUFFER HIGHLIGHTER BASENAME [PREAMBLE]" + print -r -- >&2 "" + print -r -- >&2 "Generate highlighters/HIGHLIGHTER/test-data/BASENAME.zsh based on the" + print -r -- >&2 "current highlighting of BUFFER, using the setup code PREAMBLE." + exit 1 +fi +buffer=$1 +ZSH_HIGHLIGHT_HIGHLIGHTERS=( $2 ) +fname=${0:A:h:h}/highlighters/$2/test-data/${3%.zsh}.zsh +preamble=${4:-""} + +# Load the main script. +. ${0:A:h:h}/zsh-syntax-highlighting.zsh + +# Overwrite _zsh_highlight_add_highlight so we get the key itself instead of the style +_zsh_highlight_add_highlight() +{ + region_highlight+=("$1 $2 $3") +} + + +# Copyright block +year="`LC_ALL=C date +%Y`" +if ! { read -q "?Set copyright year to $year? " } always { echo "" }; then + year="YYYY" +fi +<$0 sed -n -e '1,/^$/p' | sed -e "s/2[0-9][0-9][0-9]/${year}/" > $fname +# Assumes stdout is line-buffered +git add -- $fname +exec > >(tee -a $fname) + +# Preamble +if [[ -n $preamble ]]; then + print -rl -- "$preamble" "" +fi + +# Buffer +print -n 'BUFFER=' +if [[ $buffer != (#s)[$'\t -~']#(#e) ]]; then + print -r -- ${(qqqq)buffer} +else + print -r -- ${(qq)buffer} +fi +echo "" + +# Expectations +print 'expected_region_highlight=(' +() { + local i + local PREBUFFER + local BUFFER + + PREBUFFER="" + BUFFER="$buffer" + region_highlight=() + eval $( + exec 3>&1 >/dev/null + typeset -r __tests_tmpdir="$(mktemp -d)" + { + # Use a subshell to ensure $__tests_tmpdir, which is to be rm -rf'd, won't be modified. + (cd -- "$__tests_tmpdir" && eval $preamble && _zsh_highlight && typeset -p region_highlight >&3) + : # workaround zsh bug workers/45305 with respect to the $(…) subshell we're in + } always { + rm -rf -- ${__tests_tmpdir} + } + ) + + for ((i=1; i<=${#region_highlight}; i++)); do + local -a highlight_zone; highlight_zone=( ${(z)region_highlight[$i]} ) + integer start=$highlight_zone[1] end=$highlight_zone[2] + if (( start < end )) # region_highlight ranges are half-open + then + (( --end )) # convert to closed range, like expected_region_highlight + (( ++start, ++end )) # region_highlight is 0-indexed; expected_region_highlight is 1-indexed + fi + printf " %s # %s\n" ${(qq):-"$start $end $highlight_zone[3]"} ${${(qqqq)BUFFER[start,end]}[3,-2]} + done +} +print ')' diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/tap-colorizer.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/tap-colorizer.zsh new file mode 100755 index 00000000..f3dc84e7 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/tap-colorizer.zsh @@ -0,0 +1,71 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015, 2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# This is a stdin-to-stdout filter that takes TAP output (such as 'make test') +# on stdin and passes it, colorized, to stdout. + +emulate -LR zsh + +if [[ ! -t 1 ]] ; then + exec cat +fi + +while read -r line; +do + case $line in + # comment (filename header) or plan + (#* | <->..<->) + print -nP %F{blue} + ;; + # SKIP + (*# SKIP*) + print -nP %F{yellow} + ;; + # XPASS + (ok*# TODO*) + print -nP %F{red} + ;; + # XFAIL + (not ok*# TODO*) + print -nP %F{yellow} + ;; + # FAIL + (not ok*) + print -nP %F{red} + ;; + # PASS + (ok*) + print -nP %F{green} + ;; + esac + print -nr - "$line" + print -nP %f + echo "" # newline +done diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/tap-filter b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/tap-filter new file mode 100755 index 00000000..f9aa6041 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/tap-filter @@ -0,0 +1,47 @@ +#!/usr/bin/env perl +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# vim: ft=perl sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# This is a stdin-to-stdout filter that takes TAP output (such as 'make test') +# on stdin and deletes lines pertaining to expected results. +# +# More specifically, if any of the test points in a test file either failed but +# was expected to pass, or passed but was expected to fail, then emit that test +# file's output; else, elide that test file's output. + +use v5.10.0; +use warnings; +use strict; + +undef $/; # slurp mode +print for + grep { /^ok.*# TODO/m or /^not ok(?!.*# TODO)/m or /^Bail out!/m } + # Split on plan lines and remove them from the output. (To keep them, + # use the lookahead syntax, «(?=…)», to make the match zero-length.) + split /^\d+\.\.\d+$/m, + ; diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/test-highlighting.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/test-highlighting.zsh new file mode 100755 index 00000000..8b564a8b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/test-highlighting.zsh @@ -0,0 +1,291 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2017 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + + +setopt NO_UNSET WARN_CREATE_GLOBAL + +# Required for add-zle-hook-widget. +zmodload zsh/zle + +local -r root=${0:h:h} +local -a anon_argv; anon_argv=("$@") + +(){ +set -- "${(@)anon_argv}" +# Check an highlighter was given as argument. +[[ -n "$1" ]] || { + echo >&2 "Bail out! You must provide the name of a valid highlighter as argument." + exit 2 +} + +# Check the highlighter is valid. +[[ -f $root/highlighters/$1/$1-highlighter.zsh ]] || { + echo >&2 "Bail out! Could not find highlighter ${(qq)1}." + exit 2 +} + +# Check the highlighter has test data. +[[ -d $root/highlighters/$1/test-data ]] || { + echo >&2 "Bail out! Highlighter ${(qq)1} has no test data." + exit 2 +} + +# Set up results_filter +local results_filter +if [[ ${QUIET-} == y ]]; then + if type -w perl >/dev/null; then + results_filter=$root/tests/tap-filter + else + echo >&2 "Bail out! quiet mode not supported: perl not found"; exit 2 + fi +else + results_filter=cat +fi +[[ -n $results_filter ]] || { echo >&2 "Bail out! BUG setting \$results_filter"; exit 2 } + +# Load the main script. +# While here, test that it doesn't eat aliases. +print > >($results_filter | $root/tests/tap-colorizer.zsh) -r -- "# global (driver) tests" +print > >($results_filter | $root/tests/tap-colorizer.zsh) -r -- "1..1" +alias -- +plus=plus +alias -- _other=other +local original_alias_dash_L_output="$(alias -L)" +. $root/zsh-syntax-highlighting.zsh +if [[ $original_alias_dash_L_output == $(alias -L) ]]; then + print -r -- "ok 1 # 'alias -- +foo=bar' is preserved" +else + print -r -- "not ok 1 # 'alias -- +foo=bar' is preserved" + exit 1 +fi > >($results_filter | $root/tests/tap-colorizer.zsh) + +# Overwrite _zsh_highlight_add_highlight so we get the key itself instead of the style +_zsh_highlight_add_highlight() +{ + region_highlight+=("$1 $2 $3") +} + +# Activate the highlighter. +ZSH_HIGHLIGHT_HIGHLIGHTERS=($1) + +# In zsh<5.3, 'typeset -p arrayvar' emits two lines, so we use this wrapper instead. +typeset_p() { + for 1 ; do + if [[ ${(tP)1} == *array* ]]; then + print -r -- "$1=( ${(@qqqqP)1} )" + else + print -r -- "$1=${(qqqqP)1}" + fi + done +} + +# Escape # as ♯ and newline as ↵ they are illegal in the 'description' part of TAP output +# The string to escape is «"$@"»; the result is returned in $REPLY. +tap_escape() { + local s="${(j. .)@}" + REPLY="${${s//'#'/♯}//$'\n'/↵}" +} + +# Runs a highlighting test +# $1: data file +run_test_internal() { + + local tests_tempdir="$1"; shift + local srcdir="$PWD" + builtin cd -q -- "$tests_tempdir" || { echo >&2 "Bail out! On ${(qq)1}: cd failed: $?"; return 1 } + + # Load the data and prepare checking it. + local BUFFER CURSOR MARK PENDING PREBUFFER REGION_ACTIVE WIDGET REPLY skip_test fail_test unsorted=0 + local expected_mismatch + local skip_mismatch + local -a expected_region_highlight region_highlight + + local ARG="$1" + local RETURN="" + () { + setopt localoptions + + # WARNING: The remainder of this anonymous function will run with the test's options in effect + if { ! . "$srcdir"/"$ARG" } || (( $#fail_test )); then + print -r -- "1..1" + print -r -- "## ${ARG:t:r}" + tap_escape $fail_test; fail_test=$REPLY + print -r -- "not ok 1 - failed setup: $fail_test" + return ${RETURN:=0} + fi + + (( $#skip_test )) && { + print -r -- "1..0 # SKIP $skip_test" + print -r -- "## ${ARG:t:r}" + return ${RETURN:=0} + } + + # Check the data declares $PREBUFFER or $BUFFER. + [[ -z $PREBUFFER && -z $BUFFER ]] && { echo >&2 "Bail out! On ${(qq)ARG}: Either 'PREBUFFER' or 'BUFFER' must be declared and non-blank"; return ${RETURN:=1}; } + [[ $PREBUFFER == (''|*$'\n') ]] || { echo >&2 "Bail out! On ${(qq)ARG}: PREBUFFER=${(qqqq)PREBUFFER} doesn't end with a newline"; return ${RETURN:=1}; } + + # Set sane defaults for ZLE variables + : ${CURSOR=$#BUFFER} ${PENDING=0} ${WIDGET=z-sy-h-test-harness-test-widget} + + # Process the data. + _zsh_highlight + }; [[ -z $RETURN ]] || return $RETURN + unset ARG + + integer print_expected_and_actual=0 + + if (( unsorted )); then + region_highlight=("${(@n)region_highlight}") + expected_region_highlight=("${(@n)expected_region_highlight}") + fi + + # Print the plan line, and some comments for human readers + echo "1..$(( $#expected_region_highlight + 1))" + echo "## ${1:t:r}" # note: tests/edit-failed-tests looks for the "##" emitted by this line + [[ -n $PREBUFFER ]] && printf '# %s\n' "$(typeset_p PREBUFFER)" + [[ -n $BUFFER ]] && printf '# %s\n' "$(typeset_p BUFFER)" + + local i + for ((i=1; i<=$#expected_region_highlight; i++)); do + local -a expected_highlight_zone; expected_highlight_zone=( ${(z)expected_region_highlight[i]} ) + integer exp_start=$expected_highlight_zone[1] exp_end=$expected_highlight_zone[2] + local todo= + if (( $+expected_highlight_zone[4] )); then + todo="# TODO $expected_highlight_zone[4]" + skip_mismatch="cardinality check disabled whilst regular test points are expected to fail" + fi + if ! (( $+region_highlight[i] )); then + print -r -- "not ok $i - unmatched expectation ($exp_start $exp_end $expected_highlight_zone[3])" \ + "${skip_mismatch:+"# TODO ${(qqq)skip_mismatch}"}" + if [[ -z $skip_mismatch ]]; then (( ++print_expected_and_actual )); fi + continue + fi + local -a highlight_zone; highlight_zone=( ${(z)region_highlight[i]} ) + integer start=$(( highlight_zone[1] + 1 )) end=$highlight_zone[2] + local desc="[$start,$end] «${BUFFER[$start,$end]}»" + tap_escape $desc; desc=$REPLY + if + [[ $start != $exp_start ]] || + [[ $end != $exp_end ]] || + [[ ${highlight_zone[3]%,} != ${expected_highlight_zone[3]} ]] # remove the comma that's before the memo field + then + print -r -- "not ok $i - $desc - expected ($exp_start $exp_end ${(qqq)expected_highlight_zone[3]}), observed ($start $end ${(qqq)highlight_zone[3]}). $todo" + if [[ -z $todo ]]; then (( ++print_expected_and_actual )); fi + else + print -r -- "ok $i - $desc${todo:+ - }$todo" + fi + unset expected_highlight_zone + unset exp_start exp_end + unset todo + unset highlight_zone + unset start end + unset desc + done + + # If both $skip_mismatch and $expected_mismatch are set, that means the test + # has some XFail test points, _and_ explicitly sets $expected_mismatch as + # well. Explicit settings should have priority, so we ignore $skip_mismatch + # if $expected_mismatch is set. + if [[ -n $skip_mismatch && -z $expected_mismatch ]]; then + tap_escape $skip_mismatch; skip_mismatch=$REPLY + print "ok $i - cardinality check" "# SKIP $skip_mismatch" + else + local todo + if [[ -n $expected_mismatch ]]; then + tap_escape $expected_mismatch; expected_mismatch=$REPLY + todo="# TODO $expected_mismatch" + fi + if (( $#expected_region_highlight == $#region_highlight )); then + print -r -- "ok $i - cardinality check${todo:+ - }$todo" + else + local details + details+="have $#expected_region_highlight expectations and $#region_highlight region_highlight entries: " + details+="«$(typeset_p expected_region_highlight)» «$(typeset_p region_highlight)»" + tap_escape $details; details=$REPLY + print -r -- "not ok $i - cardinality check - $details${todo:+ - }$todo" + if [[ -z $todo ]]; then (( ++print_expected_and_actual )); fi + fi + fi + if (( print_expected_and_actual )); then + () { + local -a left_column right_column + left_column=( "expected_region_highlight" "${(qq)expected_region_highlight[@]}" ) + right_column=( "region_highlight" "${(qq)region_highlight[@]}" ) + integer difference=$(( $#right_column - $#left_column )) + repeat $difference do left_column+=(.); done + paste \ + =(print -rC1 -- $left_column) \ + =(print -rC1 -- $right_column) \ + | if type column >/dev/null; then column -t -s $'\t'; else cat; fi \ + | sed 's/^/# /' + } + fi +} + +# Run a single test file. The exit status is 1 if the test harness had +# an error and 0 otherwise. The exit status does not depend on whether +# test points succeeded or failed. +run_test() { + # Do not combine the declaration and initialization: «local x="$(false)"» does not set $?. + local __tests_tempdir + __tests_tempdir="$(mktemp -d)" && [[ -d $__tests_tempdir ]] || { + echo >&2 "Bail out! mktemp failed"; return 1 + } + typeset -r __tests_tempdir # don't allow tests to override the variable that we will 'rm -rf' later on + + { + # Use a subshell to isolate tests from each other. + # (So tests can alter global shell state using 'cd', 'hash', etc) + { + # These braces are so multios don't come into play. + { (run_test_internal "$__tests_tempdir" "$@") 3>&1 >&2 2>&3 } | grep \^ + local ret=$pipestatus[1] stderr=$pipestatus[2] + if (( ! stderr )); then + # stdout will become stderr + echo "Bail out! On ${(qq)1}: output on stderr"; return 1 + else + return $ret + fi + } 3>&1 >&2 2>&3 + } always { + rm -rf -- "$__tests_tempdir" + } +} + +# Process each test data file in test data directory. +integer something_failed=0 +ZSH_HIGHLIGHT_STYLES=() +local data_file +for data_file in $root/highlighters/$1/test-data/*.zsh; do + run_test "$data_file" | tee >($results_filter | $root/tests/tap-colorizer.zsh) | grep -v '^not ok.*# TODO' | grep -Eq '^not ok|^ok.*# TODO' && (( something_failed=1 )) + (( $pipestatus[1] )) && exit 2 +done + +exit $something_failed +} diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/test-perfs.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/test-perfs.zsh new file mode 100755 index 00000000..aa139aad --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/test-perfs.zsh @@ -0,0 +1,103 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + + +# Required for add-zle-hook-widget. +zmodload zsh/zle + +# Check an highlighter was given as argument. +[[ -n "$1" ]] || { + echo >&2 "Bail out! You must provide the name of a valid highlighter as argument." + exit 2 +} + +# Check the highlighter is valid. +[[ -f ${0:h:h}/highlighters/$1/$1-highlighter.zsh ]] || { + echo >&2 "Bail out! Could not find highlighter ${(qq)1}." + exit 2 +} + +# Check the highlighter has test data. +[[ -d ${0:h:h}/highlighters/$1/test-data ]] || { + echo >&2 "Bail out! Highlighter ${(qq)1} has no test data." + exit 2 +} + +# Load the main script. +typeset -a region_highlight +. ${0:h:h}/zsh-syntax-highlighting.zsh + +# Activate the highlighter. +ZSH_HIGHLIGHT_HIGHLIGHTERS=($1) + +# Runs a highlighting test +# $1: data file +run_test_internal() { + local -a highlight_zone + + local tests_tempdir="$1"; shift + local srcdir="$PWD" + builtin cd -q -- "$tests_tempdir" || { echo >&2 "Bail out! cd failed: $?"; return 1 } + + # Load the data and prepare checking it. + PREBUFFER= BUFFER= ; + . "$srcdir"/"$1" + + # Check the data declares $PREBUFFER or $BUFFER. + [[ -z $PREBUFFER && -z $BUFFER ]] && { echo >&2 "Bail out! Either 'PREBUFFER' or 'BUFFER' must be declared and non-blank"; return 1; } + + # Set $? for _zsh_highlight + true && _zsh_highlight +} + +run_test() { + # Do not combine the declaration and initialization: «local x="$(false)"» does not set $?. + local __tests_tempdir + __tests_tempdir="$(mktemp -d)" && [[ -d $__tests_tempdir ]] || { + echo >&2 "Bail out! mktemp failed"; return 1 + } + typeset -r __tests_tempdir # don't allow tests to override the variable that we will 'rm -rf' later on + + { + (run_test_internal "$__tests_tempdir" "$@") + } always { + rm -rf -- "$__tests_tempdir" + } +} + +# Process each test data file in test data directory. +local data_file +TIMEFMT="%*Es" +{ time (for data_file in ${0:h:h}/highlighters/$1/test-data/*.zsh; do + run_test "$data_file" + (( $pipestatus[1] )) && exit 2 +done) } 2>&1 || exit $? + +exit 0 diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/test-zprof.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/test-zprof.zsh new file mode 100755 index 00000000..ada16187 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/tests/test-zprof.zsh @@ -0,0 +1,78 @@ +#!/usr/bin/env zsh +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2015 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# Load the main script. +typeset -a region_highlight +. ${0:h:h}/zsh-syntax-highlighting.zsh + +# Activate the highlighter. +ZSH_HIGHLIGHT_HIGHLIGHTERS=(main) + +source_file=0.7.1:highlighters/$1/$1-highlighter.zsh + +# Runs a highlighting test +# $1: data file +run_test_internal() { + setopt interactivecomments + + local -a highlight_zone + + local tests_tempdir="$1"; shift + local srcdir="$PWD" + builtin cd -q -- "$tests_tempdir" || { echo >&2 "Bail out! cd failed: $?"; return 1 } + + # Load the data and prepare checking it. + PREBUFFER= + BUFFER=$(cd -- "$srcdir" && git cat-file blob $source_file) + expected_region_highlight=() + + zmodload zsh/zprof + zprof -c + # Set $? for _zsh_highlight + true && _zsh_highlight + zprof +} + +run_test() { + # Do not combine the declaration and initialization: «local x="$(false)"» does not set $?. + local __tests_tempdir + __tests_tempdir="$(mktemp -d)" && [[ -d $__tests_tempdir ]] || { + echo >&2 "Bail out! mktemp failed"; return 1 + } + typeset -r __tests_tempdir # don't allow tests to override the variable that we will 'rm -rf' later on + + { + (run_test_internal "$__tests_tempdir" "$@") + } always { + rm -rf -- "$__tests_tempdir" + } +} + +run_test diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.plugin.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.plugin.zsh new file mode 100644 index 00000000..f2456aec --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.plugin.zsh @@ -0,0 +1,2 @@ +0=${(%):-%N} +source ${0:A:h}/zsh-syntax-highlighting.zsh diff --git a/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh new file mode 100644 index 00000000..bec01898 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/plugins/zsh-syntax-highlighting/zsh-syntax-highlighting.zsh @@ -0,0 +1,600 @@ +# ------------------------------------------------------------------------------------------------- +# Copyright (c) 2010-2020 zsh-syntax-highlighting contributors +# All rights reserved. +# +# Redistribution and use in source and binary forms, with or without modification, are permitted +# provided that the following conditions are met: +# +# * Redistributions of source code must retain the above copyright notice, this list of conditions +# and the following disclaimer. +# * Redistributions in binary form must reproduce the above copyright notice, this list of +# conditions and the following disclaimer in the documentation and/or other materials provided +# with the distribution. +# * Neither the name of the zsh-syntax-highlighting contributors nor the names of its contributors +# may be used to endorse or promote products derived from this software without specific prior +# written permission. +# +# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR +# IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND +# FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR +# CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +# DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, +# DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER +# IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT +# OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +# ------------------------------------------------------------------------------------------------- +# -*- mode: zsh; sh-indentation: 2; indent-tabs-mode: nil; sh-basic-offset: 2; -*- +# vim: ft=zsh sw=2 ts=2 et +# ------------------------------------------------------------------------------------------------- + +# First of all, ensure predictable parsing. +typeset zsh_highlight__aliases="$(builtin alias -Lm '[^+]*')" +# In zsh <= 5.2, aliases that begin with a plus sign ('alias -- +foo=42') +# are emitted by `alias -L` without a '--' guard, so they don't round trip. +# +# Hence, we exclude them from unaliasing: +builtin unalias -m '[^+]*' + +# Set $0 to the expected value, regardless of functionargzero. +0=${(%):-%N} +if true; then + # $0 is reliable + typeset -g ZSH_HIGHLIGHT_VERSION=$(<"${0:A:h}"/.version) + typeset -g ZSH_HIGHLIGHT_REVISION=$(<"${0:A:h}"/.revision-hash) + if [[ $ZSH_HIGHLIGHT_REVISION == \$Format:* ]]; then + # When running from a source tree without 'make install', $ZSH_HIGHLIGHT_REVISION + # would be set to '$Format:%H$' literally. That's an invalid value, and obtaining + # the valid value (via `git rev-parse HEAD`, as Makefile does) might be costly, so: + ZSH_HIGHLIGHT_REVISION=HEAD + fi +fi + +# This function takes a single argument F and returns True iff F is an autoload stub. +_zsh_highlight__function_is_autoload_stub_p() { + if zmodload -e zsh/parameter; then + #(( ${+functions[$1]} )) && + [[ "$functions[$1]" == *"builtin autoload -X"* ]] + else + #[[ $(type -wa -- "$1") == *'function'* ]] && + [[ "${${(@f)"$(which -- "$1")"}[2]}" == $'\t'$histchars[3]' undefined' ]] + fi + # Do nothing here: return the exit code of the if. +} + +# Return True iff the argument denotes a function name. +_zsh_highlight__is_function_p() { + if zmodload -e zsh/parameter; then + (( ${+functions[$1]} )) + else + [[ $(type -wa -- "$1") == *'function'* ]] + fi +} + +# This function takes a single argument F and returns True iff F denotes the +# name of a callable function. A function is callable if it is fully defined +# or if it is marked for autoloading and autoloading it at the first call to it +# will succeed. In particular, if F has been marked for autoloading +# but is not available in $fpath, then calling this function on F will return False. +# +# See users/21671 http://www.zsh.org/cgi-bin/mla/redirect?USERNUMBER=21671 +_zsh_highlight__function_callable_p() { + if _zsh_highlight__is_function_p "$1" && + ! _zsh_highlight__function_is_autoload_stub_p "$1" + then + # Already fully loaded. + return 0 # true + else + # "$1" is either an autoload stub, or not a function at all. + # + # Use a subshell to avoid affecting the calling shell. + # + # We expect 'autoload +X' to return non-zero if it fails to fully load + # the function. + ( autoload -U +X -- "$1" 2>/dev/null ) + return $? + fi +} + +# ------------------------------------------------------------------------------------------------- +# Core highlighting update system +# ------------------------------------------------------------------------------------------------- + +# Use workaround for bug in ZSH? +# zsh-users/zsh@48cadf4 http://www.zsh.org/mla/workers//2017/msg00034.html +autoload -Uz is-at-least +if is-at-least 5.4; then + typeset -g zsh_highlight__pat_static_bug=false +else + typeset -g zsh_highlight__pat_static_bug=true +fi + +# Array declaring active highlighters names. +typeset -ga ZSH_HIGHLIGHT_HIGHLIGHTERS + +# Update ZLE buffer syntax highlighting. +# +# Invokes each highlighter that needs updating. +# This function is supposed to be called whenever the ZLE state changes. +_zsh_highlight() +{ + # Store the previous command return code to restore it whatever happens. + local ret=$? + # Make it read-only. Can't combine this with the previous line when POSIX_BUILTINS may be set. + typeset -r ret + + # $region_highlight should be predefined, either by zle or by the test suite's mock (non-special) array. + (( ${+region_highlight} )) || { + echo >&2 'zsh-syntax-highlighting: error: $region_highlight is not defined' + echo >&2 'zsh-syntax-highlighting: (Check whether zsh-syntax-highlighting was installed according to the instructions.)' + return $ret + } + + # Probe the memo= feature, once. + (( ${+zsh_highlight__memo_feature} )) || { + region_highlight+=( " 0 0 fg=red, memo=zsh-syntax-highlighting" ) + case ${region_highlight[-1]} in + ("0 0 fg=red") + # zsh 5.8 or earlier + integer -gr zsh_highlight__memo_feature=0 + ;; + ("0 0 fg=red memo=zsh-syntax-highlighting") + # zsh 5.9 or later + integer -gr zsh_highlight__memo_feature=1 + ;; + (" 0 0 fg=red, memo=zsh-syntax-highlighting") ;& + (*) + # We can get here in two ways: + # + # 1. When not running as a widget. In that case, $region_highlight is + # not a special variable (= one with custom getter/setter functions + # written in C) but an ordinary one, so the third case pattern matches + # and we fall through to this block. (The test suite uses this codepath.) + # + # 2. When running under a future version of zsh that will have changed + # the serialization of $region_highlight elements from their underlying + # C structs, so that none of the previous case patterns will match. + # + # In either case, fall back to a version check. + # + # The memo= feature was added to zsh in commit zsh-5.8-172-gdd6e702ee. + # The version number at the time was 5.8.0.2-dev (see Config/version.mk). + # Therefore, on zsh master 5.8.0.3 and newer the memo= feature is available. + # However, there's also the zsh 5.8.1 release, which doesn't have the + # memo= feature. + # + # On zsh master 5.8.0.2 between the aforementioned commit and the + # first Config/version.mk bump after it (zsh-5.8-607-g75c1edde5, the + # bump to 5.8.1.1-dev following the backport to master of the bump + # to 5.8.1), this condition will false negative. + if is-at-least 5.8.1.1 $ZSH_VERSION.0.0; then + integer -gr zsh_highlight__memo_feature=1 + else + integer -gr zsh_highlight__memo_feature=0 + fi + ;; + esac + region_highlight[-1]=() + } + + # Reset region_highlight to build it from scratch + if (( zsh_highlight__memo_feature )); then + region_highlight=( "${(@)region_highlight:#*memo=zsh-syntax-highlighting*}" ) + else + # Legacy codepath. Not very interoperable with other plugins (issue #418). + region_highlight=() + fi + + # Remove all highlighting in isearch, so that only the underlining done by zsh itself remains. + # For details see FAQ entry 'Why does syntax highlighting not work while searching history?'. + # This disables highlighting during isearch (for reasons explained in README.md) unless zsh is new enough + # and doesn't have the pattern matching bug + if [[ $WIDGET == zle-isearch-update ]] && { $zsh_highlight__pat_static_bug || ! (( $+ISEARCHMATCH_ACTIVE )) }; then + return $ret + fi + + # Before we 'emulate -L', save the user's options + local -A zsyh_user_options + if zmodload -e zsh/parameter; then + zsyh_user_options=("${(kv)options[@]}") + else + local canonical_options onoff option raw_options + raw_options=(${(f)"$(emulate -R zsh; set -o)"}) + canonical_options=(${${${(M)raw_options:#*off}%% *}#no} ${${(M)raw_options:#*on}%% *}) + for option in "${canonical_options[@]}"; do + [[ -o $option ]] + case $? in + (0) zsyh_user_options+=($option on);; + (1) zsyh_user_options+=($option off);; + (*) # Can't happen, surely? + echo "zsh-syntax-highlighting: warning: '[[ -o $option ]]' returned $?" + ;; + esac + done + fi + typeset -r zsyh_user_options + + emulate -L zsh + setopt localoptions warncreateglobal nobashrematch + local REPLY # don't leak $REPLY into global scope + + # Do not highlight if there are more than 300 chars in the buffer. It's most + # likely a pasted command or a huge list of files in that case.. + [[ -n ${ZSH_HIGHLIGHT_MAXLENGTH:-} ]] && [[ $#BUFFER -gt $ZSH_HIGHLIGHT_MAXLENGTH ]] && return $ret + + # Do not highlight if there are pending inputs (copy/paste). + (( KEYS_QUEUED_COUNT > 0 )) && return $ret + (( PENDING > 0 )) && return $ret + + { + local cache_place + local -a region_highlight_copy + + # Select which highlighters in ZSH_HIGHLIGHT_HIGHLIGHTERS need to be invoked. + local highlighter; for highlighter in $ZSH_HIGHLIGHT_HIGHLIGHTERS; do + + # eval cache place for current highlighter and prepare it + cache_place="_zsh_highlight__highlighter_${highlighter}_cache" + typeset -ga ${cache_place} + + # If highlighter needs to be invoked + if ! type "_zsh_highlight_highlighter_${highlighter}_predicate" >&/dev/null; then + echo "zsh-syntax-highlighting: warning: disabling the ${(qq)highlighter} highlighter as it has not been loaded" >&2 + # TODO: use ${(b)} rather than ${(q)} if supported + ZSH_HIGHLIGHT_HIGHLIGHTERS=( ${ZSH_HIGHLIGHT_HIGHLIGHTERS:#${highlighter}} ) + elif "_zsh_highlight_highlighter_${highlighter}_predicate"; then + + # save a copy, and cleanup region_highlight + region_highlight_copy=("${region_highlight[@]}") + region_highlight=() + + # Execute highlighter and save result + { + "_zsh_highlight_highlighter_${highlighter}_paint" + } always { + : ${(AP)cache_place::="${region_highlight[@]}"} + } + + # Restore saved region_highlight + region_highlight=("${region_highlight_copy[@]}") + + fi + + # Use value form cache if any cached + region_highlight+=("${(@P)cache_place}") + + done + + # Re-apply zle_highlight settings + + # region + () { + (( REGION_ACTIVE )) || return + integer min max + if (( MARK > CURSOR )) ; then + min=$CURSOR max=$MARK + else + min=$MARK max=$CURSOR + fi + if (( REGION_ACTIVE == 1 )); then + [[ $KEYMAP = vicmd ]] && (( max++ )) + elif (( REGION_ACTIVE == 2 )); then + local needle=$'\n' + # CURSOR and MARK are 0 indexed between letters like region_highlight + # Do not include the newline in the highlight + (( min = ${BUFFER[(Ib:min:)$needle]} )) + (( max = ${BUFFER[(ib:max:)$needle]} - 1 )) + fi + _zsh_highlight_apply_zle_highlight region standout "$min" "$max" + } + + # yank / paste (zsh-5.1.1 and newer) + (( $+YANK_ACTIVE )) && (( YANK_ACTIVE )) && _zsh_highlight_apply_zle_highlight paste standout "$YANK_START" "$YANK_END" + + # isearch + (( $+ISEARCHMATCH_ACTIVE )) && (( ISEARCHMATCH_ACTIVE )) && _zsh_highlight_apply_zle_highlight isearch underline "$ISEARCHMATCH_START" "$ISEARCHMATCH_END" + + # suffix + (( $+SUFFIX_ACTIVE )) && (( SUFFIX_ACTIVE )) && _zsh_highlight_apply_zle_highlight suffix bold "$SUFFIX_START" "$SUFFIX_END" + + + return $ret + + + } always { + typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER="$BUFFER" + typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR=$CURSOR + } +} + +# Apply highlighting based on entries in the zle_highlight array. +# This function takes four arguments: +# 1. The exact entry (no patterns) in the zle_highlight array: +# region, paste, isearch, or suffix +# 2. The default highlighting that should be applied if the entry is unset +# 3. and 4. Two integer values describing the beginning and end of the +# range. The order does not matter. +_zsh_highlight_apply_zle_highlight() { + local entry="$1" default="$2" + integer first="$3" second="$4" + + # read the relevant entry from zle_highlight + # + # ### In zsh≥5.0.8 we'd use ${(b)entry}, but we support older zsh's, so we don't + # ### add (b). The only effect is on the failure mode for callers that violate + # ### the precondition. + local region="${zle_highlight[(r)${entry}:*]-}" + + if [[ -z "$region" ]]; then + # entry not specified at all, use default value + region=$default + else + # strip prefix + region="${region#${entry}:}" + + # no highlighting when set to the empty string or to 'none' + if [[ -z "$region" ]] || [[ "$region" == none ]]; then + return + fi + fi + + integer start end + if (( first < second )); then + start=$first end=$second + else + start=$second end=$first + fi + region_highlight+=("$start $end $region, memo=zsh-syntax-highlighting") +} + + +# ------------------------------------------------------------------------------------------------- +# API/utility functions for highlighters +# ------------------------------------------------------------------------------------------------- + +# Array used by highlighters to declare user overridable styles. +typeset -gA ZSH_HIGHLIGHT_STYLES + +# Whether the command line buffer has been modified or not. +# +# Returns 0 if the buffer has changed since _zsh_highlight was last called. +_zsh_highlight_buffer_modified() +{ + [[ "${_ZSH_HIGHLIGHT_PRIOR_BUFFER:-}" != "$BUFFER" ]] +} + +# Whether the cursor has moved or not. +# +# Returns 0 if the cursor has moved since _zsh_highlight was last called. +_zsh_highlight_cursor_moved() +{ + [[ -n $CURSOR ]] && [[ -n ${_ZSH_HIGHLIGHT_PRIOR_CURSOR-} ]] && (($_ZSH_HIGHLIGHT_PRIOR_CURSOR != $CURSOR)) +} + +# Add a highlight defined by ZSH_HIGHLIGHT_STYLES. +# +# Should be used by all highlighters aside from 'pattern' (cf. ZSH_HIGHLIGHT_PATTERN). +# Overwritten in tests/test-highlighting.zsh when testing. +_zsh_highlight_add_highlight() +{ + local -i start end + local highlight + start=$1 + end=$2 + shift 2 + for highlight; do + if (( $+ZSH_HIGHLIGHT_STYLES[$highlight] )); then + region_highlight+=("$start $end $ZSH_HIGHLIGHT_STYLES[$highlight], memo=zsh-syntax-highlighting") + break + fi + done +} + +# ------------------------------------------------------------------------------------------------- +# Setup functions +# ------------------------------------------------------------------------------------------------- + +# Helper for _zsh_highlight_bind_widgets +# $1 is name of widget to call +_zsh_highlight_call_widget() +{ + builtin zle "$@" && + _zsh_highlight +} + +# Decide whether to use the zle-line-pre-redraw codepath (colloquially known as +# "feature/redrawhook", after the topic branch's name) or the legacy "bind all +# widgets" codepath. +# +# We use the new codepath under two conditions: +# +# 1. If it's available, which we check by testing for add-zle-hook-widget's availability. +# +# 2. If zsh has the memo= feature, which is required for interoperability reasons. +# See issues #579 and #735, and the issues referenced from them. +# +# We check this with a plain version number check, since a functional check, +# as done by _zsh_highlight, can only be done from inside a widget +# function — a catch-22. +# +# See _zsh_highlight for the magic version number. +if is-at-least 5.8.1.1 $ZSH_VERSION.0.0 && _zsh_highlight__function_callable_p add-zle-hook-widget +then + autoload -U add-zle-hook-widget + _zsh_highlight__zle-line-finish() { + # Reset $WIDGET since the 'main' highlighter depends on it. + # + # Since $WIDGET is declared by zle as read-only in this function's scope, + # a nested function is required in order to shadow its built-in value; + # see "User-defined widgets" in zshall. + () { + local -h -r WIDGET=zle-line-finish + _zsh_highlight + } + } + _zsh_highlight__zle-line-pre-redraw() { + # Set $? to 0 for _zsh_highlight. Without this, subsequent + # zle-line-pre-redraw hooks won't run, since add-zle-hook-widget happens to + # call us with $? == 1 in the common case. + true && _zsh_highlight "$@" + } + _zsh_highlight_bind_widgets(){} + if [[ -o zle ]]; then + add-zle-hook-widget zle-line-pre-redraw _zsh_highlight__zle-line-pre-redraw + add-zle-hook-widget zle-line-finish _zsh_highlight__zle-line-finish + fi +else + # Rebind all ZLE widgets to make them invoke _zsh_highlights. + _zsh_highlight_bind_widgets() + { + setopt localoptions noksharrays + typeset -F SECONDS + local prefix=orig-s$SECONDS-r$RANDOM # unique each time, in case we're sourced more than once + + # Load ZSH module zsh/zleparameter, needed to override user defined widgets. + zmodload zsh/zleparameter 2>/dev/null || { + print -r -- >&2 'zsh-syntax-highlighting: failed loading zsh/zleparameter.' + return 1 + } + + # Override ZLE widgets to make them invoke _zsh_highlight. + local -U widgets_to_bind + widgets_to_bind=(${${(k)widgets}:#(.*|run-help|which-command|beep|set-local-history|yank|yank-pop)}) + + # Always wrap special zle-line-finish widget. This is needed to decide if the + # current line ends and special highlighting logic needs to be applied. + # E.g. remove cursor imprint, don't highlight partial paths, ... + widgets_to_bind+=(zle-line-finish) + + # Always wrap special zle-isearch-update widget to be notified of updates in isearch. + # This is needed because we need to disable highlighting in that case. + widgets_to_bind+=(zle-isearch-update) + + local cur_widget + for cur_widget in $widgets_to_bind; do + case ${widgets[$cur_widget]:-""} in + + # Already rebound event: do nothing. + user:_zsh_highlight_widget_*);; + + # The "eval"'s are required to make $cur_widget a closure: the value of the parameter at function + # definition time is used. + # + # We can't use ${0/_zsh_highlight_widget_} because these widgets are always invoked with + # NO_function_argzero, regardless of the option's setting here. + + # User defined widget: override and rebind old one with prefix "orig-". + user:*) zle -N $prefix-$cur_widget ${widgets[$cur_widget]#*:} + eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }" + zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;; + + # Completion widget: override and rebind old one with prefix "orig-". + completion:*) zle -C $prefix-$cur_widget ${${(s.:.)widgets[$cur_widget]}[2,3]} + eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget ${(q)prefix}-${(q)cur_widget} -- \"\$@\" }" + zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;; + + # Builtin widget: override and make it call the builtin ".widget". + builtin) eval "_zsh_highlight_widget_${(q)prefix}-${(q)cur_widget}() { _zsh_highlight_call_widget .${(q)cur_widget} -- \"\$@\" }" + zle -N $cur_widget _zsh_highlight_widget_$prefix-$cur_widget;; + + # Incomplete or nonexistent widget: Bind to z-sy-h directly. + *) + if [[ $cur_widget == zle-* ]] && (( ! ${+widgets[$cur_widget]} )); then + _zsh_highlight_widget_${cur_widget}() { :; _zsh_highlight } + zle -N $cur_widget _zsh_highlight_widget_$cur_widget + else + # Default: unhandled case. + print -r -- >&2 "zsh-syntax-highlighting: unhandled ZLE widget ${(qq)cur_widget}" + print -r -- >&2 "zsh-syntax-highlighting: (This is sometimes caused by doing \`bindkey ${(q-)cur_widget}\` without creating the ${(qq)cur_widget} widget with \`zle -N\` or \`zle -C\`.)" + fi + esac + done + } +fi + +# Load highlighters from directory. +# +# Arguments: +# 1) Path to the highlighters directory. +_zsh_highlight_load_highlighters() +{ + setopt localoptions noksharrays bareglobqual + + # Check the directory exists. + [[ -d "$1" ]] || { + print -r -- >&2 "zsh-syntax-highlighting: highlighters directory ${(qq)1} not found." + return 1 + } + + # Load highlighters from highlighters directory and check they define required functions. + local highlighter highlighter_dir + for highlighter_dir ($1/*/(/)); do + highlighter="${highlighter_dir:t}" + [[ -f "$highlighter_dir${highlighter}-highlighter.zsh" ]] && + . "$highlighter_dir${highlighter}-highlighter.zsh" + if type "_zsh_highlight_highlighter_${highlighter}_paint" &> /dev/null && + type "_zsh_highlight_highlighter_${highlighter}_predicate" &> /dev/null; + then + # New (0.5.0) function names + elif type "_zsh_highlight_${highlighter}_highlighter" &> /dev/null && + type "_zsh_highlight_${highlighter}_highlighter_predicate" &> /dev/null; + then + # Old (0.4.x) function names + if false; then + # TODO: only show this warning for plugin authors/maintainers, not for end users + print -r -- >&2 "zsh-syntax-highlighting: warning: ${(qq)highlighter} highlighter uses deprecated entry point names; please ask its maintainer to update it: https://github.com/zsh-users/zsh-syntax-highlighting/issues/329" + fi + # Make it work. + eval "_zsh_highlight_highlighter_${(q)highlighter}_paint() { _zsh_highlight_${(q)highlighter}_highlighter \"\$@\" }" + eval "_zsh_highlight_highlighter_${(q)highlighter}_predicate() { _zsh_highlight_${(q)highlighter}_highlighter_predicate \"\$@\" }" + else + print -r -- >&2 "zsh-syntax-highlighting: ${(qq)highlighter} highlighter should define both required functions '_zsh_highlight_highlighter_${highlighter}_paint' and '_zsh_highlight_highlighter_${highlighter}_predicate' in ${(qq):-"$highlighter_dir${highlighter}-highlighter.zsh"}." + fi + done +} + + +# ------------------------------------------------------------------------------------------------- +# Setup +# ------------------------------------------------------------------------------------------------- + +# Try binding widgets. +_zsh_highlight_bind_widgets || { + print -r -- >&2 'zsh-syntax-highlighting: failed binding ZLE widgets, exiting.' + return 1 +} + +# Resolve highlighters directory location. +_zsh_highlight_load_highlighters "${ZSH_HIGHLIGHT_HIGHLIGHTERS_DIR:-${${0:A}:h}/highlighters}" || { + print -r -- >&2 'zsh-syntax-highlighting: failed loading highlighters, exiting.' + return 1 +} + +# Reset scratch variables when commandline is done. +_zsh_highlight_preexec_hook() +{ + typeset -g _ZSH_HIGHLIGHT_PRIOR_BUFFER= + typeset -gi _ZSH_HIGHLIGHT_PRIOR_CURSOR= +} +autoload -Uz add-zsh-hook +add-zsh-hook preexec _zsh_highlight_preexec_hook 2>/dev/null || { + print -r -- >&2 'zsh-syntax-highlighting: failed loading add-zsh-hook.' + } + +# Load zsh/parameter module if available +zmodload zsh/parameter 2>/dev/null || true + +# Initialize the array of active highlighters if needed. +[[ $#ZSH_HIGHLIGHT_HIGHLIGHTERS -eq 0 ]] && ZSH_HIGHLIGHT_HIGHLIGHTERS=(main) + +if (( $+X_ZSH_HIGHLIGHT_DIRS_BLACKLIST )); then + print >&2 'zsh-syntax-highlighting: X_ZSH_HIGHLIGHT_DIRS_BLACKLIST is deprecated. Please use ZSH_HIGHLIGHT_DIRS_BLACKLIST.' + ZSH_HIGHLIGHT_DIRS_BLACKLIST=($X_ZSH_HIGHLIGHT_DIRS_BLACKLIST) + unset X_ZSH_HIGHLIGHT_DIRS_BLACKLIST +fi + +# Restore the aliases we unned +eval "$zsh_highlight__aliases" +builtin unset zsh_highlight__aliases + +# Set $?. +true diff --git a/dots/.config/zsh/config/profile/init.zsh b/configurations/price/dots/xdg/config/zsh/config/profile/init.zsh similarity index 100% rename from dots/.config/zsh/config/profile/init.zsh rename to configurations/price/dots/xdg/config/zsh/config/profile/init.zsh diff --git a/dots/.config/zsh/config/profile/profile/aliases.zsh b/configurations/price/dots/xdg/config/zsh/config/profile/profile/aliases.zsh similarity index 100% rename from dots/.config/zsh/config/profile/profile/aliases.zsh rename to configurations/price/dots/xdg/config/zsh/config/profile/profile/aliases.zsh diff --git a/dots/.config/zsh/config/profile/profile/env.zsh b/configurations/price/dots/xdg/config/zsh/config/profile/profile/env.zsh similarity index 98% rename from dots/.config/zsh/config/profile/profile/env.zsh rename to configurations/price/dots/xdg/config/zsh/config/profile/profile/env.zsh index 43720a45..c819ecca 100644 --- a/dots/.config/zsh/config/profile/profile/env.zsh +++ b/configurations/price/dots/xdg/config/zsh/config/profile/profile/env.zsh @@ -173,3 +173,6 @@ export POWERSHELL_TELEMETRY_OPTOUT=true ### NPM ### export NPM_CONFIG_PREFIX="${HOME}/.npm-global" export PATH="${PATH}:${NPM_CONFIG_PREFIX}/bin" + +### NIX ### +source "${HOME}/.nix-profile/etc/profile.d/hm-session-vars.sh" >/dev/null 2>&1 diff --git a/dots/.config/zsh/config/profile/profile/functions.zsh b/configurations/price/dots/xdg/config/zsh/config/profile/profile/functions.zsh similarity index 100% rename from dots/.config/zsh/config/profile/profile/functions.zsh rename to configurations/price/dots/xdg/config/zsh/config/profile/profile/functions.zsh diff --git a/dots/.config/zsh/config/profile/profile/keybinds.zsh b/configurations/price/dots/xdg/config/zsh/config/profile/profile/keybinds.zsh similarity index 100% rename from dots/.config/zsh/config/profile/profile/keybinds.zsh rename to configurations/price/dots/xdg/config/zsh/config/profile/profile/keybinds.zsh diff --git a/dots/.config/zsh/config/profile/profile/options.zsh b/configurations/price/dots/xdg/config/zsh/config/profile/profile/options.zsh similarity index 100% rename from dots/.config/zsh/config/profile/profile/options.zsh rename to configurations/price/dots/xdg/config/zsh/config/profile/profile/options.zsh diff --git a/dots/.config/zsh/config/style/init.zsh b/configurations/price/dots/xdg/config/zsh/config/style/init.zsh similarity index 100% rename from dots/.config/zsh/config/style/init.zsh rename to configurations/price/dots/xdg/config/zsh/config/style/init.zsh diff --git a/dots/.config/zsh/config/themes/config.zsh b/configurations/price/dots/xdg/config/zsh/config/themes/config.zsh similarity index 100% rename from dots/.config/zsh/config/themes/config.zsh rename to configurations/price/dots/xdg/config/zsh/config/themes/config.zsh diff --git a/dots/.config/zsh/config/themes/init.zsh b/configurations/price/dots/xdg/config/zsh/config/themes/init.zsh similarity index 100% rename from dots/.config/zsh/config/themes/init.zsh rename to configurations/price/dots/xdg/config/zsh/config/themes/init.zsh diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/.gitattributes b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/.gitattributes new file mode 100644 index 00000000..41b2d3a8 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/.gitattributes @@ -0,0 +1,5 @@ +* text=auto +*.zsh text eol=lf +*.zsh-theme text eol=lf +/prompt_powerlevel9k_setup text eol=lf +/prompt_powerlevel10k_setup text eol=lf diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/.gitignore b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/.gitignore new file mode 100644 index 00000000..416cfaac --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/.gitignore @@ -0,0 +1 @@ +*.zwc diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/LICENSE b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/LICENSE new file mode 100644 index 00000000..7986ede9 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/LICENSE @@ -0,0 +1,22 @@ +Copyright (c) 2009-2014 Robby Russell and contributors (see https://github.com/robbyrussell/oh-my-zsh/contributors) +Copyright (c) 2014-2017 Ben Hilburn +Copyright (c) 2019 Roman Perepelitsa and contributors (see https://github.com/romkatv/powerlevel10k/contributors) + +MIT LICENSE + +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. diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/Makefile b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/Makefile new file mode 100644 index 00000000..86e55ee4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/Makefile @@ -0,0 +1,14 @@ +ZSH := $(shell command -v zsh 2> /dev/null) + +all: + +zwc: + $(MAKE) -C gitstatus zwc + $(or $(ZSH),:) -fc 'for f in *.zsh-theme internal/*.zsh; do zcompile -R -- $$f.zwc $$f || exit; done' + +minify: + $(MAKE) -C gitstatus minify + rm -rf -- .git .gitattributes .gitignore LICENSE Makefile README.md font.md powerlevel10k.png + +pkg: zwc + $(MAKE) -C gitstatus pkg diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/README.md b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/README.md new file mode 100644 index 00000000..6ff6f449 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/README.md @@ -0,0 +1,2041 @@ +# Powerlevel10k +[![Gitter](https://badges.gitter.im/powerlevel10k/community.svg)]( + https://gitter.im/powerlevel10k/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) + +Powerlevel10k is a theme for Zsh. It emphasizes [speed](#uncompromising-performance), +[flexibility](#extremely-customizable) and [out-of-the-box experience](#configuration-wizard). + +![Powerlevel10k]( +https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/prompt-styles-high-contrast.png) + +- [Getting started](#getting-started) +- [Features](#features) +- [Installation](#installation) +- [Configuration](#configuration) +- [Fonts](#fonts) +- [Try it in Docker](#try-it-in-docker) +- [License](#license) +- [FAQ](#faq) +- [Troubleshooting](#troubleshooting) + +## Getting started + +1. [Install the recommended font](#meslo-nerd-font-patched-for-powerlevel10k). *Optional but highly + recommended.* +1. [Install Powerlevel10k](#installation) itself. +1. Restart Zsh with `exec zsh`. +1. Type `p10k configure` if the configuration wizard doesn't start automatically. + +## Features + +- [Configuration wizard](#configuration-wizard) +- [Uncompromising performance](#uncompromising-performance) +- [Powerlevel9k compatibility](#powerlevel9k-compatibility) +- [Pure compatibility](#pure-compatibility) +- [Instant prompt](#instant-prompt) +- [Show on command](#show-on-command) +- [Transient prompt](#transient-prompt) +- [Current directory that just works](#current-directory-that-just-works) +- [Extremely customizable](#extremely-customizable) +- [Batteries included](#batteries-included) +- [Extensible](#extensible) + +### Configuration wizard + +Type `p10k configure` to access the builtin configuration wizard right from your terminal. + +
+ Screen recording + + ![Powerlevel10k Configuration Wizard]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/configuration-wizard.gif) +
+ +All styles except [Pure](#pure-compatibility) are functionally equivalent. They display the same +information and differ only in presentation. + +Configuration wizard creates `~/.p10k.zsh` based on your preferences. Additional prompt +customization can be done by editing this file. It has plenty of comments to help you navigate +through configuration options. + +*Tip*: Install [the recommended font](#meslo-nerd-font-patched-for-powerlevel10k) before +running `p10k configure` to unlock all prompt styles. + +*FAQ:* + +- [What is the best prompt style in the configuration wizard?]( + #what-is-the-best-prompt-style-in-the-configuration-wizard) +- [What do different symbols in Git status mean?]( + #what-do-different-symbols-in-git-status-mean) +- [How do I change prompt colors?](#how-do-i-change-prompt-colors) + +*Troubleshooting*: + +- [Some prompt styles are missing from the configuration wizard]( + #some-prompt-styles-are-missing-from-the-configuration-wizard). +- [Question mark in prompt](#question-mark-in-prompt). +- [Icons, glyphs or powerline symbols don't render](#icons-glyphs-or-powerline-symbols-dont-render). +- [Sub-pixel imperfections around powerline symbols]( + #sub-pixel-imperfections-around-powerline-symbols). +- [Directory is difficult to see in prompt when using Rainbow style]( + #directory-is-difficult-to-see-in-prompt-when-using-rainbow-style). + +### Uncompromising performance + +When you hit *ENTER*, the next prompt appears instantly. With Powerlevel10k there is no prompt lag. +If you install Cygwin on Raspberry Pi, `cd` into a Linux Git repository and activate enough prompt +segments to fill four prompt lines on both sides of the screen... wait, that's just crazy and no +one ever does that. Probably impossible, too. The point is, Powerlevel10k prompt is always fast, no +matter what you do! + +
+ Screen recording + + ![Powerlevel10k Performance]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/performance.gif) +
+ +Note how the effect of every command is instantly reflected by the very next prompt. + +| Command | Prompt Indicator | Meaning | +|-------------------------------|:----------------:|----------------------------------------------------------------------:| +| `timew start hack linux` | `⌚ hack linux` | time tracking enabled in [timewarrior](https://timewarrior.net/) | +| `touch x y` | `?2` | 2 untracked files in the Git repo | +| `rm COPYING` | `!1` | 1 unstaged change in the Git repo | +| `echo 3.7.3 >.python-version` | `🐍 3.7.3` | the current python version in [pyenv](https://github.com/pyenv/pyenv) | + +Other Zsh themes capable of displaying the same information either produce prompt lag or print +prompt that doesn't reflect the current state of the system and then refresh it later. With +Powerlevel10k you get fast prompt *and* up-to-date information. + +*FAQ*: [Is it really fast?](#is-it-really-fast) + +### Powerlevel9k compatibility + +Powerlevel10k understands all [Powerlevel9k](https://github.com/Powerlevel9k/powerlevel9k) +configuration parameters. + +
+ Screen recording + + ![Powerlevel10k Compatibility with 9k]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/9k-compatibility.gif) +
+ +[Migration](#installation) from Powerlevel9k to Powerlevel10k is a straightforward process. All +your `POWERLEVEL9K` configuration parameters will still work. Prompt will look the same as before +([almost]( + #does-powerlevel10k-always-render-exactly-the-same-prompt-as-powerlevel9k-given-the-same-config)) +but it will be [much faster](#uncompromising-performance) ([certainly](#is-it-really-fast)). + +*FAQ*: + +- [I'm using Powerlevel9k with Oh My Zsh. How do I migrate?]( + #im-using-powerlevel9k-with-oh-my-zsh-how-do-i-migrate) +- [Does Powerlevel10k always render exactly the same prompt as Powerlevel9k given the same config?]( + #does-powerlevel10k-always-render-exactly-the-same-prompt-as-powerlevel9k-given-the-same-config) +- [What is the relationship between Powerlevel9k and Powerlevel10k?]( + #What-is-the-relationship-between-powerlevel9k-and-powerlevel10k) + +### Pure compatibility + +Powerlevel10k can produce the same prompt as [Pure](https://github.com/sindresorhus/pure). Type +`p10k configure` and select *Pure* style. + +
+ Screen recording + + ![Powerlevel10k Pure Style]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/pure-style.gif) +
+ +You can still use Powerlevel10k features such as [transient prompt](#transient-prompt) or +[instant prompt](#instant-prompt) when sporting Pure style. + +To customize prompt, edit `~/.p10k.zsh`. Powerlevel10k doesn't recognize Pure configuration +parameters, so you'll need to use `POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD=3` instead of +`PURE_CMD_MAX_EXEC_TIME=3`, etc. All relevant parameters are in `~/.p10k.zsh`. This file has +plenty of comments to help you navigate through it. + +*FAQ:* [What is the best prompt style in the configuration wizard?]( + #what-is-the-best-prompt-style-in-the-configuration-wizard) + +### Instant prompt + +If your `~/.zshrc` loads many plugins, or perhaps just a few slow ones +(for example, [pyenv](https://github.com/pyenv/pyenv) or [nvm](https://github.com/nvm-sh/nvm)), you +may have noticed that it takes some time for Zsh to start. + +
+ Screen recording + + ![Powerlevel10k No Instant Prompt]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/no-instant-prompt.gif) +
+ +Powerlevel10k can remove Zsh startup lag **even if it's not caused by a theme**. + +
+ Screen recording + + ![Powerlevel10k Instant Prompt]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/instant-prompt.gif) +
+ +This feature is called *Instant Prompt*. You need to explicitly enable it through `p10k configure` +or [manually](#how-do-i-configure-instant-prompt). It does what it says on the tin -- prints prompt +instantly upon Zsh startup allowing you to start typing while plugins are still loading. + +Other themes *increase* Zsh startup lag -- some by a lot, others by a just a little. Powerlevel10k +*removes* it outright. + +If you are curious about how *Instant Prompt* works, see +[this section in zsh-bench](https://github.com/romkatv/zsh-bench#instant-prompt). + +*FAQ:* [How do I configure instant prompt?](#how-do-i-configure-instant-prompt) + +### Show on command + +The behavior of some commands depends on global environment. For example, `kubectl run ...` runs an +image on the cluster defined by the current kubernetes context. If you frequently change context +between "prod" and "testing", you might want to display the current context in Zsh prompt. If you do +likewise for AWS, Azure and Google Cloud credentials, prompt will get pretty crowded. + +Enter *Show On Command*. This feature makes prompt segments appear only when they are relevant to +the command you are currently typing. + +
+ Screen recording + + ![Powerlevel10k Show On Command]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/show-on-command.gif) +
+ +Configs created by `p10k configure` enable show on command for several prompt segments by default. +Here's the relevant parameter for kubernetes context: + +```zsh +# Show prompt segment "kubecontext" only when the command you are typing invokes one of these tools. +typeset -g POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND='kubectl|helm|kubens' +``` + +To customize when different prompt segments are shown, open `~/.p10k.zsh`, search for +`SHOW_ON_COMMAND` and either remove these parameters to display affected segments unconditionally, +or change their values. + +### Transient prompt + +When *Transient Prompt* is enabled through `p10k configure`, Powerlevel10k will trim down every +prompt when accepting a command line. + +
+ Screen recording + + ![Powerlevel10k Transient Prompt]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/transient-prompt.gif) +
+ +Transient prompt makes it much easier to copy-paste series of commands from the terminal scrollback. + +*Tip*: If you enable transient prompt, take advantage of two-line prompt. You'll get the benefit of +extra space for typing commands without the usual drawback of reduced scrollback density. Sparse +prompt (with an empty line before prompt) also works great in combination with transient prompt. + +### Current directory that just works + +The current working directory is perhaps the most important prompt segment. Powerlevel10k goes to +great length to highlight its important parts and to truncate it with the least loss of information +when horizontal space gets scarce. + +
+ Screen recording + + ![Powerlevel10k Directory Truncation]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/directory-truncation.gif) +
+ +When the full directory doesn't fit, the leftmost segment gets truncated to its shortest unique +prefix. In the screencast, `~/work` becomes `~/wo`. It couldn't be truncated to `~/w` because it +would be ambiguous (there was `~/wireguard` when the session was recorded). The next segment -- +`projects` -- turns into `p` as there was nothing else that started with `p` in `~/work/`. + +Directory segments are shown in one of three colors: + +- Truncated segments are bleak. +- Important segments are bright and never truncated. These include the first and the last segment, + roots of Git repositories, etc. +- Regular segments (not truncated but can be) use in-between color. + +*Tip*: If you copy-paste a truncated directory and hit *TAB*, it'll complete to the original. + +*Troubleshooting*: [Directory is difficult to see in prompt when using Rainbow style.]( + #directory-is-difficult-to-see-in-prompt-when-using-rainbow-style) + +### Extremely customizable + +Powerlevel10k can be configured to look like any other Zsh theme out there. + +
+ Screen recording + + ![Powerlevel10k Other Theme Emulation]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/other-theme-emulation.gif) +
+ +[Pure](#pure-compatibility), [Powerlevel9k](#powerlevel9k-compatibility) and [robbyrussell]( + #how-to-make-powerlevel10k-look-like-robbyrussell-oh-my-zsh-theme) emulations are built-in. +To emulate the appearance of other themes, you'll need to write a suitable configuration file. The +best way to go about it is to run `p10k configure`, select the style that is the closest to your +goal and then edit `~/.p10k.zsh`. + +The full range of Powerlevel10k appearance spans from spartan: + +![Powerlevel10k Spartan Style]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/spartan-style.png) + +To ~~ridiculous~~ extravagant: + +![Powerlevel10k Extravagant Style]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/extravagant-style.png) + +### Batteries included + +Powerlevel10k comes with dozens of built-in high quality segments. When you run `p10k configure` +and choose any style except [Pure](#pure-compatibility), many of these segments get enabled by +default while others can be manually enabled by opening `~/.p10k.zsh` and uncommenting them. You can +enable as many segments as you like. It won't slow down your prompt or Zsh startup. + +| Segment | Meaning | +|--------:|---------| +| `anaconda` | virtual environment from [conda](https://conda.io/) | +| `asdf` | tool versions from [asdf](https://github.com/asdf-vm/asdf) | +| `aws` | [aws profile](https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) | +| `aws_eb_env` | [aws elastic beanstalk](https://aws.amazon.com/elasticbeanstalk/) environment | +| `azure` | [azure](https://docs.microsoft.com/en-us/cli/azure) account name | +| `background_jobs` | presence of background jobs | +| `battery` | internal battery state and charge level (yep, batteries *literally* included) | +| `command_execution_time` | duration (wall time) of the last command | +| `context` | user@hostname | +| `cpu_arch` | CPU architecture | +| `dir` | current working directory | +| `direnv` | [direnv](https://direnv.net/) status | +| `disk_usage` | disk usage | +| `dotnet_version` | [dotnet](https://dotnet.microsoft.com) version | +| `fvm` | flutter environment from [fvm](https://github.com/leoafarias/fvm) | +| `gcloud` | [google cloud](https://cloud.google.com/) cli account and project | +| `goenv` | go environment from [goenv](https://github.com/syndbg/goenv) | +| `google_app_cred` | [google application credentials](https://cloud.google.com/docs/authentication/production) | +| `go_version` | [go](https://golang.org) version | +| `haskell_stack` | haskell version from [stack](https://haskellstack.org/) | +| `ip` | IP address and bandwidth usage for a specified network interface | +| `java_version` | [java](https://www.java.com/) version | +| `jenv` | java environment from [jenv](https://github.com/jenv/jenv) | +| `kubecontext` | current [kubernetes](https://kubernetes.io/) context | +| `laravel_version` | [laravel php framework](https://laravel.com/) version | +| `load` | CPU load | +| `luaenv` | lua environment from [luaenv](https://github.com/cehoffman/luaenv) | +| `midnight_commander` | [midnight commander](https://midnight-commander.org/) shell | +| `nix_shell` | [nix shell](https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) indicator | +| `nnn` | [nnn](https://github.com/jarun/nnn) shell | +| `lf` | [lf](https://github.com/gokcehan/lf) shell | +| `chezmoi_shell` | [chezmoi](https://www.chezmoi.io/) shell | +| `nodeenv` | node.js environment from [nodeenv](https://github.com/ekalinin/nodeenv) | +| `nodenv` | node.js environment from [nodenv](https://github.com/nodenv/nodenv) | +| `node_version` | [node.js](https://nodejs.org/) version | +| `nordvpn` | [nordvpn](https://nordvpn.com/) connection status | +| `nvm` | node.js environment from [nvm](https://github.com/nvm-sh/nvm) | +| `os_icon` | your OS logo (apple for macOS, swirl for debian, etc.) | +| `package` | `name@version` from [package.json](https://docs.npmjs.com/files/package.json) | +| `perlbrew` | perl version from [perlbrew](https://github.com/gugod/App-perlbrew) | +| `phpenv` | php environment from [phpenv](https://github.com/phpenv/phpenv) | +| `php_version` | [php](https://www.php.net/) version | +| `plenv` | perl environment from [plenv](https://github.com/tokuhirom/plenv) | +| `prompt_char` | multi-functional prompt symbol; changes depending on vi mode: `❯`, `❮`, `V`, `▶` for insert, command, visual and replace mode respectively; turns red on error | +| `proxy` | system-wide http/https/ftp proxy | +| `public_ip` | public IP address | +| `pyenv` | python environment from [pyenv](https://github.com/pyenv/pyenv) | +| `ram` | free RAM | +| `ranger` | [ranger](https://github.com/ranger/ranger) shell | +| `rbenv` | ruby environment from [rbenv](https://github.com/rbenv/rbenv) | +| `rust_version` | [rustc](https://www.rust-lang.org) version | +| `rvm` | ruby environment from [rvm](https://rvm.io) | +| `scalaenv` | scala version from [scalaenv](https://github.com/scalaenv/scalaenv) | +| `status` | exit code of the last command | +| `swap` | used swap | +| `taskwarrior` | [taskwarrior](https://taskwarrior.org/) task count | +| `terraform` | [terraform](https://www.terraform.io) workspace | +| `terraform_version` | [terraform](https://www.terraform.io) version | +| `time` | current time | +| `timewarrior` | [timewarrior](https://timewarrior.net/) tracking status | +| `todo` | [todo](https://github.com/todotxt/todo.txt-cli) items | +| `toolbox` | [toolbox](https://github.com/containers/toolbox) name | +| `vcs` | Git repository status | +| `vim_shell` | [vim](https://www.vim.org/) shell (`:sh`) | +| `virtualenv` | python environment from [venv](https://docs.python.org/3/library/venv.html) | +| `vi_mode` | vi mode (you don't need this if you've enabled prompt_char) | +| `vpn_ip` | virtual private network indicator | +| `wifi` | WiFi speed | +| `xplr` | [xplr](https://github.com/sayanarijit/xplr) shell | + +### Extensible + +If there is no prompt segment that does what you need, implement your own. Powerlevel10k provides +public API for defining segments that are as fast and as flexible as built-in ones. + +
+ Screen recording + + ![Powerlevel10k Custom Segment]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/custom-segment.gif) +
+ +On Linux you can fetch current CPU temperature by reading `/sys/class/thermal/thermal_zone0/temp`. +The screencast shows how to define a prompt segment to display this value. Once the segment is +defined, you can use it like any other segment. All standard customization parameters will work for +it out of the box. + +Type `p10k help segment` for reference. + +*Tip*: Prefix names of your own segments with `my_` to avoid clashes with future versions of +Powerlevel10k. + +## Installation + +- [Manual](#manual) 👈 **choose this if confused or uncertain** +- [Oh My Zsh](#oh-my-zsh) +- [Prezto](#prezto) +- [Zim](#zim) +- [Antibody](#antibody) +- [Antidote](#antidote) +- [Antigen](#antigen) +- [Zplug](#zplug) +- [Zgen](#zgen) +- [Zplugin](#zplugin) +- [Zinit](#zinit) +- [Zi](#zi) +- [Zap](#zap) +- [Homebrew](#homebrew) +- [Arch Linux](#arch-linux) +- [Alpine Linux](#alpine-linux) +- [Fig](#fig) + +### Manual + +```zsh +git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ~/powerlevel10k +echo 'source ~/powerlevel10k/powerlevel10k.zsh-theme' >>~/.zshrc +``` + +Users in China can use the official mirror on gitee.com for faster download.
+中国用户可以使用 gitee.com 上的官方镜像加速下载. + +```zsh +git clone --depth=1 https://gitee.com/romkatv/powerlevel10k.git ~/powerlevel10k +echo 'source ~/powerlevel10k/powerlevel10k.zsh-theme' >>~/.zshrc +``` + +This is the simplest kind of installation and it works even if you are using a plugin manager. Just +make sure to disable the current theme in your plugin manager. See +[troubleshooting](#cannot-make-powerlevel10k-work-with-my-plugin-manager) for help. + +### Oh My Zsh + +1. Clone the repository: + ```zsh + git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k + ``` + Users in China can use the official mirror on gitee.com for faster download.
+ 中国用户可以使用 gitee.com 上的官方镜像加速下载. + + ```zsh + git clone --depth=1 https://gitee.com/romkatv/powerlevel10k.git ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k + ``` +2. Set `ZSH_THEME="powerlevel10k/powerlevel10k"` in `~/.zshrc`. + +### Prezto + +Add `zstyle :prezto:module:prompt theme powerlevel10k` to `~/.zpreztorc`. + +### Zim + +Add `zmodule romkatv/powerlevel10k --use degit` to `~/.zimrc` and run `zimfw install`. + +### Antibody + +Add `antibody bundle romkatv/powerlevel10k` to `~/.zshrc`. + +### Antidote + +Add `romkatv/powerlevel10k` to `~/.zsh_plugins.txt`. + +### Antigen + +Add `antigen theme romkatv/powerlevel10k` to `~/.zshrc`. Make sure you have `antigen apply` +somewhere after it. + +### Zplug + +Add `zplug romkatv/powerlevel10k, as:theme, depth:1` to `~/.zshrc`. + +### Zgen + +Add `zgen load romkatv/powerlevel10k powerlevel10k` to `~/.zshrc`. + +### Zplugin + +Add `zplugin ice depth=1; zplugin light romkatv/powerlevel10k` to `~/.zshrc`. + +The use of `depth=1` ice is optional. Other types of ice are neither recommended nor officially +supported by Powerlevel10k. + +### Zinit + +Add `zinit ice depth=1; zinit light romkatv/powerlevel10k` to `~/.zshrc`. + +The use of `depth=1` ice is optional. Other types of ice are neither recommended nor officially +supported by Powerlevel10k. + +### Zi + +Add `zi ice depth=1; zi light romkatv/powerlevel10k` to `~/.zshrc`. + +The use of `depth=1` ice is optional. Other types of ice are neither recommended nor officially +supported by Powerlevel10k. + +### Zap + +Add `plug "romkatv/powerlevel10k"` to `~/.zshrc`. + +### Homebrew + +```zsh +brew install powerlevel10k +echo "source $(brew --prefix)/share/powerlevel10k/powerlevel10k.zsh-theme" >>~/.zshrc +``` + +### Arch Linux + +```zsh +yay -S --noconfirm zsh-theme-powerlevel10k-git +echo 'source /usr/share/zsh-theme-powerlevel10k/powerlevel10k.zsh-theme' >>~/.zshrc +``` + +[zsh-theme-powerlevel10k-git](https://aur.archlinux.org/packages/zsh-theme-powerlevel10k-git/) +referenced above is the official Powerlevel10k package. + +There is also [zsh-theme-powerlevel10k]( + https://www.archlinux.org/packages/community/x86_64/zsh-theme-powerlevel10k/) community package. +Historically, [it has been breaking often and for extended periods of time]( + https://github.com/romkatv/powerlevel10k/pull/786). **Do not use it.** + +### Alpine Linux + +```zsh +apk add zsh zsh-theme-powerlevel10k +mkdir -p ~/.local/share/zsh/plugins +ln -s /usr/share/zsh/plugins/powerlevel10k ~/.local/share/zsh/plugins/ +``` + +### Fig + +Follow the instructions on +[this page](https://fig.io/plugins/other/powerlevel10k). + +## Configuration + +- [For new users](#for-new-users) +- [For Powerlevel9k users](#for-powerlevel9k-users) + +### For new users + +On the first run, Powerlevel10k [configuration wizard](#configuration-wizard) will ask you a few +questions and configure your prompt. If it doesn't trigger automatically, type `p10k configure`. +Configuration wizard creates `~/.p10k.zsh` based on your preferences. Additional prompt +customization can be done by editing this file. It has plenty of comments to help you navigate +through configuration options. + +*FAQ*: + +- [What is the best prompt style in the configuration wizard?]( + #what-is-the-best-prompt-style-in-the-configuration-wizard) +- [What do different symbols in Git status mean?]( + #what-do-different-symbols-in-git-status-mean) +- [How do I change the format of Git status?](#how-do-i-change-the-format-of-git-status) +- [How do I add username and/or hostname to prompt?]( + #how-do-i-add-username-andor-hostname-to-prompt) +- [How do I change prompt colors?](#how-do-i-change-prompt-colors) +- [Why some prompt segments appear and disappear as I'm typing?]( + #why-some-prompt-segments-appear-and-disappear-as-im-typing) + +*Troubleshooting*: + +- [Question mark in prompt](#question-mark-in-prompt). +- [Icons, glyphs or powerline symbols don't render](#icons-glyphs-or-powerline-symbols-dont-render). +- [Sub-pixel imperfections around powerline symbols]( + #sub-pixel-imperfections-around-powerline-symbols). +- [Directory is difficult to see in prompt when using Rainbow style]( + #directory-is-difficult-to-see-in-prompt-when-using-rainbow-style). + +### For Powerlevel9k users + +If you've been using Powerlevel9k before, **do not remove the configuration options**. Powerlevel10k +will pick them up and provide you with the same prompt UI you are used to. See +[Powerlevel9k compatibility](#powerlevel9k-compatibility). + +*FAQ*: + +- [I'm using Powerlevel9k with Oh My Zsh. How do I migrate?]( + #im-using-powerlevel9k-with-oh-my-zsh-how-do-i-migrate) +- [What is the relationship between Powerlevel9k and Powerlevel10k?]( + #what-is-the-relationship-between-powerlevel9k-and-powerlevel10k) +- [Does Powerlevel10k always render exactly the same prompt as Powerlevel9k given the same config?]( + #does-powerlevel10k-always-render-exactly-the-same-prompt-as-powerlevel9k-given-the-same-config) + +*Troubleshooting*: [Extra or missing spaces in prompt compared to Powerlevel9k]( + #extra-or-missing-spaces-in-prompt-compared-to-powerlevel9k). + +## Fonts + +Powerlevel10k doesn't require custom fonts but can take advantage of them if they are available. +It works well with [Nerd Fonts](https://github.com/ryanoasis/nerd-fonts), +[Source Code Pro](https://github.com/adobe-fonts/source-code-pro), +[Font Awesome](https://fontawesome.com/), [Powerline](https://github.com/powerline/fonts), and even +the default system fonts. The full choice of style options is available only when using +[Nerd Fonts](https://github.com/ryanoasis/nerd-fonts). + +👇 **Recommended font**: Meslo Nerd Font patched for Powerlevel10k. 👇 + +### Meslo Nerd Font patched for Powerlevel10k + +Gorgeous monospace font designed by Jim Lyles for Bitstream, customized by the same for Apple, +further customized by André Berg, and finally patched by yours truly with customized scripts +originally developed by Ryan L McIntyre of Nerd Fonts. Contains all glyphs and symbols that +Powerlevel10k may need. Battle-tested in dozens of different terminals on all major operating +systems. + +*FAQ*: [How was the recommended font created?](#how-was-the-recommended-font-created) + +#### Automatic font installation + +If you are using iTerm2 or Termux, `p10k configure` can install the recommended font for you. +Simply answer `Yes` when asked whether to install *Meslo Nerd Font*. + +If you are using a different terminal, proceed with manual font installation. 👇 + +#### Manual font installation + +1. Download these four ttf files: + - [MesloLGS NF Regular.ttf]( + https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Regular.ttf) + - [MesloLGS NF Bold.ttf]( + https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Bold.ttf) + - [MesloLGS NF Italic.ttf]( + https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Italic.ttf) + - [MesloLGS NF Bold Italic.ttf]( + https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Bold%20Italic.ttf) +1. Double-click on each file and click "Install". This will make `MesloLGS NF` font available to all + applications on your system. +1. Configure your terminal to use this font: + - **iTerm2**: Type `p10k configure` and answer `Yes` when asked whether to install + *Meslo Nerd Font*. Alternatively, open *iTerm2 → Preferences → Profiles → Text* and set *Font* to + `MesloLGS NF`. + - **Apple Terminal**: Open *Terminal → Preferences → Profiles → Text*, click *Change* under *Font* + and select `MesloLGS NF` family. + - **Hyper**: Open *Hyper → Edit → Preferences* and change the value of `fontFamily` under + `module.exports.config` to `MesloLGS NF`. + - **Visual Studio Code**: Open *File → Preferences → Settings* (PC) or + *Code → Preferences → Settings* (Mac), enter `terminal.integrated.fontFamily` in the search box at + the top of *Settings* tab and set the value below to `MesloLGS NF`. + Consult [this screenshot]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/389133fb8c9a2347929a23702ce3039aacc46c3d/visual-studio-code-font-settings.jpg) + to see how it should look like or see [this issue]( + https://github.com/romkatv/powerlevel10k/issues/671) for extra information. + - **GNOME Terminal** (the default Ubuntu terminal): Open *Terminal → Preferences* and click on the + selected profile under *Profiles*. Check *Custom font* under *Text Appearance* and select + `MesloLGS NF Regular`. + - **Konsole**: Open *Settings → Edit Current Profile → Appearance*, click *Select Font* and select + `MesloLGS NF Regular`. + - **Tilix**: Open *Tilix → Preferences* and click on the selected profile under *Profiles*. Check + *Custom font* under *Text Appearance* and select `MesloLGS NF Regular`. + - **Windows Console Host** (the old thing): Click the icon in the top left corner, then + *Properties → Font* and set *Font* to `MesloLGS NF`. + - **Windows Terminal** by Microsoft (the new thing): Open *Settings* (Ctrl+,), click + either on the selected profile under *Profiles* or on *Defaults*, click *Appearance* and set + *Font face* to `MesloLGS NF`. + - **IntelliJ** (and other IDEs by Jet Brains): Open *IDE → Edit → Preferences → Editor → + Color Scheme → Console Font*. Select *Use console font instead of the default* and set the font + name to `MesloLGS NF`. + - **Termux**: Type `p10k configure` and answer `Yes` when asked whether to install + *Meslo Nerd Font*. + - **Blink**: Type `config`, go to *Appearance*, tap *Add a new font*, tap *Open Gallery*, select + *MesloLGS NF.css*, tap *import* and type `exit` in the home view to reload the font. + - **Tabby** (formerly **Terminus**): Open *Settings → Appearance* and set *Font* to `MesloLGS NF`. + - **Terminator**: Open *Preferences* using the context menu. Under *Profiles* select the *General* + tab (should be selected already), uncheck *Use the system fixed width font* (if not already) + and select `MesloLGS NF Regular`. Exit the Preferences dialog by clicking *Close*. + - **Guake**: Right Click on an open terminal and open *Preferences*. Under *Appearance* + tab, uncheck *Use the system fixed width font* (if not already) and select `MesloLGS NF Regular`. + Exit the Preferences dialog by clicking *Close*. + - **MobaXterm**: Open *Settings* → *Configuration* → *Terminal* → (under *Terminal look and feel*) + and change *Font* to `MesloLGS NF`. + - **Asbrú Connection Manager**: Open *Preferences → Local Shell Options → Look and Feel*, enable + *Use these personal options* and change *Font:* under *Terminal UI* to `MesloLGS NF Regular`. + To change the font for the remote host connections, go to *Preferences → Terminal Options → + Look and Feel* and change *Font:* under *Terminal UI* to `MesloLGS NF Regular`. + - **WSLtty**: Right click on an open terminal and then on *Options*. In the *Text* section, under + *Font*, click *"Select..."* and set Font to `MesloLGS NF Regular`. + - **Yakuake**: Click *≡* → *Manage Profiles* → *New* → *Appearance*. Click *Choose* next to the + *Font* dropdown, select `MesloLGS NF` and click *OK*. Click *OK* to save the profile. Select the + new profile and click *Set as Default*. + - **Alacritty**: Create or open `~/.config/alacritty/alacritty.yml` and add the following section + to it: + ```yaml + font: + normal: + family: "MesloLGS NF" + ``` + - **kitty**: Create or open `~/.config/kitty/kitty.conf` and add the following line to it: + ```text + font_family MesloLGS NF + ``` + Restart kitty by closing all sessions and opening a new session. + - **puTTY**: Set *Window* → *Appearance* → *Font* to `MesloLGS NF`. Requires puTTY + version >= 0.75. + - **WezTerm**: Create or open `$HOME/.config/wezterm/wezterm.lua` and add the following: + ```lua + local wezterm = require 'wezterm'; + return { + font = wezterm.font("MesloLGS NF"), + } + ``` + If the file already exists, only add the line with the font to the existing return. + Also add the first line if it is not already present. + - **urxvt**: Create or open `~/.Xresources` and add the following line to it: + ```text + URxvt.font: xft:MesloLGS NF:size=11 + ``` + You can adjust the font size to your preference. After changing the config run + `xrdb ~/.Xresources` to reload it. The new config is applied to all new terminals. + - **xterm**: Create or open `~/.Xresources` and add the following line to it: + ```text + xterm*faceName: MesloLGS NF + ``` + After changing the config run `xrdb ~/.Xresources` to reload it. The new config is applied to + all new terminals. + - **Zed**: Open `~/.config/zed/settings.json` and set `terminal.font_family` to `"MesloLGS NF"`. + ```jsonc + { + "terminal": { + "font_family": "MesloLGS NF" + }, + // Other settings. + } + ``` + - Crostini (Linux on Chrome OS): Open + chrome-untrusted://terminal/html/nassh_preferences_editor.html, set *Text font family* to + `'MesloLGS NF'` (including the quotes) and *Custom CSS (inline text)* to the following: + ```css + @font-face { + font-family: "MesloLGS NF"; + src: url("https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/MesloLGS%20NF%20Regular.ttf"); + font-weight: normal; + font-style: normal; + } + @font-face { + font-family: "MesloLGS NF"; + src: url("https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/MesloLGS%20NF%20Bold.ttf"); + font-weight: bold; + font-style: normal; + } + @font-face { + font-family: "MesloLGS NF"; + src: url("https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/MesloLGS%20NF%20Italic.ttf"); + font-weight: normal; + font-style: italic; + } + @font-face { + font-family: "MesloLGS NF"; + src: url("https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/MesloLGS%20NF%20Bold%20Italic.ttf"); + font-weight: bold; + font-style: italic; + } + ``` + **_CAVEAT_**: If you open the normal terminal preferences these settings will be overwritten. +1. Run `p10k configure` to generate a new `~/.p10k.zsh`. The old config may work + incorrectly with the new font. + +_Using a different terminal and know how to set the font for it? Share your knowledge by sending a +PR to expand the list!_ + +## Try it in Docker + +Try Powerlevel10k in Docker. You can safely make any changes to the file system while trying out +the theme. Once you exit Zsh, the container is deleted. + +```zsh +docker run -e TERM -e COLORTERM -e LC_ALL=C.UTF-8 -it --rm alpine sh -uec ' + apk add git zsh nano vim + git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ~/powerlevel10k + echo "source ~/powerlevel10k/powerlevel10k.zsh-theme" >>~/.zshrc + cd ~/powerlevel10k + exec zsh' +``` + +*Tip*: Install [the recommended font](#meslo-nerd-font-patched-for-powerlevel10k) before +running the Docker command to get access to all prompt styles. + +*Tip*: Run `p10k configure` while in Docker to try a different prompt style. + +## License + +Powerlevel10k is released under the +[MIT license](https://github.com/romkatv/powerlevel10k/blob/master/LICENSE). + +## FAQ + +- [How do I update Powerlevel10k?](#how-do-i-update-powerlevel10k) +- [How do I uninstall Powerlevel10k?](#how-do-i-uninstall-powerlevel10k) +- [How do I install Powerlevel10k on a machine without Internet access?](#how-do-i-install-powerlevel10k-on-a-machine-without-internet-access) +- [Where can I ask for help and report bugs?](#where-can-i-ask-for-help-and-report-bugs) +- [Which aspects of shell and terminal does Powerlevel10k affect?](#which-aspects-of-shell-and-terminal-does-powerlevel10k-affect) +- [I'm using Powerlevel9k with Oh My Zsh. How do I migrate?](#im-using-powerlevel9k-with-oh-my-zsh-how-do-i-migrate) +- [Is it really fast?](#is-it-really-fast) +- [How do I configure instant prompt?](#how-do-i-configure-instant-prompt) +- [How do I initialize direnv when using instant prompt?](#how-do-i-initialize-direnv-when-using-instant-prompt) +- [How do I export GPG_TTY when using instant prompt?](#how-do-i-export-gpg_tty-when-using-instant-prompt) +- [What do different symbols in Git status mean?](#what-do-different-symbols-in-git-status-mean) +- [How do I change the format of Git status?](#how-do-i-change-the-format-of-git-status) +- [Why is Git status from `$HOME/.git` not displayed in prompt?](#why-is-git-status-from-homegit-not-displayed-in-prompt) +- [Why does Git status sometimes appear grey and then gets colored after a short period of time?](#why-does-git-status-sometimes-appear-grey-and-then-gets-colored-after-a-short-period-of-time) +- [How do I add username and/or hostname to prompt?](#how-do-i-add-username-andor-hostname-to-prompt) +- [Why some prompt segments appear and disappear as I'm typing?](#why-some-prompt-segments-appear-and-disappear-as-im-typing) +- [How do I change prompt colors?](#how-do-i-change-prompt-colors) +- [Why does Powerlevel10k spawn extra processes?](#why-does-powerlevel10k-spawn-extra-processes) +- [Are there configuration options that make Powerlevel10k slow?](#are-there-configuration-options-that-make-powerlevel10k-slow) +- [Is Powerlevel10k fast to load?](#is-powerlevel10k-fast-to-load) +- [What is the relationship between Powerlevel9k and Powerlevel10k?](#what-is-the-relationship-between-powerlevel9k-and-powerlevel10k) +- [Does Powerlevel10k always render exactly the same prompt as Powerlevel9k given the same config?](#does-powerlevel10k-always-render-exactly-the-same-prompt-as-powerlevel9k-given-the-same-config) +- [What is the best prompt style in the configuration wizard?](#what-is-the-best-prompt-style-in-the-configuration-wizard) +- [How to make Powerlevel10k look like robbyrussell Oh My Zsh theme?](#how-to-make-powerlevel10k-look-like-robbyrussell-oh-my-zsh-theme) +- [Can prompts for completed commands display error status for *those* commands instead of the commands preceding them?](#can-prompts-for-completed-commands-display-error-status-for-those-commands-instead-of-the-commands-preceding-them) +- [What is the minimum supported Zsh version?](#what-is-the-minimum-supported-zsh-version) +- [How were these screenshots and animated gifs created?](#how-were-these-screenshots-and-animated-gifs-created) +- [How was the recommended font created?](#how-was-the-recommended-font-created) +- [How to package Powerlevel10k for distribution?](#how-to-package-powerlevel10k-for-distribution) + +### How do I update Powerlevel10k? + +The command to update Powerlevel10k depends on how it was installed. + +| Installation | Update command | +|-------------------------------|-------------------------------------------------------------| +| [Manual](#manual) | `git -C ~/powerlevel10k pull` | +| [Oh My Zsh](#oh-my-zsh) | `git -C ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k pull` | +| [Prezto](#prezto) | `zprezto-update` | +| [Zim](#zim) | `zimfw update` | +| [Antigen](#antigen) | `antigen update` | +| [Antidote](#antidote) | `antidote update` | +| [Zplug](#zplug) | `zplug update` | +| [Zgen](#zgen) | `zgen update` | +| [Zplugin](#zplugin) | `zplugin update` | +| [Zinit](#zinit) | `zinit update` | +| [Zi](#zi) | `zi update` | +| [Zap](#zap) | `zap update` | +| [Homebrew](#homebrew) | `brew update && brew upgrade` | +| [Arch Linux](#arch-linux) | `yay -S --noconfirm zsh-theme-powerlevel10k-git` | +| [Alpine Linux](#alpine-linux) | `apk update && apk upgrade` | + +**IMPORTANT**: Restart Zsh after updating Powerlevel10k. [Do not use `source ~/.zshrc`]( + #weird-things-happen-after-typing-source-zshrc). + +### How do I uninstall Powerlevel10k? + +1. Remove all references to "p10k" from `~/.zshrc`. You might have this snippet at the top: + ```zsh + if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then + source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" + fi + ``` + And this at the bottom: + ```zsh + [[ ! -f ~/.p10k.zsh ]] || source ~/.p10k.zsh + ``` + These are added by the [configuration wizard](#configuration-wizard). Remove them. +2. Remove all references to "powerlevel10k" from `~/.zshrc`, `~/.zpreztorc` and `~/.zimrc` (some + of these files may be missing -- this is normal). These references have been added manually by + yourself when installing Powerlevel10k. Refer to the [installation instructions](#installation) + if you need a reminder. +3. Verify that all references to "p10k" and "powerlevel10k" are gone from `~/.zshrc`, `~/.zpreztorc` + and `~/.zimrc`. + ```zsh + grep -E 'p10k|powerlevel10k' ~/.zshrc ~/.zpreztorc ~/.zimrc 2>/dev/null + ``` + If this command produces output, there are still references to "p10k" or "powerlevel10k". You + need to remove them. +4. Delete Powerlevel10k configuration file. This file is created by the + [configuration wizard](#configuration-wizard) and may contain manual edits by yourself. + ```zsh + rm -f ~/.p10k.zsh + ``` +5. Delete Powerlevel10k source files. These files have been downloaded when you've installed + Powerlevel10k. The command to delete them depends on which installation method you'd chosen. + Refer to the [installation instructions](#installation) if you need a reminder. + + | Installation | Uninstall command | + |-------------------------------|------------------------------------------------------------------| + | [Manual](#manual) | `rm -rf ~/powerlevel10k` | + | [Oh My Zsh](#oh-my-zsh) | `rm -rf -- ${ZSH_CUSTOM:-$HOME/.oh-my-zsh/custom}/themes/powerlevel10k` | + | [Prezto](#prezto) | n/a | + | [Zim](#zim) | `zimfw uninstall` | + | [Antigen](#antigen) | `antigen purge romkatv/powerlevel10k` | + | [Antidote](#antidote) | `antidote purge romkatv/powerlevel10k` | + | [Zplug](#zplug) | `zplug clean` | + | [Zgen](#zgen) | `zgen reset` | + | [Zplugin](#zplugin) | `zplugin delete romkatv/powerlevel10k` | + | [Zinit](#zinit) | `zinit delete romkatv/powerlevel10k` | + | [Zi](#zi) | `zi delete romkatv/powerlevel10k` | + | [Zap](#zap) | `zsh -ic 'zap clean'` | + | [Homebrew](#homebrew) | `brew uninstall powerlevel10k` | + | [Arch Linux](#arch-linux) | `yay -R --noconfirm zsh-theme-powerlevel10k-git` | + | [Alpine Linux](#alpine-linux) | `apk del zsh-theme-powerlevel10k` | +6. Restart Zsh. [Do not use `source ~/.zshrc`](#weird-things-happen-after-typing-source-zshrc). +7. Delete Powerlevel10k cache files. + ```zsh + rm -rf -- "${XDG_CACHE_HOME:-$HOME/.cache}"/p10k-*(N) "${XDG_CACHE_HOME:-$HOME/.cache}"/gitstatus + ``` + +### How do I install Powerlevel10k on a machine without Internet access? + +1. Run this command on the machine without Internet access: + ```sh + uname -sm | tr '[A-Z]' '[a-z]' + ``` +2. Run these commands on a machine connected to the Internet after replacing the value of + `target_uname` with the output of the previous command: + ```sh + target_uname="replace this with the output of the previous command" + git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ~/powerlevel10k + GITSTATUS_CACHE_DIR="$HOME"/powerlevel10k/gitstatus/usrbin ~/powerlevel10k/gitstatus/install -f -s "${target_uname% *}" -m "${target_uname#* }" + ``` +3. Copy `~/powerlevel10k` from the machine connected to the Internet to the one without Internet + access. +4. Add `source ~/powerlevel10k/powerlevel10k.zsh-theme` to `~/.zshrc` on the machine without + Internet access: + ```zsh + echo 'source ~/powerlevel10k/powerlevel10k.zsh-theme' >>~/.zshrc + ``` +5. If `~/.zshrc` on the machine without Internet access sets `ZSH_THEME`, remove that line. + ```zsh + sed -i.bak '/^ZSH_THEME=/d' ~/.zshrc + ``` + +To update, remove `~/powerlevel10k` on both machines and repeat steps 1-3. + +### Where can I ask for help and report bugs? + +The best way to ask for help and to report bugs is to [open an issue]( + https://github.com/romkatv/powerlevel10k/issues). + +[Gitter]( + https://gitter.im/powerlevel10k/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) +is another option. + +If all else fails, email roman.perepelitsa@gmail.com. + +If necessary, encrypt your communication with [this PGP key]( + https://api.github.com/users/romkatv/gpg_keys). + +### Which aspects of shell and terminal does Powerlevel10k affect? + +Powerlevel10k defines prompt and nothing else. It sets [prompt-related options]( + http://zsh.sourceforge.net/Doc/Release/Options.html#Prompting), and parameters `PS1` and `RPS1`. + +![Prompt Highlight]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/prompt-highlight.png) + +Everything within the highlighted areas on the screenshot is produced by Powerlevel10k. +Powerlevel10k has no control over the terminal content or colors outside these areas. + +Powerlevel10k does not affect: + +- Terminal window/tab title. +- Colors used by `ls`. +- The behavior of `git` command. +- The content and style of Tab completions. +- Command line colors (syntax highlighting, autosuggestions, etc.). +- Key bindings. +- Aliases. +- Prompt parameters other than `PS1` and `RPS1`. +- Zsh options other than those [related to prompt]( + http://zsh.sourceforge.net/Doc/Release/Options.html#Prompting). + +### I'm using Powerlevel9k with Oh My Zsh. How do I migrate? + +1. Run this command: +```zsh +# Add powerlevel10k to the list of Oh My Zsh themes. +git clone --depth=1 https://github.com/romkatv/powerlevel10k.git $ZSH_CUSTOM/themes/powerlevel10k +# Replace ZSH_THEME="powerlevel9k/powerlevel9k" with ZSH_THEME="powerlevel10k/powerlevel10k". +sed -i.bak 's/powerlevel9k/powerlevel10k/g' ~/.zshrc +# Restart Zsh. +exec zsh +``` +2. *Optional but highly recommended:* + 1. Install [the recommended font](#meslo-nerd-font-patched-for-powerlevel10k). + 1. Type `p10k configure` and choose your favorite prompt style. + +*Related:* + - [Powerlevel9k compatibility.](#powerlevel9k-compatibility) + - [Does Powerlevel10k always render exactly the same prompt as Powerlevel9k given the same config?]( + #does-powerlevel10k-always-render-exactly-the-same-prompt-as-powerlevel9k-given-the-same-config) + - [Extra or missing spaces in prompt compared to Powerlevel9k.]( + #extra-or-missing-spaces-in-prompt-compared-to-powerlevel9k) + - [Configuration wizard.](#configuration-wizard) + +### Is it really fast? + +Yes. See [zsh-bench](https://github.com/romkatv/zsh-bench) or a direct comparison with +[Powerlevel9k](https://asciinema.org/a/NHRjK3BMePw66jtRVY2livHwZ) and +[Spaceship](https://asciinema.org/a/253094). + +### How do I configure instant prompt? + +See [instant prompt](#instant-prompt) to learn about instant prompt. This section explains how you +can enable and configure it and lists caveats that you should be aware of. + +Instant prompt can be enabled either through `p10k configure` or by manually adding the following +code snippet at the top of `~/.zshrc`: + +```zsh +# Enable Powerlevel10k instant prompt. Should stay close to the top of ~/.zshrc. +# Initialization code that may require console input (password prompts, [y/n] +# confirmations, etc.) must go above this block; everything else may go below. +if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then + source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" +fi +``` + +It's important that you copy the lines verbatim. Don't replace `source` with something else, don't +call `zcompile`, don't redirect output, etc. + +When instant prompt is enabled, for the duration of Zsh initialization standard input is redirected +to `/dev/null` and standard output with standard error are redirected to a temporary file. Once Zsh +is fully initialized, standard file descriptors are restored and the content of the temporary file +is printed out. + +When using instant prompt, you should carefully check any output that appears on Zsh startup as it +may indicate that initialization has been altered, or perhaps even broken, by instant prompt. +Initialization code that may require console input, such as asking for a keyring password or for a +*[y/n]* confirmation, must be moved above the instant prompt preamble in `~/.zshrc`. Initialization +code that merely prints to console but never reads from it will work correctly with instant prompt, +although output that normally has colors may appear uncolored. You can either leave it be, suppress +the output, or move it above the instant prompt preamble. + +Here's an example of `~/.zshrc` that breaks when instant prompt is enabled: + +```zsh +if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then + source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" +fi + +keychain id_rsa --agents ssh # asks for password +chatty-script # spams to stdout even when everything is fine +# ... +``` + +Fixed version: + +```zsh +keychain id_rsa --agents ssh # moved before instant prompt + +# OK to perform console I/O before this point. +if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then + source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" +fi +# From this point on, until zsh is fully initialized, console input won't work and +# console output may appear uncolored. + +chatty-script >/dev/null # spam output suppressed +# ... +``` + +If `POWERLEVEL9K_INSTANT_PROMPT` is unset or set to `verbose`, Powerlevel10k will print a warning +when it detects console output during initialization to bring attention to potential issues. You can +silence this warning (without suppressing console output) with `POWERLEVEL9K_INSTANT_PROMPT=quiet`. +This is recommended if some initialization code in `~/.zshrc` prints to console and it's infeasible +to move it above the instant prompt preamble or to suppress its output. You can completely disable +instant prompt with `POWERLEVEL9K_INSTANT_PROMPT=off`. Do this if instant prompt breaks Zsh +initialization and you don't know how to fix it. + +The value of `POWERLEVEL9K_INSTANT_PROMPT` can be changed by running `p10k configure` and selecting +the appropriate option on the *Instant Prompt* screen. Alternatively, you can search for +`POWERLEVEL9K_INSTANT_PROMPT` in the existing `~/.p10k.zsh` and change its value there. + +*Note*: Instant prompt requires Zsh >= 5.4. It's OK to enable it even when using an older version of +Zsh but it won't do anything. + +*FAQ*: + +- [How do I initialize direnv when using instant prompt?]( + #how-do-i-initialize-direnv-when-using-instant-prompt) +- [How do I export GPG_TTY when using instant prompt?]( + #how-do-i-export-gpg_tty-when-using-instant-prompt) + +### How do I initialize direnv when using instant prompt? + +If you've enabled [instant prompt](#instant-prompt), you should have these lines at the top of +`~/.zshrc`: + +```zsh +if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then + source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" +fi +``` + +To initialize direnv you need to add one line above that block and one line below it. + +```zsh +(( ${+commands[direnv]} )) && emulate zsh -c "$(direnv export zsh)" + +if [[ -r "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" ]]; then + source "${XDG_CACHE_HOME:-$HOME/.cache}/p10k-instant-prompt-${(%):-%n}.zsh" +fi + +(( ${+commands[direnv]} )) && emulate zsh -c "$(direnv hook zsh)" +``` + +*Related*: [How do I export GPG_TTY when using instant prompt?]( + #how-do-i-export-gpg_tty-when-using-instant-prompt) + +### How do I export GPG_TTY when using instant prompt? + +You can export `GPG_TTY` like this anywhere in `~/.zshrc`: + +```zsh +export GPG_TTY=$TTY +``` + +This works whether you are using [instant prompt](#instant-prompt) or not. It works even if you +aren't using powerlevel10k. As an extra bonus, it's much faster than the commonly used +`export GPG_TTY=$(tty)`. + +*Related*: [How do I initialize direnv when using instant prompt?]( + #how-do-i-initialize-direnv-when-using-instant-prompt) + +### What do different symbols in Git status mean? + +When using Lean, Classic or Rainbow style, Git status may look like this: + +```text +feature:master wip ⇣42⇡42 ⇠42⇢42 *42 merge ~42 +42 !42 ?42 +``` + +| Symbol | Meaning | Source | +| --------- | -------------------------------------------------------------------- | ------------------------------------------------------ | +| `feature` | current branch; replaced with `#tag` or `@commit` if not on a branch | `git status --ignore-submodules=dirty` | +| `master` | remote tracking branch; only shown if different from local branch | `git rev-parse --abbrev-ref --symbolic-full-name @{upstream}` | +| `wip` | the latest commit's summary contains "wip" or "WIP" | `git show --pretty=%s --no-patch HEAD` | +| `=` | up to date with the remote (neither ahead nor behind) | `git rev-list --count HEAD...@{upstream}` | +| `⇣42` | this many commits behind the remote | `git rev-list --right-only --count HEAD...@{upstream}` | +| `⇡42` | this many commits ahead of the remote | `git rev-list --left-only --count HEAD...@{upstream}` | +| `⇠42` | this many commits behind the push remote | `git rev-list --right-only --count HEAD...@{push}` | +| `⇢42` | this many commits ahead of the push remote | `git rev-list --left-only --count HEAD...@{push}` | +| `*42` | this many stashes | `git stash list` | +| `merge` | repository state | `git status --ignore-submodules=dirty` | +| `~42` | this many merge conflicts | `git status --ignore-submodules=dirty` | +| `+42` | this many staged changes | `git status --ignore-submodules=dirty` | +| `!42` | this many unstaged changes | `git status --ignore-submodules=dirty` | +| `?42` | this many untracked files | `git status --ignore-submodules=dirty` | +| `─` | the number of staged, unstaged or untracked files is unknown | `echo $POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY` or `git config --get bash.showDirtyState` | + +*Related*: [How do I change the format of Git status?](#how-do-i-change-the-format-of-git-status) + +### How do I change the format of Git status? + +To change the format of Git status, open `~/.p10k.zsh`, search for `my_git_formatter` and edit its +source code. + +*Related*: [What do different symbols in Git status mean?]( + #what-do-different-symbols-in-git-status-mean) + +### Why is Git status from `$HOME/.git` not displayed in prompt? + +When using Lean, Classic or Rainbow style, `~/.p10k.zsh` contains the following parameter: + +```zsh +# Don't show Git status in prompt for repositories whose workdir matches this pattern. +# For example, if set to '~', the Git repository at $HOME/.git will be ignored. +# Multiple patterns can be combined with '|': '~(|/foo)|/bar/baz/*'. +typeset -g POWERLEVEL9K_VCS_DISABLED_WORKDIR_PATTERN='~' +``` + +To see Git status for `$HOME/.git` in prompt, open `~/.p10k.zsh` and remove +`POWERLEVEL9K_VCS_DISABLED_WORKDIR_PATTERN`. + +### Why does Git status sometimes appear grey and then gets colored after a short period of time? + +tl;dr: When Git status in prompt is greyed out, it means Powerlevel10k is currently computing +up-to-date Git status in the background. Prompt will get automatically refreshed when this +computation completes. + +When your current directory is within a Git repository, Powerlevel10k computes up-to-date Git +status after every command. If the repository is large, or the machine is slow, this computation +can take quite a bit of time. If it takes longer than 10 milliseconds (configurable via +`POWERLEVEL9K_VCS_MAX_SYNC_LATENCY_SECONDS`), Powerlevel10k displays the last known Git status in +grey and continues to compute up-to-date Git status in the background. When the computation +completes, Powerlevel10k refreshes prompt with new information, this time with colored Git status. + +When using *Rainbow* style, Git status is displayed as black on grey while it's still being +computed. Depending on the terminal color palette, this may be difficult to read. In this case you +might want to change the background color to something lighter for more contrast. To do that, open +`~/.p10k.zsh`, search for `POWERLEVEL9K_VCS_LOADING_BACKGROUND`, uncomment it if it's commented out, +and change the value. + +```zsh +typeset -g POWERLEVEL9K_VCS_LOADING_BACKGROUND=244 +``` + +Type `source ~/.p10k.zsh` to apply your changes to the current Zsh session. + +*Related*: [How do I change prompt colors?](#how-do-i-change-prompt-colors) + +### How do I add username and/or hostname to prompt? + +When using Lean, Classic or Rainbow style, prompt shows `username@hostname` when you are logged in +as root or via SSH. There is little value in showing `username` or `hostname` when you are logged in +to your local machine as a normal user. So the absence of `username@hostname` in your prompt is an +indication that you are working locally and that you aren't root. You can change it, however. + +Open `~/.p10k.zsh`. Close to the top you can see the most important parameters that define which +segments are shown in your prompt. All generally useful prompt segments are listed in there. Some of +them are enabled, others are commented out. One of them is of interest to you. + +```zsh +typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=( + ... + context # user@hostname + ... +) +``` + +Search for `context` to find the section in the config that lists parameters specific to this prompt +segment. You should see the following lines: + +```zsh +# Don't show context unless running with privileges or in SSH. +# Tip: Remove the next line to always show context. +typeset -g POWERLEVEL9K_CONTEXT_{DEFAULT,SUDO}_{CONTENT,VISUAL_IDENTIFIER}_EXPANSION= +``` + +If you follow the tip and remove (or comment out) the last line, you'll always see +`username@hostname` in prompt. You can change the format to just `username`, or change the color, by +adjusting the values of parameters nearby. There are plenty of comments to help you navigate. + +You can also move `context` to a different position in `POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS` or even +to `POWERLEVEL9K_LEFT_PROMPT_ELEMENTS`. + +### Why some prompt segments appear and disappear as I'm typing? + +Prompt segments can be configured to be shown only when the current command you are typing invokes +a relevant tool. + +```zsh +# Show prompt segment "kubecontext" only when the command you are typing invokes +# invokes kubectl, helm, or kubens. +typeset -g POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND='kubectl|helm|kubens' +``` + +Configs created by `p10k configure` may contain parameters of this kind. To customize when different +prompt segments are shown, open `~/.p10k.zsh`, search for `SHOW_ON_COMMAND` and either remove these +parameters or change their values. + +You can also define a function in `~/.zshrc` to toggle the display of a prompt segment between +*always* and *on command*. This is similar to `kubeon`/`kubeoff` from +[kube-ps1](https://github.com/jonmosco/kube-ps1). + +```zsh +function kube-toggle() { + if (( ${+POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND} )); then + unset POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND + else + POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND='kubectl|helm|kubens' + fi + p10k reload + if zle; then + zle push-input + zle accept-line + fi +} +``` + +Invoke this function by typing `kube-toggle`. You can also bind it to a key by adding two more lines +to `~/.zshrc`: + +```zsh +zle -N kube-toggle +bindkey '^]' kube-toggle # ctrl-] to toggle kubecontext in powerlevel10k prompt +``` + +### How do I change prompt colors? + +You can either [change the color palette used by your terminal]( + #change-the-color-palette-used-by-your-terminal) or +[set colors through Powerlevel10k configuration parameters]( + #set-colors-through-Powerlevel10k-configuration-parameters). + +#### Change the color palette used by your terminal + +How exactly you change the terminal color palette (a.k.a. color scheme, or theme) depends on the +kind of terminal you are using. Look around in terminal's settings/preferences or consult +documentation. + +When you change the terminal color palette, it usually affects only the first 16 colors, numbered +from 0 to 15. In order to see any effect on Powerlevel10k prompt, you need to use prompt style that +utilizes these low-numbered colors. Type `p10k configure` and select *Rainbow*, *Lean* → *8 colors* +or *Pure* → *Original*. Other styles use higher-numbered colors, so they look the same in any +terminal color palette. + +#### Set colors through Powerlevel10k configuration parameters + +Open `~/.p10k.zsh`, search for "color", "foreground" and "background" and change values of +appropriate parameters. For example, here's how you can set the foreground of `time` prompt segment +to bright red: + +```zsh +typeset -g POWERLEVEL9K_TIME_FOREGROUND=160 +``` + +Colors are specified using numbers from 0 to 255. Colors from 0 to 15 look differently in different +terminals. Many terminals also support customization of these colors through color palettes +(a.k.a. color schemes, or themes). Colors from 16 to 255 always look the same. + +Type `source ~/.p10k.zsh` to apply your changes to the current Zsh session. + +To see how different colors look in your terminal, run the following command: + +```zsh +for i in {0..255}; do print -Pn "%K{$i} %k%F{$i}${(l:3::0:)i}%f " ${${(M)$((i%6)):#3}:+$'\n'}; done +``` + +*Related:* + - [Directory is difficult to see in prompt when using Rainbow style.]( + #directory-is-difficult-to-see-in-prompt-when-using-rainbow-style) + +### Why does Powerlevel10k spawn extra processes? + +Powerlevel10k uses [gitstatus](https://github.com/romkatv/gitstatus) as the backend behind `vcs` +prompt; gitstatus spawns `gitstatusd` and `zsh`. See +[gitstatus](https://github.com/romkatv/gitstatus) for details. Powerlevel10k may also spawn `zsh` +to perform computation without blocking prompt. To avoid security hazard, these background processes +aren't shared by different interactive shells. They terminate automatically when the parent `zsh` +process terminates or runs `exec(3)`. + +### Are there configuration options that make Powerlevel10k slow? + +No, Powerlevel10k is always fast, with any configuration you throw at it. If you have noticeable +prompt latency when using Powerlevel10k, please +[open an issue](https://github.com/romkatv/powerlevel10k/issues). + +### Is Powerlevel10k fast to load? + +Yes. See [zsh-bench](https://github.com/romkatv/zsh-bench). + +### What is the relationship between Powerlevel9k and Powerlevel10k? + +Powerlevel10k was forked from Powerlevel9k in March 2019 after a week-long discussion in +[powerlevel9k#1170](https://github.com/Powerlevel9k/powerlevel9k/issues/1170). Powerlevel9k was +already a mature project with a large user base and a release cycle measured in months. Powerlevel10k +was spun off to iterate on performance improvements and new features at much higher pace. + +Powerlevel9k and Powerlevel10k are independent projects. When using one, you shouldn't install the +other. Issues should be filed against the project that you actually use. There are no individuals +that have commit rights in both repositories. All bug fixes and new features committed to +Powerlevel9k repository get ported to Powerlevel10k. + +Over time, virtually all code in Powerlevel10k has been rewritten. There is currently no meaningful +overlap between the implementations of Powerlevel9k and Powerlevel10k. + +Powerlevel10k is committed to maintaining backward compatibility with all configs indefinitely. This +commitment covers all configuration parameters recognized by Powerlevel9k (see +[Powerlevel9k compatibility](#powerlevel9k-compatibility)) and additional parameters that only +Powerlevel10k understands. Names of all parameters in Powerlevel10k start with `POWERLEVEL9K_` for +consistency. + +### Does Powerlevel10k always render exactly the same prompt as Powerlevel9k given the same config? + +Almost. There are a few differences. + +- By default only `git` vcs backend is enabled in Powerlevel10k. If you need `svn` and `hg`, add + them to `POWERLEVEL9K_VCS_BACKENDS`. These backends aren't yet optimized in Powerlevel10k, so + enabling them will make prompt *very slow*. +- Powerlevel10k doesn't support `POWERLEVEL9K_VCS_SHOW_SUBMODULE_DIRTY=true`. +- Powerlevel10k strives to be bug-compatible with Powerlevel9k but not when it comes to egregious + bugs. If you accidentally rely on these bugs, your prompt will differ between Powerlevel9k and + Powerlevel10k. Some examples: + - Powerlevel9k ignores some options that are set after the theme is sourced while Powerlevel10k + respects all options. If you see different icons in Powerlevel9k and Powerlevel10k, you've + probably defined `POWERLEVEL9K_MODE` before sourcing the theme. This parameter gets ignored + by Powerlevel9k but honored by Powerlevel10k. If you want your prompt to look in Powerlevel10k + the same as in Powerlevel9k, remove `POWERLEVEL9K_MODE`. + - Powerlevel9k doesn't respect `ZLE_RPROMPT_INDENT`. As a result, right prompt in Powerlevel10k + can have an extra space at the end compared to Powerlevel9k. Set `ZLE_RPROMPT_INDENT=0` if you + don't want that space. More details in + [troubleshooting](#extra-space-without-background-on-the-right-side-of-right-prompt). + - Powerlevel9k has inconsistent spacing around icons. This was fixed in Powerlevel10k. Set + `POWERLEVEL9K_LEGACY_ICON_SPACING=true` to get the same spacing as in Powerlevel9k. More + details in [troubleshooting](#extra-or-missing-spaces-around-icons). + - There are dozens more bugs in Powerlevel9k that don't exist in Powerlevel10k. + +If you notice any other changes in prompt appearance when switching from Powerlevel9k to +Powerlevel10k, please [open an issue](https://github.com/romkatv/powerlevel10k/issues). + +### What is the best prompt style in the configuration wizard? + +There are as many opinions on what constitutes the best prompt as there are people. It mostly comes +down to personal preference. There are, however, a few hidden implications of different choices. + +Pure style is an exact replication of [Pure Zsh theme](https://github.com/sindresorhus/pure). It +exists to ease the migration for users of this theme. Unless you are one of them, choose Lean +style over Pure. + +If you want to confine prompt colors to the selected terminal color palette (say, *Solarized Dark*), +use *Rainbow*, *Lean* → *8 colors* or *Pure* → *Original*. Other styles use fixed colors and thus +look the same in any terminal color palette. + +All styles except Pure have an option to use *ASCII* charset. Prompt will look less pretty but will +render correctly with all fonts and in all locales. + +If you enable transient prompt, take advantage of two-line prompt. You'll get the benefit of +extra space for typing commands without the usual drawback of reduced scrollback density. Having +all commands start from the same offset is also nice. + +Similarly, if you enable transient prompt, sparse prompt (with an empty line before prompt) is a +great choice. + +If you are using vi keymap, choose prompt with `prompt_char` in it (shown as green `❯` in the +wizard). This symbol changes depending on vi mode: `❯`, `❮`, `V`, `▶` for insert, command, visual +and replace mode respectively. When a command fails, the symbol turns red. *Lean* style always has +`prompt_char` in it. *Rainbow* and *Classic* styles have it only in the two-line configuration +without left frame. + +If you value horizontal space or prefer minimalist aesthetics: + +- Use a monospace font, such as [the recommended font](#meslo-nerd-font-patched-for-powerlevel10k). + Non-monospace fonts require extra space after icons that are larger than a single column. +- Use Lean style. Compared to Classic and Rainbow, it saves two characters per prompt segment. +- Disable *current time* and *frame*. +- Use *few icons*. The extra icons enabled by the *many icons* option primarily serve decorative + function. Informative icons, such as background job indicator, will be shown either way. + +*Note*: You can run configuration wizard as many times as you like. Type `p10k configure` to try new +prompt style. + +### How to make Powerlevel10k look like robbyrussell Oh My Zsh theme? + +Use [this config]( + https://github.com/romkatv/powerlevel10k/blob/master/config/p10k-robbyrussell.zsh). + +You can either download it, save as `~/.p10k.zsh` and `source ~/.p10k.zsh` from `~/.zshrc`, or +source `p10k-robbyrussell.zsh` directly from your cloned `powerlevel10k` repository. + +### Can prompts for completed commands display error status for *those* commands instead of the commands preceding them? + +No. When you hit *ENTER* and the command you've typed starts running, its error status isn't yet +known, so it cannot be shown in prompt. When the command completes, the error status gets known but +it's no longer possible to update prompt for *that* command. This is why the error status for every +command is reflected in the *next* prompt. + +For details, see [this post on /r/zsh]( +https://www.reddit.com/r/zsh/comments/eg49ff/powerlevel10k_prompt_history_exit_code_colors/fc5huku). + +### What is the minimum supported Zsh version? + +Zsh 5.3 or newer should work. Fast startup requires Zsh >= 5.4. + +### How were these screenshots and animated gifs created? + +All screenshots and animated gifs were recorded in GNOME Terminal with +[the recommended font](#meslo-nerd-font-patched-for-powerlevel10k) and Tango Dark color palette with +custom background color (`#171A1B` instead of `#2E3436` -- twice as dark). + +![GNOME Terminal Color Settings]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/gnome-terminal-colors.png) + +Syntax highlighting, where present, was provided by [zsh-syntax-highlighting]( + https://github.com/zsh-users/zsh-syntax-highlighting). + +### How was the recommended font created? + +[The recommended font](#meslo-nerd-font-patched-for-powerlevel10k) is the product of many +individuals. Its origin is *Bitstream Vera Sans Mono*, which has given birth to *Menlo*, which in +turn has spawned *Meslo*. Finally, extra glyphs have been added to *Meslo* with scripts forked +from Nerd Fonts. The final font is released under the terms of +[Apache License]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/MesloLGS%20NF%20License.txt). + +MesloLGS NF font can be recreated with the following command (requires `git` and `docker`): + +```zsh +git clone --depth=1 https://github.com/romkatv/nerd-fonts.git +cd nerd-fonts +./build 'Meslo/S/*' +``` + +If everything goes well, four `ttf` files will appear in `./out`. + +### How to package Powerlevel10k for distribution? + +It's currently neither easy nor recommended to package and distribute Powerlevel10k. There are no +instructions you can follow that would allow you to easily update your package when new versions of +Powerlevel10k are released. This may change in the future but not soon. + +## Troubleshooting + +- [Question mark in prompt](#question-mark-in-prompt) +- [Icons, glyphs or powerline symbols don't render](#icons-glyphs-or-powerline-symbols-dont-render) +- [Sub-pixel imperfections around powerline symbols](#sub-pixel-imperfections-around-powerline-symbols) +- [Error: character not in range](#error-character-not-in-range) +- [Cursor is in the wrong place](#cursor-is-in-the-wrong-place) +- [Prompt wrapping around in a weird way](#prompt-wrapping-around-in-a-weird-way) +- [Right prompt is in the wrong place](#right-prompt-is-in-the-wrong-place) +- [Configuration wizard runs automatically every time Zsh is started](#configuration-wizard-runs-automatically-every-time-zsh-is-started) +- [Some prompt styles are missing from the configuration wizard](#some-prompt-styles-are-missing-from-the-configuration-wizard) +- [Cannot install the recommended font](#cannot-install-the-recommended-font) +- [Extra or missing spaces in prompt compared to Powerlevel9k](#extra-or-missing-spaces-in-prompt-compared-to-powerlevel9k) + - [Extra space without background on the right side of right prompt](#extra-space-without-background-on-the-right-side-of-right-prompt) + - [Extra or missing spaces around icons](#extra-or-missing-spaces-around-icons) +- [Weird things happen after typing `source ~/.zshrc`](#weird-things-happen-after-typing-source-zshrc) +- [Transient prompt stops working after some time](#transient-prompt-stops-working-after-some-time) +- [Cannot make Powerlevel10k work with my plugin manager](#cannot-make-powerlevel10k-work-with-my-plugin-manager) +- [Directory is difficult to see in prompt when using Rainbow style](#directory-is-difficult-to-see-in-prompt-when-using-rainbow-style) +- [Horrific mess when resizing terminal window](#horrific-mess-when-resizing-terminal-window) +- [Icons cut off in Konsole](#icons-cut-off-in-konsole) +- [Arch Linux logo has a dot in the bottom right corner](#arch-linux-logo-has-a-dot-in-the-bottom-right-corner) +- [Incorrect git status in prompt](#incorrect-git-status-in-prompt) + +### Question mark in prompt + +If it looks like a regular `?`, that's normal. It means you have untracked files in the current Git +repository. Type `git status` to see these files. You can change this symbol or disable the display +of untracked files altogether. Search for `untracked files` in `~/.p10k.zsh`. + +*FAQ*: [What do different symbols in Git status mean?]( + #what-do-different-symbols-in-git-status-mean) + +You can also get a weird-looking question mark in your prompt if your terminal's font is missing +some glyphs. See [icons, glyphs or powerline symbols don't render]( + #icons-glyphs-or-powerline-symbols-dont-render). + +### Icons, glyphs or powerline symbols don't render + +Restart your terminal, [install the recommended font](#meslo-nerd-font-patched-for-powerlevel10k) +and run `p10k configure`. + +### Sub-pixel imperfections around powerline symbols + +![Powerline Prompt Imperfections]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/powerline-imperfections.png) + +There are three imperfections on the screenshot. From left to right: + +1. A thin blue line (a sub-pixel gap) between the content of a prompt segment and the following +powerline connection. +1. Incorrect alignment of a powerline connection and the following prompt segment. The connection +appears shifted to the right. +1. A thin red line below a powerline connection. The connection appears shifted up. + +Zsh themes don't have down-to-pixel control over the terminal content. Everything you see on the +screen is made of monospace characters. A white powerline prompt segment is made of text on white +background followed by U+E0B0 (a right-pointing triangle). + +![Powerline Prompt Imperfections]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/powerline-anatomy.png) + +If Powerlevel10k prompt has imperfections around powerline symbols, you'll see exactly the same +imperfections with all powerline themes (Agnoster, Powerlevel9k, Powerline, etc.) + +There are several things you can try to deal with these imperfections: + +- Try [the recommended font](#meslo-nerd-font-patched-for-powerlevel10k). If you are already using + it, switching to another font may help but is unlikely. +- Change terminal font size one point up or down. For example, in iTerm2 powerline prompt looks + perfect at font sizes 11 and 13 but breaks down at 12. +- Enable builtin powerline glyphs in terminal settings if your terminal supports it (iTerm2 does). +- Change font hinting and/or anti-aliasing mode in the terminal settings. +- Shift all text one pixel up/down/left/right if your terminal has an option to do so. +- Try a different terminal. + +A more radical solution is to switch to prompt style without background. Type `p10k configure` and +select *Lean*. This style has a modern lightweight look. As a bonus, it doesn't suffer from +rendering imperfections that afflict powerline-style prompt. + +### Error: character not in range + +Type `echo '\u276F'`. If you get an error saying "zsh: character not in range", your locale +doesn't support UTF-8. You need to fix it. If you are running Zsh over SSH, see +[this](https://github.com/romkatv/powerlevel10k/issues/153#issuecomment-518347833). If you are +running Zsh locally, Google "set UTF-8 locale in *your OS*". + +### Cursor is in the wrong place + +Type `echo '\u276F'`. If you get an error saying "zsh: character not in range", see the +[previous section](#zsh-character-not-in-range). + +If the `echo` command prints `❯` but the cursor is still in the wrong place, install +[the recommended font](#meslo-nerd-font-patched-for-powerlevel10k) and run +`p10k configure`. + +If this doesn't help, add `unset ZLE_RPROMPT_INDENT` at the bottom of `~/.zshrc`. + +Still having issues? Run the following command to diagnose the problem: + +```zsh +() { + emulate -L zsh + setopt err_return no_unset + local text + print -rl -- 'Select a part of your prompt from the terminal window and paste it below.' '' + read -r '?Prompt: ' text + local -i len=${(m)#text} + local frame="+-${(pl.$len..-.):-}-+" + print -lr -- $frame "| $text |" $frame +} +``` + +#### If the prompt line aligns with the frame + +```text ++------------------------------+ +| romka@adam ✓ ~/powerlevel10k | ++------------------------------+ +``` + +If the output of the command is aligned for every part of your prompt (left and right), this +indicates a bug in the theme or your config. Use this command to diagnose it: + +```zsh +print -rl -- ${(eq+)PROMPT} ${(eq+)RPROMPT} +``` + +Look for `%{...%}` and backslash escapes in the output. If there are any, they are the likely +culprits. Open an issue if you get stuck. + +#### If the prompt line is longer than the frame + +```text ++-----------------------------+ +| romka@adam ✓ ~/powerlevel10k | ++-----------------------------+ +``` + +This is usually caused by a terminal bug or misconfiguration that makes it print ambiguous-width +characters as double-width instead of single width. For example, +[this issue](https://github.com/romkatv/powerlevel10k/issues/165). + +#### If the prompt line is shorter than the frame and is mangled + +```text ++------------------------------+ +| romka@adam ✓~/powerlevel10k | ++------------------------------+ +``` + +Note that this prompt is different from the original as it's missing a space after the check mark. + +This can be caused by a low-level bug in macOS. See +[this issue](https://github.com/romkatv/powerlevel10k/issues/241). + +This can also happen if prompt contains glyphs designated as "wide" in the Unicode standard and your +terminal incorrectly displays them as non-wide. Terminals suffering from this limitation include +Konsole, Hyper and the integrated VSCode Terminal. The solution is to use a different terminal or +remove all wide glyphs from prompt. + +#### If the prompt line is shorter than the frame and is not mangled + +```text ++--------------------------------+ +| romka@adam ✓ ~/powerlevel10k | ++--------------------------------+ +``` + +This can be caused by misconfigured locale. See +[this issue](https://github.com/romkatv/powerlevel10k/issues/251). + +### Prompt wrapping around in a weird way + +See [cursor is in the wrong place](#cursor-is-in-the-wrong-place). + +### Right prompt is in the wrong place + +See [cursor is in the wrong place](#cursor-is-in-the-wrong-place). + +### Configuration wizard runs automatically every time Zsh is started + +When Powerlevel10k starts, it automatically runs `p10k configure` if no `POWERLEVEL9K_*` +parameters are defined. Based on your prompt style choices, the configuration wizard creates +`~/.p10k.zsh` with a bunch of `POWERLEVEL9K_*` parameters in it and adds a line to `~/.zshrc` to +source this file. The next time you start Zsh, the configuration wizard shouldn't run automatically. +If it does, this means the evaluation of `~/.zshrc` terminates prematurely before it reaches the +line that sources `~/.p10k.zsh`. This most often happens due to syntax errors in `~/.zshrc`. These +errors get hidden by the configuration wizard screen, so you don't notice them. When you exit +configuration wizard, look for error messages. You can also use +`POWERLEVEL9K_DISABLE_CONFIGURATION_WIZARD=true zsh` to start Zsh without automatically running the +configuration wizard. Once you can see the errors, fix `~/.zshrc` to get rid of them. + +### Some prompt styles are missing from the configuration wizard + +If Zsh version is below 5.7.1 or `COLORTERM` environment variable is neither `24bit` nor +`truecolor`, configuration wizard won't offer Pure style with Snazzy color scheme. *Fix*: Install +Zsh >= 5.7.1 and use a terminal with truecolor support. Verify with `print -P '%F{#ff0000}red%f'`. + +If the terminal can display fewer than 256 colors, configuration wizard preselects Lean style with +8 colors. All other styles require at least 256 colors. *Fix*: Use a terminal with 256 color support +and make sure that `TERM` environment variable is set correctly. Verify with +`print $terminfo[colors]`. + +If there is no UTF-8 locale on the system, configuration wizard won't offer prompt styles that use +Unicode characters. *Fix*: Install a UTF-8 locale. Verify with `locale -a`. + +Another case in which configuration wizard may not offer Unicode prompt styles is when the +`MULTIBYTE` shell option is disabled. *Fix*: Enable the `MULTIBYTE` option, or rather don't disable +it (this option is enabled in Zsh by default). Verify with `print -r -- ${options[MULTIBYTE]}`. + +When `MULTIBYTE` is enabled and a UTF-8 locale is available, the first few questions asked by the +configuration wizard assess capabilities of the terminal font. If your answers indicate that some +glyphs don't render correctly, configuration wizard won't offer prompt styles that use them. *Fix*: +Restart your terminal and install +[the recommended font](#meslo-nerd-font-patched-for-powerlevel10k). Verify by running +`p10k configure` and checking that all glyphs render correctly. + +### Cannot install the recommended font + +Once you download [the recommended font](#meslo-nerd-font-patched-for-powerlevel10k), +you can install it just like any other font. Google "how to install fonts on *your OS*". + +### Extra or missing spaces in prompt compared to Powerlevel9k + +tl;dr: Add `ZLE_RPROMPT_INDENT=0` and `POWERLEVEL9K_LEGACY_ICON_SPACING=true` to `~/.zshrc` to get +the same prompt spacing as in Powerlevel9k. + +When using Powerlevel10k with a Powerlevel9k config, you might get additional spaces in prompt here +and there. These come in two flavors. + +#### Extra space without background on the right side of right prompt + +tl;dr: Add `ZLE_RPROMPT_INDENT=0` to `~/.zshrc` to get rid of that space. + +From [Zsh documentation]( + http://zsh.sourceforge.net/Doc/Release/Parameters.html#index-ZLE_005fRPROMPT_005fINDENT): + +> `ZLE_RPROMPT_INDENT ` +> +> If set, used to give the indentation between the right hand side of the right prompt in the line +> editor as given by `RPS1` or `RPROMPT` and the right hand side of the screen. If not set, the +> value `1` is used. +> +> Typically this will be used to set the value to `0` so that the prompt appears flush with the +> right hand side of the screen. + +Powerlevel10k respects this parameter. If you set `ZLE_RPROMPT_INDENT=1` (or leave it unset, which +is the same thing as setting it to `1`), you'll get an empty space to the right of right prompt. If +you set `ZLE_RPROMPT_INDENT=0`, your prompt will go to the edge of the terminal. This is how it +works in every theme except Powerlevel9k. + +![ZLE_RPROMPT_INDENT: Powerlevel10k vs Powerlevel9k]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/p9k-vs-p10k-zle-rprompt-indent.png) + +Powerlevel9k issue: [powerlevel9k#1292](https://github.com/Powerlevel9k/powerlevel9k/issues/1292). +It's been fixed in the development branch of Powerlevel9k but the fix hasn't yet made it to +`master`. + +Add `ZLE_RPROMPT_INDENT=0` to `~/.zshrc` to get the same spacing on the right edge of prompt as in +Powerlevel9k. + +*Note:* Several versions of Zsh have bugs that get triggered when you set `ZLE_RPROMPT_INDENT=0`. +Powerlevel10k can work around these bugs when using powerline prompt style. If you notice visual +artifacts in prompt, or wrong cursor position, try removing `ZLE_RPROMPT_INDENT` from `~/.zshrc`. + +#### Extra or missing spaces around icons + +tl;dr: Add `POWERLEVEL9K_LEGACY_ICON_SPACING=true` to `~/.zshrc` to get the same spacing around +icons as in Powerlevel9k. + +Spacing around icons in Powerlevel9k is inconsistent. + +![ZLE_RPROMPT_INDENT: Powerlevel10k vs Powerlevel9k]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/p9k-vs-p10k-icon-spacing.png) + +This inconsistency is a constant source of annoyance, so it was fixed in Powerlevel10k. You can add +`POWERLEVEL9K_LEGACY_ICON_SPACING=true` to `~/.zshrc` to get the same spacing around icons as in +Powerlevel9k. + +*Note:* It's not a good idea to define `POWERLEVEL9K_LEGACY_ICON_SPACING` when using +`p10k configure`. + +### Weird things happen after typing `source ~/.zshrc` + +It's almost always a bad idea to run `source ~/.zshrc`, whether you are using Powerlevel10k or not. +This command may result in random errors, misbehaving code and progressive slowdown of Zsh. + +If you've made changes to `~/.zshrc` or to files sourced by it, restart Zsh to apply them. The most +reliable way to do this is to type `exit` and then start a new Zsh session. You can also use +`exec zsh`. While not exactly equivalent to complete Zsh restart, this command is much more reliable +than `source ~/.zshrc`. + +### Transient prompt stops working after some time + +See [weird things happen after typing `source ~/.zshrc`]( + #weird-things-happen-after-typing-source-zshrc). + +### Cannot make Powerlevel10k work with my plugin manager + +If the [installation instructions](#installation) didn't work for you, try disabling your current +theme (so that you end up with no theme) and then installing Powerlevel10k manually. + +1. Disable the current theme in your framework / plugin manager. + +- **oh-my-zsh:** Open `~/.zshrc` and remove the line that sets `ZSH_THEME`. It might look like this: + `ZSH_THEME="powerlevel9k/powerlevel9k"`. +- **zplug:** Open `~/.zshrc` and remove the `zplug` command that refers to your current theme. For + example, if you are currently using Powerlevel9k, look for + `zplug bhilburn/powerlevel9k, use:powerlevel9k.zsh-theme`. +- **prezto:** Open `~/.zpreztorc` and put `zstyle :prezto:module:prompt theme off` in it. Remove + any other command that sets `theme` such as `zstyle :prezto:module:prompt theme powerlevel9k`. +- **antigen:** Open `~/.zshrc` and remove the line that sets `antigen theme`. It might look like + this: `antigen theme powerlevel9k/powerlevel9k`. + +2. Install Powerlevel10k manually. + +```zsh +git clone --depth=1 https://github.com/romkatv/powerlevel10k.git ~/powerlevel10k +echo 'source ~/powerlevel10k/powerlevel10k.zsh-theme' >>~/.zshrc +``` + +This method of installation won't make anything slower or otherwise sub-par. + +### Directory is difficult to see in prompt when using Rainbow style + +In Rainbow style the current working directory is shown with bright white text on blue background. +The white is fixed and always looks the same but the appearance of "blue" is defined by your +terminal color palette. If it's very light, it may be difficult to see white text on it. + +There are several ways to fix this. + +- Type `p10k configure` and choose a more readable prompt style. +- [Change terminal color palette](#change-the-color-palette-used-by-your-terminal). Try Tango Dark + or Solarized Dark, or change just the "blue" color. +- [Change directory background and/or foreground color](#set-colors-through-Powerlevel10k-configuration-parameters). + The parameters you are looking for are called `POWERLEVEL9K_DIR_BACKGROUND`, + `POWERLEVEL9K_DIR_FOREGROUND`, `POWERLEVEL9K_DIR_SHORTENED_FOREGROUND`, + `POWERLEVEL9K_DIR_ANCHOR_FOREGROUND` and `POWERLEVEL9K_DIR_ANCHOR_BOLD`. You can find them in + `~/.p10k.zsh`. + +### Horrific mess when resizing terminal window + +When you resize a terminal window horizontally back and forth a few times, you might see this ugly +picture. + +![Powerlevel10k Resizing Mess]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/resizing-mess.png) + +tl;dr: This issue arises when a terminal reflows Zsh prompt upon resizing. It isn't specific to +Powerlevel10k. See [mitigation](#mitigation). + +*Note: This section [used to say]( + https://github.com/romkatv/powerlevel10k/blob/dce00cdb5daaa8a519df234a7012ba3257b644d4/README.md#horrific-mess-when-resizing-terminal-window) +that the problem is caused by a bug in Zsh. While it's true that it's possible to avoid the problem +in many circumstances by modifying Zsh, it cannot be completely resolved this way. Thus it's unfair +to pin the blame on Zsh.* + +#### The anatomy of the problem + +The issue is manifested when the vertical distance between the start of the current prompt and the +cursor (henceforth `VD`) changes when the terminal window is resized. + +When a terminal window gets shrunk horizontally, there are two ways for a terminal to handle long +lines that no longer fit: *reflow* or *truncate*. + +Terminal content before shrinking: + +![Terminal Content Before Shrinking]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/resize-original.png) + +Terminal reflows text when shrinking: + +![Terminal Reflows Text When Shrinking]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/resize-reflow.png) + +Terminal truncates text when shrinking: + +![Terminal Truncates Text When Shrinking]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/resize-truncate.png) + +Reflowing strategy can change the height of terminal content. If such content happens to be between +the start of the current prompt and the cursor, Zsh will print prompt on the wrong line. Truncation +strategy never changes the height of terminal content, so it doesn't trigger this issue. + +Let's see how the issue plays out in slow motion. We'll start by launching `zsh -f` and pasting +the following code: + +```zsh +function pause() { read -s } +functions -M pause 0 + +reset +print -l {1..3} +setopt prompt_subst +PROMPT=$'${$((pause()))+}left>${(pl.$((COLUMNS-12))..-.)} ' +``` + +When `PROMPT` gets expanded, it calls `pause` to let us observe the state of the terminal. Here's +the initial state: + +![Terminal Resizing Bug 1]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/resize-bug-1.png) + +Zsh keeps track of the cursor position relative to the start of the current prompt. In this case it +knows that the cursor is one line below. When we shrink the terminal window, it looks like this: + +![Terminal Resizing Bug 2]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/resize-bug-2.png) + +At this point the terminal sends `SIGWINCH` to Zsh to notify it about changes in the terminal +dimensions. Note that this signal is sent *after* the content of the terminal has been reflown. + +When Zsh receives `SIGWINCH`, it attempts to erase the current prompt and print it anew. It goes to +the position where it *thinks* the current prompt is -- one line above the cursor (!) -- erases all +terminal content that follows and prints reexpanded prompt there. However, after resizing prompt is +no longer one line above the cursor. It's two lines above! Zsh ends up printing new prompt one line +too low. + +![Terminal Resizing Bug 3]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/resize-bug-3.png) + +In this case we ended up with unwanted junk content because `VD` has *increased*. When you make +terminal window wider, `VD` can also *decrease*, which would result in the new prompt being printed +higher than intended, potentially erasing useful content in the process. + +Here are a few more examples where shrinking terminal window increased `VD`. + +- Simple one-line left prompt with right prompt. No `prompt_subst`. Note that the cursor is below + the prompt line (hit *ESC-ENTER* to get it there). + ![Zsh Prompt That Breaks on Terminal Shrinking 1]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/resize-breakable-1.png) +- Simple one-line left prompt. No `prompt_subst`, no right prompt. Here `VD` is bound to increase + upon terminal shrinking due to the command line wrapping around. + ![Zsh Prompt That Breaks on Terminal Shrinking 2]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/resize-breakable-2.png) + +#### Zsh patch + +[This Zsh patch](https://github.com/romkatv/zsh/tree/fix-winchanged) fixes the issue on some +terminals. The idea behind the patch is to use `sc` (save cursor) terminal capability before +printing prompt and `rc` (restore cursor) to move cursor back to the original position when prompt +needs to be refreshed. + +The patch works only on terminals that reflow saved cursor position together with text when the +terminal window is resized. The patch has no observable effect on terminals that don't reflow text +on resize (both patched and unpatched Zsh behave correctly) and on terminals that reflow text but +not the saved cursor position (both patched and unpatched Zsh redraw prompt at the same incorrect +position). In other words, the patch fixes the resizing issue on some terminals while keeping the +behavior unchanged on others. + +There are two alternative approaches to patching Zsh that may seem to work at first glance but in +fact don't: + +- Instead of `sc`, use `u7` terminal capability to query the current cursor position and then `cup` + to go back to it. This doesn't work because the absolute position of the start of the current + prompt changes when text gets reflown. +- Recompute `VD` based on new terminal dimensions before attempting to refresh prompt. This doesn't + work because Zsh doesn't know whether terminal reflows text or truncates it. If Zsh could somehow + know that the terminal reflows text, this approach still wouldn't work on terminals that + continuously reflow text and rapid-fire `SIGWINCH` when the window is being resized. In such + environment real terminal dimensions go out of sync with what Zsh thinks the dimensions are. + +There is no ETA for the patch making its way into upstream Zsh. See [discussion]( + https://www.zsh.org/mla/workers//2019/msg00561.html). + +#### Mitigation + +There are a few mitigation options for this issue. + +- Use [kitty](https://sw.kovidgoyal.net/kitty/) terminal version >= 0.24.0 and enable terminal-shell + integration in Powerlevel10k by defining `POWERLEVEL9K_TERM_SHELL_INTEGRATION=true` in + `~/.p10k.zsh`. +- Apply [the patch](#zsh-patch) and [rebuild Zsh from source]( + https://github.com/zsh-users/zsh/blob/master/INSTALL). It won't help if you are using Alacritty, + kitty or some other terminal that reflows text on resize but doesn't reflow saved cursor position. + On such terminals the patch will have no visible effect. +- Disable text reflowing on window resize in terminal settings. If your terminal doesn't have this + setting, try a different terminal. +- Avoid long lines between the start of prompt and cursor. + 1. Disable ruler with `POWERLEVEL9K_SHOW_RULER=false`. + 2. Disable prompt connection with `POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' '`. + 3. Disable right frame with `POWERLEVEL9K_MULTILINE_FIRST_PROMPT_SUFFIX=''`, + `POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_SUFFIX=''` and + `POWERLEVEL9K_MULTILINE_LAST_PROMPT_SUFFIX=''`. + 4. Set `POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=()`. Right prompt on the last prompt line will cause + resizing issues only when the cursor is below it. This isn't very common, so you might want to + keep some elements in `POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS` provided that none of them are + succeeded by `newline`. + +### Icons cut off in Konsole + +When using Konsole with a non-monospace font, icons may be cut off on the right side. Here +"non-monospace" refers to any font with glyphs wider than a single column, or wider than two columns +for glyphs designated as "wide" in the Unicode standard. + +![Icons cut off in Konsole]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/konsole-non-monospace-font.png) + +The last line on the screenshot shows a cut off Arch Linux logo. + +There are several mitigation options for this issue. + +1. Use a different terminal. Konsole is the only terminal that exhibits this behavior. +2. Use a monospace font. +3. Manually add an extra space after the icon that gets cut off. For example, if the content of + `os_icon` prompt segment gets cut off, open `~/.p10k.zsh`, search for + `POWERLEVEL9K_OS_ICON_CONTENT_EXPANSION` and change it as follows: +```zsh +typeset -g POWERLEVEL9K_OS_ICON_CONTENT_EXPANSION='${P9K_CONTENT} ' # extra space at the end +``` +4. Use a different icon that is monospace. For example, if Arch Linux logo gets cut off, add + the following parameter to `~/.p10k.zsh`: +```zsh +typeset -g POWERLEVEL9K_LINUX_ARCH_ICON='Arch' # plain "Arch" in place of a logo +``` +5. Disable the display of the icon that gets cut off. For example, if the content of + `os_icon` prompt segment gets cut off, open `~/.p10k.zsh` and remove `os_icon` from + `POWERLEVEL9K_LEFT_PROMPT_ELEMENTS` and `POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS`. + +*Note*: [Non-monospace fonts are not officially supported by Konsole]( + https://bugs.kde.org/show_bug.cgi?id=418553#c5). + +### Arch Linux logo has a dot in the bottom right corner + +![Arch Linux Logo with a dot]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/arch-linux-logo-dot.png) + +Some fonts have this incorrect dotted icon in bold typeface. There are two ways to fix this issue. + +1. Use a font with a correct Arch Linux logo in bold typeface. For example, + [the recommended Powerlevel10k font](#meslo-nerd-font-patched-for-powerlevel10k). +2. Display the icon in regular (non-bold) typeface. To do this, open `~/.p10k.zsh`, search for + `POWERLEVEL9K_OS_ICON_CONTENT_EXPANSION` and remove `%B` from its value. +```zsh +typeset -g POWERLEVEL9K_OS_ICON_CONTENT_EXPANSION='${P9K_CONTENT}' # not bold +``` + +### Incorrect git status in prompt + +Powerlevel10k uses [gitstatusd](https://github.com/romkatv/gitstatus) to inspect the state of git +repositories. The project relies on the [libgit2](https://github.com/libgit2/libgit2) library, which +has some gaps in its implementation. Under some conditions, this may result in discrepancies between +the real state of a git repository (reflected by `git status`) and what gets shown in the +Powerlevel10k prompt. + +Most notably, [libgit2 does not support `skipHash`](https://github.com/libgit2/libgit2/issues/6531). +If you see incorrect git status in prompt, run `git config -l` and check whether `skipHash` is +enabled. If it is, consider disabling it. Keep in mind that `skipHash` may be implicitly enabled +when activating certain git features, such as `manyFiles`. diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-classic.zsh b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-classic.zsh new file mode 100644 index 00000000..5ea8faec --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-classic.zsh @@ -0,0 +1,1731 @@ +# Config for Powerlevel10k with classic powerline prompt style. Type `p10k configure` to generate +# your own config based on it. +# +# Tip: Looking for a nice color? Here's a one-liner to print colormap. +# +# for i in {0..255}; do print -Pn "%K{$i} %k%F{$i}${(l:3::0:)i}%f " ${${(M)$((i%6)):#3}:+$'\n'}; done + +# Temporarily change options. +'builtin' 'local' '-a' 'p10k_config_opts' +[[ ! -o 'aliases' ]] || p10k_config_opts+=('aliases') +[[ ! -o 'sh_glob' ]] || p10k_config_opts+=('sh_glob') +[[ ! -o 'no_brace_expand' ]] || p10k_config_opts+=('no_brace_expand') +'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand' + +() { + emulate -L zsh -o extended_glob + + # Unset all configuration options. This allows you to apply configuration changes without + # restarting zsh. Edit ~/.p10k.zsh and type `source ~/.p10k.zsh`. + unset -m '(POWERLEVEL9K_*|DEFAULT_USER)~POWERLEVEL9K_GITSTATUS_DIR' + + # Zsh >= 5.1 is required. + [[ $ZSH_VERSION == (5.<1->*|<6->.*) ]] || return + + # The list of segments shown on the left. Fill it with the most important segments. + typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=( + # =========================[ Line #1 ]========================= + # os_icon # os identifier + dir # current directory + vcs # git status + # =========================[ Line #2 ]========================= + newline # \n + # prompt_char # prompt symbol + ) + + # The list of segments shown on the right. Fill it with less important segments. + # Right prompt on the last prompt line (where you are typing your commands) gets + # automatically hidden when the input line reaches it. Right prompt above the + # last prompt line gets hidden if it would overlap with left prompt. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=( + # =========================[ Line #1 ]========================= + status # exit code of the last command + command_execution_time # duration of the last command + background_jobs # presence of background jobs + direnv # direnv status (https://direnv.net/) + asdf # asdf version manager (https://github.com/asdf-vm/asdf) + virtualenv # python virtual environment (https://docs.python.org/3/library/venv.html) + anaconda # conda environment (https://conda.io/) + pyenv # python environment (https://github.com/pyenv/pyenv) + goenv # go environment (https://github.com/syndbg/goenv) + nodenv # node.js version from nodenv (https://github.com/nodenv/nodenv) + nvm # node.js version from nvm (https://github.com/nvm-sh/nvm) + nodeenv # node.js environment (https://github.com/ekalinin/nodeenv) + # node_version # node.js version + # go_version # go version (https://golang.org) + # rust_version # rustc version (https://www.rust-lang.org) + # dotnet_version # .NET version (https://dotnet.microsoft.com) + # php_version # php version (https://www.php.net/) + # laravel_version # laravel php framework version (https://laravel.com/) + # java_version # java version (https://www.java.com/) + # package # name@version from package.json (https://docs.npmjs.com/files/package.json) + rbenv # ruby version from rbenv (https://github.com/rbenv/rbenv) + rvm # ruby version from rvm (https://rvm.io) + fvm # flutter version management (https://github.com/leoafarias/fvm) + luaenv # lua version from luaenv (https://github.com/cehoffman/luaenv) + jenv # java version from jenv (https://github.com/jenv/jenv) + plenv # perl version from plenv (https://github.com/tokuhirom/plenv) + perlbrew # perl version from perlbrew (https://github.com/gugod/App-perlbrew) + phpenv # php version from phpenv (https://github.com/phpenv/phpenv) + scalaenv # scala version from scalaenv (https://github.com/scalaenv/scalaenv) + haskell_stack # haskell version from stack (https://haskellstack.org/) + kubecontext # current kubernetes context (https://kubernetes.io/) + terraform # terraform workspace (https://www.terraform.io) + # terraform_version # terraform version (https://www.terraform.io) + aws # aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) + aws_eb_env # aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) + azure # azure account name (https://docs.microsoft.com/en-us/cli/azure) + gcloud # google cloud cli account and project (https://cloud.google.com/) + google_app_cred # google application credentials (https://cloud.google.com/docs/authentication/production) + toolbox # toolbox name (https://github.com/containers/toolbox) + context # user@hostname + nordvpn # nordvpn connection status, linux only (https://nordvpn.com/) + ranger # ranger shell (https://github.com/ranger/ranger) + nnn # nnn shell (https://github.com/jarun/nnn) + lf # lf shell (https://github.com/gokcehan/lf) + xplr # xplr shell (https://github.com/sayanarijit/xplr) + vim_shell # vim shell indicator (:sh) + midnight_commander # midnight commander shell (https://midnight-commander.org/) + nix_shell # nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) + chezmoi_shell # chezmoi shell (https://www.chezmoi.io/) + # vi_mode # vi mode (you don't need this if you've enabled prompt_char) + # vpn_ip # virtual private network indicator + # load # CPU load + # disk_usage # disk usage + # ram # free RAM + # swap # used swap + todo # todo items (https://github.com/todotxt/todo.txt-cli) + timewarrior # timewarrior tracking status (https://timewarrior.net/) + taskwarrior # taskwarrior task count (https://taskwarrior.org/) + per_directory_history # Oh My Zsh per-directory-history local/global indicator + # cpu_arch # CPU architecture + # time # current time + # =========================[ Line #2 ]========================= + newline # \n + # ip # ip address and bandwidth usage for a specified network interface + # public_ip # public IP address + # proxy # system-wide http/https/ftp proxy + # battery # internal battery + # wifi # wifi speed + # example # example user-defined segment (see prompt_example function below) + ) + + # Defines character set used by powerlevel10k. It's best to let `p10k configure` set it for you. + typeset -g POWERLEVEL9K_MODE=nerdfont-complete + # When set to `moderate`, some icons will have an extra space after them. This is meant to avoid + # icon overlap when using non-monospace fonts. When set to `none`, spaces are not added. + typeset -g POWERLEVEL9K_ICON_PADDING=none + + # When set to true, icons appear before content on both sides of the prompt. When set + # to false, icons go after content. If empty or not set, icons go before content in the left + # prompt and after content in the right prompt. + # + # You can also override it for a specific segment: + # + # POWERLEVEL9K_STATUS_ICON_BEFORE_CONTENT=false + # + # Or for a specific segment in specific state: + # + # POWERLEVEL9K_DIR_NOT_WRITABLE_ICON_BEFORE_CONTENT=false + typeset -g POWERLEVEL9K_ICON_BEFORE_CONTENT= + + # Add an empty line before each prompt. + typeset -g POWERLEVEL9K_PROMPT_ADD_NEWLINE=true + + # Connect left prompt lines with these symbols. You'll probably want to use the same color + # as POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_FOREGROUND below. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_PREFIX='%242F╭─' + typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_PREFIX='%242F├─' + typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX='%242F╰─' + # Connect right prompt lines with these symbols. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_SUFFIX='%242F─╮' + typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_SUFFIX='%242F─┤' + typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_SUFFIX='%242F─╯' + + # Filler between left and right prompt on the first prompt line. You can set it to ' ', '·' or + # '─'. The last two make it easier to see the alignment between left and right prompt and to + # separate prompt from command output. You might want to set POWERLEVEL9K_PROMPT_ADD_NEWLINE=false + # for more compact prompt if using this option. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' ' + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_BACKGROUND= + typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_GAP_BACKGROUND= + if [[ $POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR != ' ' ]]; then + # The color of the filler. You'll probably want to match the color of POWERLEVEL9K_MULTILINE + # ornaments defined above. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_FOREGROUND=242 + # Start filler from the edge of the screen if there are no left segments on the first line. + typeset -g POWERLEVEL9K_EMPTY_LINE_LEFT_PROMPT_FIRST_SEGMENT_END_SYMBOL='%{%}' + # End filler on the edge of the screen if there are no right segments on the first line. + typeset -g POWERLEVEL9K_EMPTY_LINE_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL='%{%}' + fi + + # Default background color. + typeset -g POWERLEVEL9K_BACKGROUND=238 + + # Separator between same-color segments on the left. + typeset -g POWERLEVEL9K_LEFT_SUBSEGMENT_SEPARATOR='%246F\uE0B1' + # Separator between same-color segments on the right. + typeset -g POWERLEVEL9K_RIGHT_SUBSEGMENT_SEPARATOR='%246F\uE0B3' + # Separator between different-color segments on the left. + typeset -g POWERLEVEL9K_LEFT_SEGMENT_SEPARATOR='\uE0B0' + # Separator between different-color segments on the right. + typeset -g POWERLEVEL9K_RIGHT_SEGMENT_SEPARATOR='\uE0B2' + # To remove a separator between two segments, add "_joined" to the second segment name. + # For example: POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(os_icon context_joined) + + # The right end of left prompt. + typeset -g POWERLEVEL9K_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL='\uE0B0' + # The left end of right prompt. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL='\uE0B2' + # The left end of left prompt. + typeset -g POWERLEVEL9K_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL= + # The right end of right prompt. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_LAST_SEGMENT_END_SYMBOL= + # Left prompt terminator for lines without any segments. + typeset -g POWERLEVEL9K_EMPTY_LINE_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL= + + #################################[ os_icon: os identifier ]################################## + # OS identifier color. + typeset -g POWERLEVEL9K_OS_ICON_FOREGROUND=255 + # Custom icon. + # typeset -g POWERLEVEL9K_OS_ICON_CONTENT_EXPANSION='⭐' + + ################################[ prompt_char: prompt symbol ]################################ + # Transparent background. + typeset -g POWERLEVEL9K_PROMPT_CHAR_BACKGROUND= + # Green prompt symbol if the last command succeeded. + typeset -g POWERLEVEL9K_PROMPT_CHAR_OK_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=76 + # Red prompt symbol if the last command failed. + typeset -g POWERLEVEL9K_PROMPT_CHAR_ERROR_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=196 + # Default prompt symbol. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION='❯' + # Prompt symbol in command vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VICMD_CONTENT_EXPANSION='❮' + # Prompt symbol in visual vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIVIS_CONTENT_EXPANSION='V' + # Prompt symbol in overwrite vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIOWR_CONTENT_EXPANSION='▶' + typeset -g POWERLEVEL9K_PROMPT_CHAR_OVERWRITE_STATE=true + # No line terminator if prompt_char is the last segment. + typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL= + # No line introducer if prompt_char is the first segment. + typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL= + # No surrounding whitespace. + typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_{LEFT,RIGHT}_WHITESPACE= + + ##################################[ dir: current directory ]################################## + # Default current directory color. + typeset -g POWERLEVEL9K_DIR_FOREGROUND=31 + # If directory is too long, shorten some of its segments to the shortest possible unique + # prefix. The shortened directory can be tab-completed to the original. + typeset -g POWERLEVEL9K_SHORTEN_STRATEGY=truncate_to_unique + # Replace removed segment suffixes with this symbol. + typeset -g POWERLEVEL9K_SHORTEN_DELIMITER= + # Color of the shortened directory segments. + typeset -g POWERLEVEL9K_DIR_SHORTENED_FOREGROUND=103 + # Color of the anchor directory segments. Anchor segments are never shortened. The first + # segment is always an anchor. + typeset -g POWERLEVEL9K_DIR_ANCHOR_FOREGROUND=39 + # Display anchor directory segments in bold. + typeset -g POWERLEVEL9K_DIR_ANCHOR_BOLD=true + # Don't shorten directories that contain any of these files. They are anchors. + local anchor_files=( + .bzr + .citc + .git + .hg + .node-version + .python-version + .go-version + .ruby-version + .lua-version + .java-version + .perl-version + .php-version + .tool-versions + .shorten_folder_marker + .svn + .terraform + CVS + Cargo.toml + composer.json + go.mod + package.json + stack.yaml + ) + typeset -g POWERLEVEL9K_SHORTEN_FOLDER_MARKER="(${(j:|:)anchor_files})" + # If set to "first" ("last"), remove everything before the first (last) subdirectory that contains + # files matching $POWERLEVEL9K_SHORTEN_FOLDER_MARKER. For example, when the current directory is + # /foo/bar/git_repo/nested_git_repo/baz, prompt will display git_repo/nested_git_repo/baz (first) + # or nested_git_repo/baz (last). This assumes that git_repo and nested_git_repo contain markers + # and other directories don't. + # + # Optionally, "first" and "last" can be followed by ":" where is an integer. + # This moves the truncation point to the right (positive offset) or to the left (negative offset) + # relative to the marker. Plain "first" and "last" are equivalent to "first:0" and "last:0" + # respectively. + typeset -g POWERLEVEL9K_DIR_TRUNCATE_BEFORE_MARKER=false + # Don't shorten this many last directory segments. They are anchors. + typeset -g POWERLEVEL9K_SHORTEN_DIR_LENGTH=1 + # Shorten directory if it's longer than this even if there is space for it. The value can + # be either absolute (e.g., '80') or a percentage of terminal width (e.g, '50%'). If empty, + # directory will be shortened only when prompt doesn't fit or when other parameters demand it + # (see POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS and POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT below). + # If set to `0`, directory will always be shortened to its minimum length. + typeset -g POWERLEVEL9K_DIR_MAX_LENGTH=80 + # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least this + # many columns for typing commands. + typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS=40 + # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least + # COLUMNS * POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT * 0.01 columns for typing commands. + typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT=50 + # If set to true, embed a hyperlink into the directory. Useful for quickly + # opening a directory in the file manager simply by clicking the link. + # Can also be handy when the directory is shortened, as it allows you to see + # the full directory that was used in previous commands. + typeset -g POWERLEVEL9K_DIR_HYPERLINK=false + + # Enable special styling for non-writable and non-existent directories. See POWERLEVEL9K_LOCK_ICON + # and POWERLEVEL9K_DIR_CLASSES below. + typeset -g POWERLEVEL9K_DIR_SHOW_WRITABLE=v3 + + # The default icon shown next to non-writable and non-existent directories when + # POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3. + # typeset -g POWERLEVEL9K_LOCK_ICON='⭐' + + # POWERLEVEL9K_DIR_CLASSES allows you to specify custom icons and colors for different + # directories. It must be an array with 3 * N elements. Each triplet consists of: + # + # 1. A pattern against which the current directory ($PWD) is matched. Matching is done with + # extended_glob option enabled. + # 2. Directory class for the purpose of styling. + # 3. An empty string. + # + # Triplets are tried in order. The first triplet whose pattern matches $PWD wins. + # + # If POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3, non-writable and non-existent directories + # acquire class suffix _NOT_WRITABLE and NON_EXISTENT respectively. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_DIR_CLASSES=( + # '~/work(|/*)' WORK '' + # '~(|/*)' HOME '' + # '*' DEFAULT '') + # + # Whenever the current directory is ~/work or a subdirectory of ~/work, it gets styled with one + # of the following classes depending on its writability and existence: WORK, WORK_NOT_WRITABLE or + # WORK_NON_EXISTENT. + # + # Simply assigning classes to directories doesn't have any visible effects. It merely gives you an + # option to define custom colors and icons for different directory classes. + # + # # Styling for WORK. + # typeset -g POWERLEVEL9K_DIR_WORK_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_DIR_WORK_FOREGROUND=31 + # typeset -g POWERLEVEL9K_DIR_WORK_SHORTENED_FOREGROUND=103 + # typeset -g POWERLEVEL9K_DIR_WORK_ANCHOR_FOREGROUND=39 + # + # # Styling for WORK_NOT_WRITABLE. + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND=31 + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_SHORTENED_FOREGROUND=103 + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_ANCHOR_FOREGROUND=39 + # + # # Styling for WORK_NON_EXISTENT. + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_FOREGROUND=31 + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_SHORTENED_FOREGROUND=103 + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_ANCHOR_FOREGROUND=39 + # + # If a styling parameter isn't explicitly defined for some class, it falls back to the classless + # parameter. For example, if POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND is not set, it falls + # back to POWERLEVEL9K_DIR_FOREGROUND. + # + # typeset -g POWERLEVEL9K_DIR_CLASSES=() + + # Custom prefix. + # typeset -g POWERLEVEL9K_DIR_PREFIX='%248Fin ' + + #####################################[ vcs: git status ]###################################### + # Branch icon. Set this parameter to '\UE0A0 ' for the popular Powerline branch icon. + typeset -g POWERLEVEL9K_VCS_BRANCH_ICON= + + # Untracked files icon. It's really a question mark, your font isn't broken. + # Change the value of this parameter to show a different icon. + typeset -g POWERLEVEL9K_VCS_UNTRACKED_ICON='?' + + # Formatter for Git status. + # + # Example output: master wip ⇣42⇡42 *42 merge ~42 +42 !42 ?42. + # + # You can edit the function to customize how Git status looks. + # + # VCS_STATUS_* parameters are set by gitstatus plugin. See reference: + # https://github.com/romkatv/gitstatus/blob/master/gitstatus.plugin.zsh. + function my_git_formatter() { + emulate -L zsh + + if [[ -n $P9K_CONTENT ]]; then + # If P9K_CONTENT is not empty, use it. It's either "loading" or from vcs_info (not from + # gitstatus plugin). VCS_STATUS_* parameters are not available in this case. + typeset -g my_git_format=$P9K_CONTENT + return + fi + + if (( $1 )); then + # Styling for up-to-date Git status. + local meta='%248F' # grey foreground + local clean='%76F' # green foreground + local modified='%178F' # yellow foreground + local untracked='%39F' # blue foreground + local conflicted='%196F' # red foreground + else + # Styling for incomplete and stale Git status. + local meta='%244F' # grey foreground + local clean='%244F' # grey foreground + local modified='%244F' # grey foreground + local untracked='%244F' # grey foreground + local conflicted='%244F' # grey foreground + fi + + local res + + if [[ -n $VCS_STATUS_LOCAL_BRANCH ]]; then + local branch=${(V)VCS_STATUS_LOCAL_BRANCH} + # If local branch name is at most 32 characters long, show it in full. + # Otherwise show the first 12 … the last 12. + # Tip: To always show local branch name in full without truncation, delete the next line. + (( $#branch > 32 )) && branch[13,-13]="…" # <-- this line + res+="${clean}${(g::)POWERLEVEL9K_VCS_BRANCH_ICON}${branch//\%/%%}" + fi + + if [[ -n $VCS_STATUS_TAG + # Show tag only if not on a branch. + # Tip: To always show tag, delete the next line. + && -z $VCS_STATUS_LOCAL_BRANCH # <-- this line + ]]; then + local tag=${(V)VCS_STATUS_TAG} + # If tag name is at most 32 characters long, show it in full. + # Otherwise show the first 12 … the last 12. + # Tip: To always show tag name in full without truncation, delete the next line. + (( $#tag > 32 )) && tag[13,-13]="…" # <-- this line + res+="${meta}#${clean}${tag//\%/%%}" + fi + + # Display the current Git commit if there is no branch and no tag. + # Tip: To always display the current Git commit, delete the next line. + [[ -z $VCS_STATUS_LOCAL_BRANCH && -z $VCS_STATUS_TAG ]] && # <-- this line + res+="${meta}@${clean}${VCS_STATUS_COMMIT[1,8]}" + + # Show tracking branch name if it differs from local branch. + if [[ -n ${VCS_STATUS_REMOTE_BRANCH:#$VCS_STATUS_LOCAL_BRANCH} ]]; then + res+="${meta}:${clean}${(V)VCS_STATUS_REMOTE_BRANCH//\%/%%}" + fi + + # Display "wip" if the latest commit's summary contains "wip" or "WIP". + if [[ $VCS_STATUS_COMMIT_SUMMARY == (|*[^[:alnum:]])(wip|WIP)(|[^[:alnum:]]*) ]]; then + res+=" ${modified}wip" + fi + + if (( VCS_STATUS_COMMITS_AHEAD || VCS_STATUS_COMMITS_BEHIND )); then + # ⇣42 if behind the remote. + (( VCS_STATUS_COMMITS_BEHIND )) && res+=" ${clean}⇣${VCS_STATUS_COMMITS_BEHIND}" + # ⇡42 if ahead of the remote; no leading space if also behind the remote: ⇣42⇡42. + (( VCS_STATUS_COMMITS_AHEAD && !VCS_STATUS_COMMITS_BEHIND )) && res+=" " + (( VCS_STATUS_COMMITS_AHEAD )) && res+="${clean}⇡${VCS_STATUS_COMMITS_AHEAD}" + elif [[ -n $VCS_STATUS_REMOTE_BRANCH ]]; then + # Tip: Uncomment the next line to display '=' if up to date with the remote. + # res+=" ${clean}=" + fi + + # ⇠42 if behind the push remote. + (( VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=" ${clean}⇠${VCS_STATUS_PUSH_COMMITS_BEHIND}" + (( VCS_STATUS_PUSH_COMMITS_AHEAD && !VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=" " + # ⇢42 if ahead of the push remote; no leading space if also behind: ⇠42⇢42. + (( VCS_STATUS_PUSH_COMMITS_AHEAD )) && res+="${clean}⇢${VCS_STATUS_PUSH_COMMITS_AHEAD}" + # *42 if have stashes. + (( VCS_STATUS_STASHES )) && res+=" ${clean}*${VCS_STATUS_STASHES}" + # 'merge' if the repo is in an unusual state. + [[ -n $VCS_STATUS_ACTION ]] && res+=" ${conflicted}${VCS_STATUS_ACTION}" + # ~42 if have merge conflicts. + (( VCS_STATUS_NUM_CONFLICTED )) && res+=" ${conflicted}~${VCS_STATUS_NUM_CONFLICTED}" + # +42 if have staged changes. + (( VCS_STATUS_NUM_STAGED )) && res+=" ${modified}+${VCS_STATUS_NUM_STAGED}" + # !42 if have unstaged changes. + (( VCS_STATUS_NUM_UNSTAGED )) && res+=" ${modified}!${VCS_STATUS_NUM_UNSTAGED}" + # ?42 if have untracked files. It's really a question mark, your font isn't broken. + # See POWERLEVEL9K_VCS_UNTRACKED_ICON above if you want to use a different icon. + # Remove the next line if you don't want to see untracked files at all. + (( VCS_STATUS_NUM_UNTRACKED )) && res+=" ${untracked}${(g::)POWERLEVEL9K_VCS_UNTRACKED_ICON}${VCS_STATUS_NUM_UNTRACKED}" + # "─" if the number of unstaged files is unknown. This can happen due to + # POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY (see below) being set to a non-negative number lower + # than the number of files in the Git index, or due to bash.showDirtyState being set to false + # in the repository config. The number of staged and untracked files may also be unknown + # in this case. + (( VCS_STATUS_HAS_UNSTAGED == -1 )) && res+=" ${modified}─" + + typeset -g my_git_format=$res + } + functions -M my_git_formatter 2>/dev/null + + # Don't count the number of unstaged, untracked and conflicted files in Git repositories with + # more than this many files in the index. Negative value means infinity. + # + # If you are working in Git repositories with tens of millions of files and seeing performance + # sagging, try setting POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY to a number lower than the output + # of `git ls-files | wc -l`. Alternatively, add `bash.showDirtyState = false` to the repository's + # config: `git config bash.showDirtyState false`. + typeset -g POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY=-1 + + # Don't show Git status in prompt for repositories whose workdir matches this pattern. + # For example, if set to '~', the Git repository at $HOME/.git will be ignored. + # Multiple patterns can be combined with '|': '~(|/foo)|/bar/baz/*'. + typeset -g POWERLEVEL9K_VCS_DISABLED_WORKDIR_PATTERN='~' + + # Disable the default Git status formatting. + typeset -g POWERLEVEL9K_VCS_DISABLE_GITSTATUS_FORMATTING=true + # Install our own Git status formatter. + typeset -g POWERLEVEL9K_VCS_CONTENT_EXPANSION='${$((my_git_formatter(1)))+${my_git_format}}' + typeset -g POWERLEVEL9K_VCS_LOADING_CONTENT_EXPANSION='${$((my_git_formatter(0)))+${my_git_format}}' + # Enable counters for staged, unstaged, etc. + typeset -g POWERLEVEL9K_VCS_{STAGED,UNSTAGED,UNTRACKED,CONFLICTED,COMMITS_AHEAD,COMMITS_BEHIND}_MAX_NUM=-1 + + # Icon color. + typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_COLOR=76 + typeset -g POWERLEVEL9K_VCS_LOADING_VISUAL_IDENTIFIER_COLOR=244 + # Custom icon. + # typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_VCS_PREFIX='%248Fon ' + + # Show status of repositories of these types. You can add svn and/or hg if you are + # using them. If you do, your prompt may become slow even when your current directory + # isn't in an svn or hg reposotiry. + typeset -g POWERLEVEL9K_VCS_BACKENDS=(git) + + # These settings are used for repositories other than Git or when gitstatusd fails and + # Powerlevel10k has to fall back to using vcs_info. + typeset -g POWERLEVEL9K_VCS_CLEAN_FOREGROUND=76 + typeset -g POWERLEVEL9K_VCS_UNTRACKED_FOREGROUND=76 + typeset -g POWERLEVEL9K_VCS_MODIFIED_FOREGROUND=178 + + ##########################[ status: exit code of the last command ]########################### + # Enable OK_PIPE, ERROR_PIPE and ERROR_SIGNAL status states to allow us to enable, disable and + # style them independently from the regular OK and ERROR state. + typeset -g POWERLEVEL9K_STATUS_EXTENDED_STATES=true + + # Status on success. No content, just an icon. No need to show it if prompt_char is enabled as + # it will signify success by turning green. + typeset -g POWERLEVEL9K_STATUS_OK=true + typeset -g POWERLEVEL9K_STATUS_OK_FOREGROUND=70 + typeset -g POWERLEVEL9K_STATUS_OK_VISUAL_IDENTIFIER_EXPANSION='✔' + + # Status when some part of a pipe command fails but the overall exit status is zero. It may look + # like this: 1|0. + typeset -g POWERLEVEL9K_STATUS_OK_PIPE=true + typeset -g POWERLEVEL9K_STATUS_OK_PIPE_FOREGROUND=70 + typeset -g POWERLEVEL9K_STATUS_OK_PIPE_VISUAL_IDENTIFIER_EXPANSION='✔' + + # Status when it's just an error code (e.g., '1'). No need to show it if prompt_char is enabled as + # it will signify error by turning red. + typeset -g POWERLEVEL9K_STATUS_ERROR=true + typeset -g POWERLEVEL9K_STATUS_ERROR_FOREGROUND=160 + typeset -g POWERLEVEL9K_STATUS_ERROR_VISUAL_IDENTIFIER_EXPANSION='✘' + + # Status when the last command was terminated by a signal. + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL=true + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_FOREGROUND=160 + # Use terse signal names: "INT" instead of "SIGINT(2)". + typeset -g POWERLEVEL9K_STATUS_VERBOSE_SIGNAME=false + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_VISUAL_IDENTIFIER_EXPANSION='✘' + + # Status when some part of a pipe command fails and the overall exit status is also non-zero. + # It may look like this: 1|0. + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE=true + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_FOREGROUND=160 + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_VISUAL_IDENTIFIER_EXPANSION='✘' + + ###################[ command_execution_time: duration of the last command ]################### + # Show duration of the last command if takes at least this many seconds. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD=3 + # Show this many fractional digits. Zero means round to seconds. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PRECISION=0 + # Execution time color. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FOREGROUND=248 + # Duration format: 1d 2h 3m 4s. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FORMAT='d h m s' + # Custom icon. + # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PREFIX='%248Ftook ' + + #######################[ background_jobs: presence of background jobs ]####################### + # Don't show the number of background jobs. + typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VERBOSE=false + # Background jobs color. + typeset -g POWERLEVEL9K_BACKGROUND_JOBS_FOREGROUND=37 + # Custom icon. + # typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######################[ direnv: direnv status (https://direnv.net/) ]######################## + # Direnv color. + typeset -g POWERLEVEL9K_DIRENV_FOREGROUND=178 + # Custom icon. + # typeset -g POWERLEVEL9K_DIRENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###############[ asdf: asdf version manager (https://github.com/asdf-vm/asdf) ]############### + # Default asdf color. Only used to display tools for which there is no color override (see below). + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_FOREGROUND. + typeset -g POWERLEVEL9K_ASDF_FOREGROUND=66 + + # There are four parameters that can be used to hide asdf tools. Each parameter describes + # conditions under which a tool gets hidden. Parameters can hide tools but not unhide them. If at + # least one parameter decides to hide a tool, that tool gets hidden. If no parameter decides to + # hide a tool, it gets shown. + # + # Special note on the difference between POWERLEVEL9K_ASDF_SOURCES and + # POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW. Consider the effect of the following commands: + # + # asdf local python 3.8.1 + # asdf global python 3.8.1 + # + # After running both commands the current python version is 3.8.1 and its source is "local" as + # it takes precedence over "global". If POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW is set to false, + # it'll hide python version in this case because 3.8.1 is the same as the global version. + # POWERLEVEL9K_ASDF_SOURCES will hide python version only if the value of this parameter doesn't + # contain "local". + + # Hide tool versions that don't come from one of these sources. + # + # Available sources: + # + # - shell `asdf current` says "set by ASDF_${TOOL}_VERSION environment variable" + # - local `asdf current` says "set by /some/not/home/directory/file" + # - global `asdf current` says "set by /home/username/file" + # + # Note: If this parameter is set to (shell local global), it won't hide tools. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SOURCES. + typeset -g POWERLEVEL9K_ASDF_SOURCES=(shell local global) + + # If set to false, hide tool versions that are the same as global. + # + # Note: The name of this parameter doesn't reflect its meaning at all. + # Note: If this parameter is set to true, it won't hide tools. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_PROMPT_ALWAYS_SHOW. + typeset -g POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW=false + + # If set to false, hide tool versions that are equal to "system". + # + # Note: If this parameter is set to true, it won't hide tools. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_SYSTEM. + typeset -g POWERLEVEL9K_ASDF_SHOW_SYSTEM=true + + # If set to non-empty value, hide tools unless there is a file matching the specified file pattern + # in the current directory, or its parent directory, or its grandparent directory, and so on. + # + # Note: If this parameter is set to empty value, it won't hide tools. + # Note: SHOW_ON_UPGLOB isn't specific to asdf. It works with all prompt segments. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_ON_UPGLOB. + # + # Example: Hide nodejs version when there is no package.json and no *.js files in the current + # directory, in `..`, in `../..` and so on. + # + # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.js|package.json' + typeset -g POWERLEVEL9K_ASDF_SHOW_ON_UPGLOB= + + # Ruby version from asdf. + typeset -g POWERLEVEL9K_ASDF_RUBY_FOREGROUND=168 + # typeset -g POWERLEVEL9K_ASDF_RUBY_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_RUBY_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Python version from asdf. + typeset -g POWERLEVEL9K_ASDF_PYTHON_FOREGROUND=37 + # typeset -g POWERLEVEL9K_ASDF_PYTHON_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_PYTHON_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Go version from asdf. + typeset -g POWERLEVEL9K_ASDF_GOLANG_FOREGROUND=37 + # typeset -g POWERLEVEL9K_ASDF_GOLANG_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_GOLANG_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Node.js version from asdf. + typeset -g POWERLEVEL9K_ASDF_NODEJS_FOREGROUND=70 + # typeset -g POWERLEVEL9K_ASDF_NODEJS_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Rust version from asdf. + typeset -g POWERLEVEL9K_ASDF_RUST_FOREGROUND=37 + # typeset -g POWERLEVEL9K_ASDF_RUST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_RUST_SHOW_ON_UPGLOB='*.foo|*.bar' + + # .NET Core version from asdf. + typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_FOREGROUND=134 + # typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Flutter version from asdf. + typeset -g POWERLEVEL9K_ASDF_FLUTTER_FOREGROUND=38 + # typeset -g POWERLEVEL9K_ASDF_FLUTTER_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_FLUTTER_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Lua version from asdf. + typeset -g POWERLEVEL9K_ASDF_LUA_FOREGROUND=32 + # typeset -g POWERLEVEL9K_ASDF_LUA_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_LUA_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Java version from asdf. + typeset -g POWERLEVEL9K_ASDF_JAVA_FOREGROUND=32 + # typeset -g POWERLEVEL9K_ASDF_JAVA_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_JAVA_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Perl version from asdf. + typeset -g POWERLEVEL9K_ASDF_PERL_FOREGROUND=67 + # typeset -g POWERLEVEL9K_ASDF_PERL_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_PERL_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Erlang version from asdf. + typeset -g POWERLEVEL9K_ASDF_ERLANG_FOREGROUND=125 + # typeset -g POWERLEVEL9K_ASDF_ERLANG_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_ERLANG_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Elixir version from asdf. + typeset -g POWERLEVEL9K_ASDF_ELIXIR_FOREGROUND=129 + # typeset -g POWERLEVEL9K_ASDF_ELIXIR_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_ELIXIR_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Postgres version from asdf. + typeset -g POWERLEVEL9K_ASDF_POSTGRES_FOREGROUND=31 + # typeset -g POWERLEVEL9K_ASDF_POSTGRES_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_POSTGRES_SHOW_ON_UPGLOB='*.foo|*.bar' + + # PHP version from asdf. + typeset -g POWERLEVEL9K_ASDF_PHP_FOREGROUND=99 + # typeset -g POWERLEVEL9K_ASDF_PHP_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_PHP_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Haskell version from asdf. + typeset -g POWERLEVEL9K_ASDF_HASKELL_FOREGROUND=172 + # typeset -g POWERLEVEL9K_ASDF_HASKELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_HASKELL_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Julia version from asdf. + typeset -g POWERLEVEL9K_ASDF_JULIA_FOREGROUND=70 + # typeset -g POWERLEVEL9K_ASDF_JULIA_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_JULIA_SHOW_ON_UPGLOB='*.foo|*.bar' + + ##########[ nordvpn: nordvpn connection status, linux only (https://nordvpn.com/) ]########### + # NordVPN connection indicator color. + typeset -g POWERLEVEL9K_NORDVPN_FOREGROUND=39 + # Hide NordVPN connection indicator when not connected. + typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_CONTENT_EXPANSION= + typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_VISUAL_IDENTIFIER_EXPANSION= + # Custom icon. + # typeset -g POWERLEVEL9K_NORDVPN_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #################[ ranger: ranger shell (https://github.com/ranger/ranger) ]################## + # Ranger shell color. + typeset -g POWERLEVEL9K_RANGER_FOREGROUND=178 + # Custom icon. + # typeset -g POWERLEVEL9K_RANGER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################[ nnn: nnn shell (https://github.com/jarun/nnn) ]####################### + # Nnn shell color. + typeset -g POWERLEVEL9K_NNN_FOREGROUND=72 + # Custom icon. + # typeset -g POWERLEVEL9K_NNN_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################[ lf: lf shell (https://github.com/gokcehan/lf) ]####################### + # lf shell color. + typeset -g POWERLEVEL9K_LF_FOREGROUND=72 + # Custom icon. + # typeset -g POWERLEVEL9K_LF_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################[ xplr: xplr shell (https://github.com/sayanarijit/xplr) ]################## + # xplr shell color. + typeset -g POWERLEVEL9K_XPLR_FOREGROUND=72 + # Custom icon. + # typeset -g POWERLEVEL9K_XPLR_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########################[ vim_shell: vim shell indicator (:sh) ]########################### + # Vim shell indicator color. + typeset -g POWERLEVEL9K_VIM_SHELL_FOREGROUND=34 + # Custom icon. + # typeset -g POWERLEVEL9K_VIM_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######[ midnight_commander: midnight commander shell (https://midnight-commander.org/) ]###### + # Midnight Commander shell color. + typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_FOREGROUND=178 + # Custom icon. + # typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #[ nix_shell: nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) ]## + # Nix shell color. + typeset -g POWERLEVEL9K_NIX_SHELL_FOREGROUND=74 + + # Display the icon of nix_shell if PATH contains a subdirectory of /nix/store. + # typeset -g POWERLEVEL9K_NIX_SHELL_INFER_FROM_PATH=false + + # Tip: If you want to see just the icon without "pure" and "impure", uncomment the next line. + # typeset -g POWERLEVEL9K_NIX_SHELL_CONTENT_EXPANSION= + + # Custom icon. + # typeset -g POWERLEVEL9K_NIX_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################[ chezmoi_shell: chezmoi shell (https://www.chezmoi.io/) ]################## + # chezmoi shell color. + typeset -g POWERLEVEL9K_CHEZMOI_SHELL_FOREGROUND=33 + # Custom icon. + # typeset -g POWERLEVEL9K_CHEZMOI_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################################[ disk_usage: disk usage ]################################## + # Colors for different levels of disk usage. + typeset -g POWERLEVEL9K_DISK_USAGE_NORMAL_FOREGROUND=35 + typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_FOREGROUND=220 + typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_FOREGROUND=160 + # Thresholds for different levels of disk usage (percentage points). + typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL=90 + typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_LEVEL=95 + # If set to true, hide disk usage when below $POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL percent. + typeset -g POWERLEVEL9K_DISK_USAGE_ONLY_WARNING=false + # Custom icon. + # typeset -g POWERLEVEL9K_DISK_USAGE_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ vi_mode: vi mode (you don't need this if you've enabled prompt_char) ]########### + # Text and color for normal (a.k.a. command) vi mode. + typeset -g POWERLEVEL9K_VI_COMMAND_MODE_STRING=NORMAL + typeset -g POWERLEVEL9K_VI_MODE_NORMAL_FOREGROUND=106 + # Text and color for visual vi mode. + typeset -g POWERLEVEL9K_VI_VISUAL_MODE_STRING=VISUAL + typeset -g POWERLEVEL9K_VI_MODE_VISUAL_FOREGROUND=68 + # Text and color for overtype (a.k.a. overwrite and replace) vi mode. + typeset -g POWERLEVEL9K_VI_OVERWRITE_MODE_STRING=OVERTYPE + typeset -g POWERLEVEL9K_VI_MODE_OVERWRITE_FOREGROUND=172 + # Text and color for insert vi mode. + typeset -g POWERLEVEL9K_VI_INSERT_MODE_STRING= + typeset -g POWERLEVEL9K_VI_MODE_INSERT_FOREGROUND=66 + + # Custom icon. + # typeset -g POWERLEVEL9K_RANGER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################################[ ram: free RAM ]####################################### + # RAM color. + typeset -g POWERLEVEL9K_RAM_FOREGROUND=66 + # Custom icon. + # typeset -g POWERLEVEL9K_RAM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #####################################[ swap: used swap ]###################################### + # Swap color. + typeset -g POWERLEVEL9K_SWAP_FOREGROUND=96 + # Custom icon. + # typeset -g POWERLEVEL9K_SWAP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################################[ load: CPU load ]###################################### + # Show average CPU load over this many last minutes. Valid values are 1, 5 and 15. + typeset -g POWERLEVEL9K_LOAD_WHICH=5 + # Load color when load is under 50%. + typeset -g POWERLEVEL9K_LOAD_NORMAL_FOREGROUND=66 + # Load color when load is between 50% and 70%. + typeset -g POWERLEVEL9K_LOAD_WARNING_FOREGROUND=178 + # Load color when load is over 70%. + typeset -g POWERLEVEL9K_LOAD_CRITICAL_FOREGROUND=166 + # Custom icon. + # typeset -g POWERLEVEL9K_LOAD_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ todo: todo items (https://github.com/todotxt/todo.txt-cli) ]################ + # Todo color. + typeset -g POWERLEVEL9K_TODO_FOREGROUND=110 + # Hide todo when the total number of tasks is zero. + typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_TOTAL=true + # Hide todo when the number of tasks after filtering is zero. + typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_FILTERED=false + + # Todo format. The following parameters are available within the expansion. + # + # - P9K_TODO_TOTAL_TASK_COUNT The total number of tasks. + # - P9K_TODO_FILTERED_TASK_COUNT The number of tasks after filtering. + # + # These variables correspond to the last line of the output of `todo.sh -p ls`: + # + # TODO: 24 of 42 tasks shown + # + # Here 24 is P9K_TODO_FILTERED_TASK_COUNT and 42 is P9K_TODO_TOTAL_TASK_COUNT. + # + # typeset -g POWERLEVEL9K_TODO_CONTENT_EXPANSION='$P9K_TODO_FILTERED_TASK_COUNT' + + # Custom icon. + # typeset -g POWERLEVEL9K_TODO_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ timewarrior: timewarrior tracking status (https://timewarrior.net/) ]############ + # Timewarrior color. + typeset -g POWERLEVEL9K_TIMEWARRIOR_FOREGROUND=110 + # If the tracked task is longer than 24 characters, truncate and append "…". + # Tip: To always display tasks without truncation, delete the following parameter. + # Tip: To hide task names and display just the icon when time tracking is enabled, set the + # value of the following parameter to "". + typeset -g POWERLEVEL9K_TIMEWARRIOR_CONTENT_EXPANSION='${P9K_CONTENT:0:24}${${P9K_CONTENT:24}:+…}' + + # Custom icon. + # typeset -g POWERLEVEL9K_TIMEWARRIOR_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##############[ taskwarrior: taskwarrior task count (https://taskwarrior.org/) ]############## + # Taskwarrior color. + typeset -g POWERLEVEL9K_TASKWARRIOR_FOREGROUND=74 + + # Taskwarrior segment format. The following parameters are available within the expansion. + # + # - P9K_TASKWARRIOR_PENDING_COUNT The number of pending tasks: `task +PENDING count`. + # - P9K_TASKWARRIOR_OVERDUE_COUNT The number of overdue tasks: `task +OVERDUE count`. + # + # Zero values are represented as empty parameters. + # + # The default format: + # + # '${P9K_TASKWARRIOR_OVERDUE_COUNT:+"!$P9K_TASKWARRIOR_OVERDUE_COUNT/"}$P9K_TASKWARRIOR_PENDING_COUNT' + # + # typeset -g POWERLEVEL9K_TASKWARRIOR_CONTENT_EXPANSION='$P9K_TASKWARRIOR_PENDING_COUNT' + + # Custom icon. + # typeset -g POWERLEVEL9K_TASKWARRIOR_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######[ per_directory_history: Oh My Zsh per-directory-history local/global indicator ]####### + # Color when using local/global history. + typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_FOREGROUND=135 + typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_FOREGROUND=130 + + # Tip: Uncomment the next two lines to hide "local"/"global" text and leave just the icon. + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_CONTENT_EXPANSION='' + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_CONTENT_EXPANSION='' + + # Custom icon. + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################################[ cpu_arch: CPU architecture ]################################ + # CPU architecture color. + typeset -g POWERLEVEL9K_CPU_ARCH_FOREGROUND=172 + + # Hide the segment when on a specific CPU architecture. + # typeset -g POWERLEVEL9K_CPU_ARCH_X86_64_CONTENT_EXPANSION= + # typeset -g POWERLEVEL9K_CPU_ARCH_X86_64_VISUAL_IDENTIFIER_EXPANSION= + + # Custom icon. + # typeset -g POWERLEVEL9K_CPU_ARCH_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################################[ context: user@hostname ]################################## + # Context color when running with privileges. + typeset -g POWERLEVEL9K_CONTEXT_ROOT_FOREGROUND=178 + # Context color in SSH without privileges. + typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_FOREGROUND=180 + # Default context color (no privileges, no SSH). + typeset -g POWERLEVEL9K_CONTEXT_FOREGROUND=180 + + # Context format when running with privileges: bold user@hostname. + typeset -g POWERLEVEL9K_CONTEXT_ROOT_TEMPLATE='%B%n@%m' + # Context format when in SSH without privileges: user@hostname. + typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_TEMPLATE='%n@%m' + # Default context format (no privileges, no SSH): user@hostname. + typeset -g POWERLEVEL9K_CONTEXT_TEMPLATE='%n@%m' + + # Don't show context unless running with privileges or in SSH. + # Tip: Remove the next line to always show context. + typeset -g POWERLEVEL9K_CONTEXT_{DEFAULT,SUDO}_{CONTENT,VISUAL_IDENTIFIER}_EXPANSION= + + # Custom icon. + # typeset -g POWERLEVEL9K_CONTEXT_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_CONTEXT_PREFIX='%248Fwith ' + + ###[ virtualenv: python virtual environment (https://docs.python.org/3/library/venv.html) ]### + # Python virtual environment color. + typeset -g POWERLEVEL9K_VIRTUALENV_FOREGROUND=37 + # Don't show Python version next to the virtual environment name. + typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_PYTHON_VERSION=false + # If set to "false", won't show virtualenv if pyenv is already shown. + # If set to "if-different", won't show virtualenv if it's the same as pyenv. + typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_WITH_PYENV=false + # Separate environment name from Python version only with a space. + typeset -g POWERLEVEL9K_VIRTUALENV_{LEFT,RIGHT}_DELIMITER= + # Custom icon. + # typeset -g POWERLEVEL9K_VIRTUALENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #####################[ anaconda: conda environment (https://conda.io/) ]###################### + # Anaconda environment color. + typeset -g POWERLEVEL9K_ANACONDA_FOREGROUND=37 + + # Anaconda segment format. The following parameters are available within the expansion. + # + # - CONDA_PREFIX Absolute path to the active Anaconda/Miniconda environment. + # - CONDA_DEFAULT_ENV Name of the active Anaconda/Miniconda environment. + # - CONDA_PROMPT_MODIFIER Configurable prompt modifier (see below). + # - P9K_ANACONDA_PYTHON_VERSION Current python version (python --version). + # + # CONDA_PROMPT_MODIFIER can be configured with the following command: + # + # conda config --set env_prompt '({default_env}) ' + # + # The last argument is a Python format string that can use the following variables: + # + # - prefix The same as CONDA_PREFIX. + # - default_env The same as CONDA_DEFAULT_ENV. + # - name The last segment of CONDA_PREFIX. + # - stacked_env Comma-separated list of names in the environment stack. The first element is + # always the same as default_env. + # + # Note: '({default_env}) ' is the default value of env_prompt. + # + # The default value of POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION expands to $CONDA_PROMPT_MODIFIER + # without the surrounding parentheses, or to the last path component of CONDA_PREFIX if the former + # is empty. + typeset -g POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION='${${${${CONDA_PROMPT_MODIFIER#\(}% }%\)}:-${CONDA_PREFIX:t}}' + + # Custom icon. + # typeset -g POWERLEVEL9K_ANACONDA_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ pyenv: python environment (https://github.com/pyenv/pyenv) ]################ + # Pyenv color. + typeset -g POWERLEVEL9K_PYENV_FOREGROUND=37 + # Hide python version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_PYENV_SOURCES=(shell local global) + # If set to false, hide python version if it's the same as global: + # $(pyenv version-name) == $(pyenv global). + typeset -g POWERLEVEL9K_PYENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide python version if it's equal to "system". + typeset -g POWERLEVEL9K_PYENV_SHOW_SYSTEM=true + + # Pyenv segment format. The following parameters are available within the expansion. + # + # - P9K_CONTENT Current pyenv environment (pyenv version-name). + # - P9K_PYENV_PYTHON_VERSION Current python version (python --version). + # + # The default format has the following logic: + # + # 1. Display just "$P9K_CONTENT" if it's equal to "$P9K_PYENV_PYTHON_VERSION" or + # starts with "$P9K_PYENV_PYTHON_VERSION/". + # 2. Otherwise display "$P9K_CONTENT $P9K_PYENV_PYTHON_VERSION". + typeset -g POWERLEVEL9K_PYENV_CONTENT_EXPANSION='${P9K_CONTENT}${${P9K_CONTENT:#$P9K_PYENV_PYTHON_VERSION(|/*)}:+ $P9K_PYENV_PYTHON_VERSION}' + + # Custom icon. + # typeset -g POWERLEVEL9K_PYENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ goenv: go environment (https://github.com/syndbg/goenv) ]################ + # Goenv color. + typeset -g POWERLEVEL9K_GOENV_FOREGROUND=37 + # Hide go version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_GOENV_SOURCES=(shell local global) + # If set to false, hide go version if it's the same as global: + # $(goenv version-name) == $(goenv global). + typeset -g POWERLEVEL9K_GOENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide go version if it's equal to "system". + typeset -g POWERLEVEL9K_GOENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_GOENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ nodenv: node.js version from nodenv (https://github.com/nodenv/nodenv) ]########## + # Nodenv color. + typeset -g POWERLEVEL9K_NODENV_FOREGROUND=70 + # Hide node version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_NODENV_SOURCES=(shell local global) + # If set to false, hide node version if it's the same as global: + # $(nodenv version-name) == $(nodenv global). + typeset -g POWERLEVEL9K_NODENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide node version if it's equal to "system". + typeset -g POWERLEVEL9K_NODENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_NODENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##############[ nvm: node.js version from nvm (https://github.com/nvm-sh/nvm) ]############### + # Nvm color. + typeset -g POWERLEVEL9K_NVM_FOREGROUND=70 + # If set to false, hide node version if it's the same as default: + # $(nvm version current) == $(nvm version default). + typeset -g POWERLEVEL9K_NVM_PROMPT_ALWAYS_SHOW=false + # If set to false, hide node version if it's equal to "system". + typeset -g POWERLEVEL9K_NVM_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_NVM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ############[ nodeenv: node.js environment (https://github.com/ekalinin/nodeenv) ]############ + # Nodeenv color. + typeset -g POWERLEVEL9K_NODEENV_FOREGROUND=70 + # Don't show Node version next to the environment name. + typeset -g POWERLEVEL9K_NODEENV_SHOW_NODE_VERSION=false + # Separate environment name from Node version only with a space. + typeset -g POWERLEVEL9K_NODEENV_{LEFT,RIGHT}_DELIMITER= + # Custom icon. + # typeset -g POWERLEVEL9K_NODEENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##############################[ node_version: node.js version ]############################### + # Node version color. + typeset -g POWERLEVEL9K_NODE_VERSION_FOREGROUND=70 + # Show node version only when in a directory tree containing package.json. + typeset -g POWERLEVEL9K_NODE_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_NODE_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######################[ go_version: go version (https://golang.org) ]######################## + # Go version color. + typeset -g POWERLEVEL9K_GO_VERSION_FOREGROUND=37 + # Show go version only when in a go project subdirectory. + typeset -g POWERLEVEL9K_GO_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_GO_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #################[ rust_version: rustc version (https://www.rust-lang.org) ]################## + # Rust version color. + typeset -g POWERLEVEL9K_RUST_VERSION_FOREGROUND=37 + # Show rust version only when in a rust project subdirectory. + typeset -g POWERLEVEL9K_RUST_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_RUST_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###############[ dotnet_version: .NET version (https://dotnet.microsoft.com) ]################ + # .NET version color. + typeset -g POWERLEVEL9K_DOTNET_VERSION_FOREGROUND=134 + # Show .NET version only when in a .NET project subdirectory. + typeset -g POWERLEVEL9K_DOTNET_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_DOTNET_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #####################[ php_version: php version (https://www.php.net/) ]###################### + # PHP version color. + typeset -g POWERLEVEL9K_PHP_VERSION_FOREGROUND=99 + # Show PHP version only when in a PHP project subdirectory. + typeset -g POWERLEVEL9K_PHP_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_PHP_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ laravel_version: laravel php framework version (https://laravel.com/) ]########### + # Laravel version color. + typeset -g POWERLEVEL9K_LARAVEL_VERSION_FOREGROUND=161 + # Custom icon. + # typeset -g POWERLEVEL9K_LARAVEL_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ####################[ java_version: java version (https://www.java.com/) ]#################### + # Java version color. + typeset -g POWERLEVEL9K_JAVA_VERSION_FOREGROUND=32 + # Show java version only when in a java project subdirectory. + typeset -g POWERLEVEL9K_JAVA_VERSION_PROJECT_ONLY=true + # Show brief version. + typeset -g POWERLEVEL9K_JAVA_VERSION_FULL=false + # Custom icon. + # typeset -g POWERLEVEL9K_JAVA_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###[ package: name@version from package.json (https://docs.npmjs.com/files/package.json) ]#### + # Package color. + typeset -g POWERLEVEL9K_PACKAGE_FOREGROUND=117 + # Package format. The following parameters are available within the expansion. + # + # - P9K_PACKAGE_NAME The value of `name` field in package.json. + # - P9K_PACKAGE_VERSION The value of `version` field in package.json. + # + # typeset -g POWERLEVEL9K_PACKAGE_CONTENT_EXPANSION='${P9K_PACKAGE_NAME//\%/%%}@${P9K_PACKAGE_VERSION//\%/%%}' + # Custom icon. + # typeset -g POWERLEVEL9K_PACKAGE_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #############[ rbenv: ruby version from rbenv (https://github.com/rbenv/rbenv) ]############## + # Rbenv color. + typeset -g POWERLEVEL9K_RBENV_FOREGROUND=168 + # Hide ruby version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_RBENV_SOURCES=(shell local global) + # If set to false, hide ruby version if it's the same as global: + # $(rbenv version-name) == $(rbenv global). + typeset -g POWERLEVEL9K_RBENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide ruby version if it's equal to "system". + typeset -g POWERLEVEL9K_RBENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_RBENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######################[ rvm: ruby version from rvm (https://rvm.io) ]######################## + # Rvm color. + typeset -g POWERLEVEL9K_RVM_FOREGROUND=168 + # Don't show @gemset at the end. + typeset -g POWERLEVEL9K_RVM_SHOW_GEMSET=false + # Don't show ruby- at the front. + typeset -g POWERLEVEL9K_RVM_SHOW_PREFIX=false + # Custom icon. + # typeset -g POWERLEVEL9K_RVM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ fvm: flutter version management (https://github.com/leoafarias/fvm) ]############ + # Fvm color. + typeset -g POWERLEVEL9K_FVM_FOREGROUND=38 + # Custom icon. + # typeset -g POWERLEVEL9K_FVM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ luaenv: lua version from luaenv (https://github.com/cehoffman/luaenv) ]########### + # Lua color. + typeset -g POWERLEVEL9K_LUAENV_FOREGROUND=32 + # Hide lua version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_LUAENV_SOURCES=(shell local global) + # If set to false, hide lua version if it's the same as global: + # $(luaenv version-name) == $(luaenv global). + typeset -g POWERLEVEL9K_LUAENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide lua version if it's equal to "system". + typeset -g POWERLEVEL9K_LUAENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_LUAENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###############[ jenv: java version from jenv (https://github.com/jenv/jenv) ]################ + # Java color. + typeset -g POWERLEVEL9K_JENV_FOREGROUND=32 + # Hide java version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_JENV_SOURCES=(shell local global) + # If set to false, hide java version if it's the same as global: + # $(jenv version-name) == $(jenv global). + typeset -g POWERLEVEL9K_JENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide java version if it's equal to "system". + typeset -g POWERLEVEL9K_JENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_JENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ plenv: perl version from plenv (https://github.com/tokuhirom/plenv) ]############ + # Perl color. + typeset -g POWERLEVEL9K_PLENV_FOREGROUND=67 + # Hide perl version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_PLENV_SOURCES=(shell local global) + # If set to false, hide perl version if it's the same as global: + # $(plenv version-name) == $(plenv global). + typeset -g POWERLEVEL9K_PLENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide perl version if it's equal to "system". + typeset -g POWERLEVEL9K_PLENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_PLENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ perlbrew: perl version from perlbrew (https://github.com/gugod/App-perlbrew) ]############ + # Perlbrew color. + typeset -g POWERLEVEL9K_PERLBREW_FOREGROUND=67 + # Show perlbrew version only when in a perl project subdirectory. + typeset -g POWERLEVEL9K_PERLBREW_PROJECT_ONLY=true + # Don't show "perl-" at the front. + typeset -g POWERLEVEL9K_PERLBREW_SHOW_PREFIX=false + # Custom icon. + # typeset -g POWERLEVEL9K_PERLBREW_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ############[ phpenv: php version from phpenv (https://github.com/phpenv/phpenv) ]############ + # PHP color. + typeset -g POWERLEVEL9K_PHPENV_FOREGROUND=99 + # Hide php version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_PHPENV_SOURCES=(shell local global) + # If set to false, hide php version if it's the same as global: + # $(phpenv version-name) == $(phpenv global). + typeset -g POWERLEVEL9K_PHPENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide php version if it's equal to "system". + typeset -g POWERLEVEL9K_PHPENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_PHPENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######[ scalaenv: scala version from scalaenv (https://github.com/scalaenv/scalaenv) ]####### + # Scala color. + typeset -g POWERLEVEL9K_SCALAENV_FOREGROUND=160 + # Hide scala version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_SCALAENV_SOURCES=(shell local global) + # If set to false, hide scala version if it's the same as global: + # $(scalaenv version-name) == $(scalaenv global). + typeset -g POWERLEVEL9K_SCALAENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide scala version if it's equal to "system". + typeset -g POWERLEVEL9K_SCALAENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_SCALAENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ haskell_stack: haskell version from stack (https://haskellstack.org/) ]########### + # Haskell color. + typeset -g POWERLEVEL9K_HASKELL_STACK_FOREGROUND=172 + # Hide haskell version if it doesn't come from one of these sources. + # + # shell: version is set by STACK_YAML + # local: version is set by stack.yaml up the directory tree + # global: version is set by the implicit global project (~/.stack/global-project/stack.yaml) + typeset -g POWERLEVEL9K_HASKELL_STACK_SOURCES=(shell local) + # If set to false, hide haskell version if it's the same as in the implicit global project. + typeset -g POWERLEVEL9K_HASKELL_STACK_ALWAYS_SHOW=true + # Custom icon. + # typeset -g POWERLEVEL9K_HASKELL_STACK_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ terraform: terraform workspace (https://www.terraform.io) ]################# + # Don't show terraform workspace if it's literally "default". + typeset -g POWERLEVEL9K_TERRAFORM_SHOW_DEFAULT=false + # POWERLEVEL9K_TERRAFORM_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current terraform workspace gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_TERRAFORM_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_TERRAFORM_CLASSES defines the workspace class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' OTHER) + # + # If your current terraform workspace is "project_test", its class is TEST because "project_test" + # doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_FOREGROUND=28 + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' OTHER) + typeset -g POWERLEVEL9K_TERRAFORM_OTHER_FOREGROUND=38 + # typeset -g POWERLEVEL9K_TERRAFORM_OTHER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #############[ terraform_version: terraform version (https://www.terraform.io) ]############## + # Terraform version color. + typeset -g POWERLEVEL9K_TERRAFORM_VERSION_FOREGROUND=38 + # Custom icon. + # typeset -g POWERLEVEL9K_TERRAFORM_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #############[ kubecontext: current kubernetes context (https://kubernetes.io/) ]############# + # Show kubecontext only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show kubecontext. + typeset -g POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND='kubectl|helm|kubens|kubectx|oc|istioctl|kogito|k9s|helmfile|flux|fluxctl|stern|kubeseal|skaffold|kubent|kubecolor|cmctl|sparkctl' + + # Kubernetes context classes for the purpose of using different colors, icons and expansions with + # different contexts. + # + # POWERLEVEL9K_KUBECONTEXT_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current kubernetes context gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_KUBECONTEXT_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_KUBECONTEXT_CLASSES defines the context class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' DEFAULT) + # + # If your current kubernetes context is "deathray-testing/default", its class is TEST + # because "deathray-testing/default" doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_FOREGROUND=28 + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' DEFAULT) + typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_FOREGROUND=134 + # typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Use POWERLEVEL9K_KUBECONTEXT_CONTENT_EXPANSION to specify the content displayed by kubecontext + # segment. Parameter expansions are very flexible and fast, too. See reference: + # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion. + # + # Within the expansion the following parameters are always available: + # + # - P9K_CONTENT The content that would've been displayed if there was no content + # expansion defined. + # - P9K_KUBECONTEXT_NAME The current context's name. Corresponds to column NAME in the + # output of `kubectl config get-contexts`. + # - P9K_KUBECONTEXT_CLUSTER The current context's cluster. Corresponds to column CLUSTER in the + # output of `kubectl config get-contexts`. + # - P9K_KUBECONTEXT_NAMESPACE The current context's namespace. Corresponds to column NAMESPACE + # in the output of `kubectl config get-contexts`. If there is no + # namespace, the parameter is set to "default". + # - P9K_KUBECONTEXT_USER The current context's user. Corresponds to column AUTHINFO in the + # output of `kubectl config get-contexts`. + # + # If the context points to Google Kubernetes Engine (GKE) or Elastic Kubernetes Service (EKS), + # the following extra parameters are available: + # + # - P9K_KUBECONTEXT_CLOUD_NAME Either "gke" or "eks". + # - P9K_KUBECONTEXT_CLOUD_ACCOUNT Account/project ID. + # - P9K_KUBECONTEXT_CLOUD_ZONE Availability zone. + # - P9K_KUBECONTEXT_CLOUD_CLUSTER Cluster. + # + # P9K_KUBECONTEXT_CLOUD_* parameters are derived from P9K_KUBECONTEXT_CLUSTER. For example, + # if P9K_KUBECONTEXT_CLUSTER is "gke_my-account_us-east1-a_my-cluster-01": + # + # - P9K_KUBECONTEXT_CLOUD_NAME=gke + # - P9K_KUBECONTEXT_CLOUD_ACCOUNT=my-account + # - P9K_KUBECONTEXT_CLOUD_ZONE=us-east1-a + # - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01 + # + # If P9K_KUBECONTEXT_CLUSTER is "arn:aws:eks:us-east-1:123456789012:cluster/my-cluster-01": + # + # - P9K_KUBECONTEXT_CLOUD_NAME=eks + # - P9K_KUBECONTEXT_CLOUD_ACCOUNT=123456789012 + # - P9K_KUBECONTEXT_CLOUD_ZONE=us-east-1 + # - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01 + typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION= + # Show P9K_KUBECONTEXT_CLOUD_CLUSTER if it's not empty and fall back to P9K_KUBECONTEXT_NAME. + POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${P9K_KUBECONTEXT_CLOUD_CLUSTER:-${P9K_KUBECONTEXT_NAME}}' + # Append the current context's namespace if it's not "default". + POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${${:-/$P9K_KUBECONTEXT_NAMESPACE}:#/default}' + + # Custom prefix. + # typeset -g POWERLEVEL9K_KUBECONTEXT_PREFIX='%248Fat ' + + #[ aws: aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) ]# + # Show aws only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show aws. + typeset -g POWERLEVEL9K_AWS_SHOW_ON_COMMAND='aws|awless|terraform|pulumi|terragrunt' + + # POWERLEVEL9K_AWS_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current AWS profile gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_AWS_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_AWS_CLASSES defines the profile class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_AWS_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' DEFAULT) + # + # If your current AWS profile is "company_test", its class is TEST + # because "company_test" doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_AWS_TEST_FOREGROUND=28 + # typeset -g POWERLEVEL9K_AWS_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_AWS_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_AWS_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' DEFAULT) + typeset -g POWERLEVEL9K_AWS_DEFAULT_FOREGROUND=208 + # typeset -g POWERLEVEL9K_AWS_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # AWS segment format. The following parameters are available within the expansion. + # + # - P9K_AWS_PROFILE The name of the current AWS profile. + # - P9K_AWS_REGION The region associated with the current AWS profile. + typeset -g POWERLEVEL9K_AWS_CONTENT_EXPANSION='${P9K_AWS_PROFILE//\%/%%}${P9K_AWS_REGION:+ ${P9K_AWS_REGION//\%/%%}}' + + #[ aws_eb_env: aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) ]# + # AWS Elastic Beanstalk environment color. + typeset -g POWERLEVEL9K_AWS_EB_ENV_FOREGROUND=70 + # Custom icon. + # typeset -g POWERLEVEL9K_AWS_EB_ENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ azure: azure account name (https://docs.microsoft.com/en-us/cli/azure) ]########## + # Show azure only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show azure. + typeset -g POWERLEVEL9K_AZURE_SHOW_ON_COMMAND='az|terraform|pulumi|terragrunt' + + # POWERLEVEL9K_AZURE_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current azure account name gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_AZURE_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_AZURE_CLASSES defines the account class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_AZURE_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' OTHER) + # + # If your current azure account is "company_test", its class is TEST because "company_test" + # doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_AZURE_TEST_FOREGROUND=28 + # typeset -g POWERLEVEL9K_AZURE_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_AZURE_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_AZURE_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' OTHER) + + # Azure account name color. + typeset -g POWERLEVEL9K_AZURE_OTHER_FOREGROUND=32 + # Custom icon. + # typeset -g POWERLEVEL9K_AZURE_OTHER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ gcloud: google cloud account and project (https://cloud.google.com/) ]########### + # Show gcloud only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show gcloud. + typeset -g POWERLEVEL9K_GCLOUD_SHOW_ON_COMMAND='gcloud|gcs|gsutil' + # Google cloud color. + typeset -g POWERLEVEL9K_GCLOUD_FOREGROUND=32 + + # Google cloud format. Change the value of POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION and/or + # POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION if the default is too verbose or not informative + # enough. You can use the following parameters in the expansions. Each of them corresponds to the + # output of `gcloud` tool. + # + # Parameter | Source + # -------------------------|-------------------------------------------------------------------- + # P9K_GCLOUD_CONFIGURATION | gcloud config configurations list --format='value(name)' + # P9K_GCLOUD_ACCOUNT | gcloud config get-value account + # P9K_GCLOUD_PROJECT_ID | gcloud config get-value project + # P9K_GCLOUD_PROJECT_NAME | gcloud projects describe $P9K_GCLOUD_PROJECT_ID --format='value(name)' + # + # Note: ${VARIABLE//\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced with '%%'. + # + # Obtaining project name requires sending a request to Google servers. This can take a long time + # and even fail. When project name is unknown, P9K_GCLOUD_PROJECT_NAME is not set and gcloud + # prompt segment is in state PARTIAL. When project name gets known, P9K_GCLOUD_PROJECT_NAME gets + # set and gcloud prompt segment transitions to state COMPLETE. + # + # You can customize the format, icon and colors of gcloud segment separately for states PARTIAL + # and COMPLETE. You can also hide gcloud in state PARTIAL by setting + # POWERLEVEL9K_GCLOUD_PARTIAL_VISUAL_IDENTIFIER_EXPANSION and + # POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION to empty. + typeset -g POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_ID//\%/%%}' + typeset -g POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_NAME//\%/%%}' + + # Send a request to Google (by means of `gcloud projects describe ...`) to obtain project name + # this often. Negative value disables periodic polling. In this mode project name is retrieved + # only when the current configuration, account or project id changes. + typeset -g POWERLEVEL9K_GCLOUD_REFRESH_PROJECT_NAME_SECONDS=60 + + # Custom icon. + # typeset -g POWERLEVEL9K_GCLOUD_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #[ google_app_cred: google application credentials (https://cloud.google.com/docs/authentication/production) ]# + # Show google_app_cred only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show google_app_cred. + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_SHOW_ON_COMMAND='terraform|pulumi|terragrunt' + + # Google application credentials classes for the purpose of using different colors, icons and + # expansions with different credentials. + # + # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES is an array with even number of elements. The first + # element in each pair defines a pattern against which the current kubernetes context gets + # matched. More specifically, it's P9K_CONTENT prior to the application of context expansion + # (see below) that gets matched. If you unset all POWERLEVEL9K_GOOGLE_APP_CRED_*CONTENT_EXPANSION + # parameters, you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES defines the context class. Patterns are tried in order. + # The first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=( + # '*:*prod*:*' PROD + # '*:*test*:*' TEST + # '*' DEFAULT) + # + # If your current Google application credentials is "service_account deathray-testing x@y.com", + # its class is TEST because it doesn't match the pattern '* *prod* *' but does match '* *test* *'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_FOREGROUND=28 + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_CONTENT_EXPANSION='$P9K_GOOGLE_APP_CRED_PROJECT_ID' + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=( + # '*:*prod*:*' PROD # These values are examples that are unlikely + # '*:*test*:*' TEST # to match your needs. Customize them as needed. + '*' DEFAULT) + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_FOREGROUND=32 + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Use POWERLEVEL9K_GOOGLE_APP_CRED_CONTENT_EXPANSION to specify the content displayed by + # google_app_cred segment. Parameter expansions are very flexible and fast, too. See reference: + # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion. + # + # You can use the following parameters in the expansion. Each of them corresponds to one of the + # fields in the JSON file pointed to by GOOGLE_APPLICATION_CREDENTIALS. + # + # Parameter | JSON key file field + # ---------------------------------+--------------- + # P9K_GOOGLE_APP_CRED_TYPE | type + # P9K_GOOGLE_APP_CRED_PROJECT_ID | project_id + # P9K_GOOGLE_APP_CRED_CLIENT_EMAIL | client_email + # + # Note: ${VARIABLE//\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced by '%%'. + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_CONTENT_EXPANSION='${P9K_GOOGLE_APP_CRED_PROJECT_ID//\%/%%}' + + ##############[ toolbox: toolbox name (https://github.com/containers/toolbox) ]############### + # Toolbox color. + typeset -g POWERLEVEL9K_TOOLBOX_FOREGROUND=178 + # Don't display the name of the toolbox if it matches fedora-toolbox-*. + typeset -g POWERLEVEL9K_TOOLBOX_CONTENT_EXPANSION='${P9K_TOOLBOX_NAME:#fedora-toolbox-*}' + # Custom icon. + # typeset -g POWERLEVEL9K_TOOLBOX_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_TOOLBOX_PREFIX='%248Fin ' + + ###############################[ public_ip: public IP address ]############################### + # Public IP color. + typeset -g POWERLEVEL9K_PUBLIC_IP_FOREGROUND=94 + # Custom icon. + # typeset -g POWERLEVEL9K_PUBLIC_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ########################[ vpn_ip: virtual private network indicator ]######################### + # VPN IP color. + typeset -g POWERLEVEL9K_VPN_IP_FOREGROUND=81 + # When on VPN, show just an icon without the IP address. + # Tip: To display the private IP address when on VPN, remove the next line. + typeset -g POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION= + # Regular expression for the VPN network interface. Run `ifconfig` or `ip -4 a show` while on VPN + # to see the name of the interface. + typeset -g POWERLEVEL9K_VPN_IP_INTERFACE='(gpd|wg|(.*tun)|tailscale)[0-9]*|(zt.*)' + # If set to true, show one segment per matching network interface. If set to false, show only + # one segment corresponding to the first matching network interface. + # Tip: If you set it to true, you'll probably want to unset POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION. + typeset -g POWERLEVEL9K_VPN_IP_SHOW_ALL=false + # Custom icon. + # typeset -g POWERLEVEL9K_VPN_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ ip: ip address and bandwidth usage for a specified network interface ]########### + # IP color. + typeset -g POWERLEVEL9K_IP_FOREGROUND=38 + # The following parameters are accessible within the expansion: + # + # Parameter | Meaning + # ----------------------+------------------------------------------- + # P9K_IP_IP | IP address + # P9K_IP_INTERFACE | network interface + # P9K_IP_RX_BYTES | total number of bytes received + # P9K_IP_TX_BYTES | total number of bytes sent + # P9K_IP_RX_BYTES_DELTA | number of bytes received since last prompt + # P9K_IP_TX_BYTES_DELTA | number of bytes sent since last prompt + # P9K_IP_RX_RATE | receive rate (since last prompt) + # P9K_IP_TX_RATE | send rate (since last prompt) + typeset -g POWERLEVEL9K_IP_CONTENT_EXPANSION='${P9K_IP_RX_RATE:+%70F⇣$P9K_IP_RX_RATE }${P9K_IP_TX_RATE:+%215F⇡$P9K_IP_TX_RATE }%38F$P9K_IP_IP' + # Show information for the first network interface whose name matches this regular expression. + # Run `ifconfig` or `ip -4 a show` to see the names of all network interfaces. + typeset -g POWERLEVEL9K_IP_INTERFACE='[ew].*' + # Custom icon. + # typeset -g POWERLEVEL9K_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #########################[ proxy: system-wide http/https/ftp proxy ]########################## + # Proxy color. + typeset -g POWERLEVEL9K_PROXY_FOREGROUND=68 + # Custom icon. + # typeset -g POWERLEVEL9K_PROXY_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################################[ battery: internal battery ]################################# + # Show battery in red when it's below this level and not connected to power supply. + typeset -g POWERLEVEL9K_BATTERY_LOW_THRESHOLD=20 + typeset -g POWERLEVEL9K_BATTERY_LOW_FOREGROUND=160 + # Show battery in green when it's charging or fully charged. + typeset -g POWERLEVEL9K_BATTERY_{CHARGING,CHARGED}_FOREGROUND=70 + # Show battery in yellow when it's discharging. + typeset -g POWERLEVEL9K_BATTERY_DISCONNECTED_FOREGROUND=178 + # Battery pictograms going from low to high level of charge. + typeset -g POWERLEVEL9K_BATTERY_STAGES=('%K{232}▁' '%K{232}▂' '%K{232}▃' '%K{232}▄' '%K{232}▅' '%K{232}▆' '%K{232}▇' '%K{232}█') + # Don't show the remaining time to charge/discharge. + typeset -g POWERLEVEL9K_BATTERY_VERBOSE=false + + #####################################[ wifi: wifi speed ]##################################### + # WiFi color. + typeset -g POWERLEVEL9K_WIFI_FOREGROUND=68 + # Custom icon. + # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Use different colors and icons depending on signal strength ($P9K_WIFI_BARS). + # + # # Wifi colors and icons for different signal strength levels (low to high). + # typeset -g my_wifi_fg=(68 68 68 68 68) # <-- change these values + # typeset -g my_wifi_icon=('WiFi' 'WiFi' 'WiFi' 'WiFi' 'WiFi') # <-- change these values + # + # typeset -g POWERLEVEL9K_WIFI_CONTENT_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}$P9K_WIFI_LAST_TX_RATE Mbps' + # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}${my_wifi_icon[P9K_WIFI_BARS+1]}' + # + # The following parameters are accessible within the expansions: + # + # Parameter | Meaning + # ----------------------+--------------- + # P9K_WIFI_SSID | service set identifier, a.k.a. network name + # P9K_WIFI_LINK_AUTH | authentication protocol such as "wpa2-psk" or "none"; empty if unknown + # P9K_WIFI_LAST_TX_RATE | wireless transmit rate in megabits per second + # P9K_WIFI_RSSI | signal strength in dBm, from -120 to 0 + # P9K_WIFI_NOISE | noise in dBm, from -120 to 0 + # P9K_WIFI_BARS | signal strength in bars, from 0 to 4 (derived from P9K_WIFI_RSSI and P9K_WIFI_NOISE) + + ####################################[ time: current time ]#################################### + # Current time color. + typeset -g POWERLEVEL9K_TIME_FOREGROUND=66 + # Format for the current time: 09:51:02. See `man 3 strftime`. + typeset -g POWERLEVEL9K_TIME_FORMAT='%D{%H:%M:%S}' + # If set to true, time will update when you hit enter. This way prompts for the past + # commands will contain the start times of their commands as opposed to the default + # behavior where they contain the end times of their preceding commands. + typeset -g POWERLEVEL9K_TIME_UPDATE_ON_COMMAND=false + # Custom icon. + # typeset -g POWERLEVEL9K_TIME_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_TIME_PREFIX='%248Fat ' + + # Example of a user-defined prompt segment. Function prompt_example will be called on every + # prompt if `example` prompt segment is added to POWERLEVEL9K_LEFT_PROMPT_ELEMENTS or + # POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS. It displays an icon and orange text greeting the user. + # + # Type `p10k help segment` for documentation and a more sophisticated example. + function prompt_example() { + p10k segment -f 208 -i '⭐' -t 'hello, %n' + } + + # User-defined prompt segments may optionally provide an instant_prompt_* function. Its job + # is to generate the prompt segment for display in instant prompt. See + # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. + # + # Powerlevel10k will call instant_prompt_* at the same time as the regular prompt_* function + # and will record all `p10k segment` calls it makes. When displaying instant prompt, Powerlevel10k + # will replay these calls without actually calling instant_prompt_*. It is imperative that + # instant_prompt_* always makes the same `p10k segment` calls regardless of environment. If this + # rule is not observed, the content of instant prompt will be incorrect. + # + # Usually, you should either not define instant_prompt_* or simply call prompt_* from it. If + # instant_prompt_* is not defined for a segment, the segment won't be shown in instant prompt. + function instant_prompt_example() { + # Since prompt_example always makes the same `p10k segment` calls, we can call it from + # instant_prompt_example. This will give us the same `example` prompt segment in the instant + # and regular prompts. + prompt_example + } + + # User-defined prompt segments can be customized the same way as built-in segments. + # typeset -g POWERLEVEL9K_EXAMPLE_FOREGROUND=208 + # typeset -g POWERLEVEL9K_EXAMPLE_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Transient prompt works similarly to the builtin transient_rprompt option. It trims down prompt + # when accepting a command line. Supported values: + # + # - off: Don't change prompt when accepting a command line. + # - always: Trim down prompt when accepting a command line. + # - same-dir: Trim down prompt when accepting a command line unless this is the first command + # typed after changing current working directory. + typeset -g POWERLEVEL9K_TRANSIENT_PROMPT=off + + # Instant prompt mode. + # + # - off: Disable instant prompt. Choose this if you've tried instant prompt and found + # it incompatible with your zsh configuration files. + # - quiet: Enable instant prompt and don't print warnings when detecting console output + # during zsh initialization. Choose this if you've read and understood + # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. + # - verbose: Enable instant prompt and print a warning when detecting console output during + # zsh initialization. Choose this if you've never tried instant prompt, haven't + # seen the warning, or if you are unsure what this all means. + typeset -g POWERLEVEL9K_INSTANT_PROMPT=verbose + + # Hot reload allows you to change POWERLEVEL9K options after Powerlevel10k has been initialized. + # For example, you can type POWERLEVEL9K_BACKGROUND=red and see your prompt turn red. Hot reload + # can slow down prompt by 1-2 milliseconds, so it's better to keep it turned off unless you + # really need it. + typeset -g POWERLEVEL9K_DISABLE_HOT_RELOAD=true + + # If p10k is already loaded, reload configuration. + # This works even with POWERLEVEL9K_DISABLE_HOT_RELOAD=true. + (( ! $+functions[p10k] )) || p10k reload +} + +# Tell `p10k configure` which file it should overwrite. +typeset -g POWERLEVEL9K_CONFIG_FILE=${${(%):-%x}:a} + +(( ${#p10k_config_opts} )) && setopt ${p10k_config_opts[@]} +'builtin' 'unset' 'p10k_config_opts' diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-lean-8colors.zsh b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-lean-8colors.zsh new file mode 100644 index 00000000..38328c4e --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-lean-8colors.zsh @@ -0,0 +1,1709 @@ +# Config for Powerlevel10k with 8-color lean prompt style. Type `p10k configure` to generate +# your own config based on it. +# +# Tip: Looking for a nice color? Here's a one-liner to print colormap. +# +# for i in {0..255}; do print -Pn "%K{$i} %k%F{$i}${(l:3::0:)i}%f " ${${(M)$((i%6)):#3}:+$'\n'}; done + +# Temporarily change options. +'builtin' 'local' '-a' 'p10k_config_opts' +[[ ! -o 'aliases' ]] || p10k_config_opts+=('aliases') +[[ ! -o 'sh_glob' ]] || p10k_config_opts+=('sh_glob') +[[ ! -o 'no_brace_expand' ]] || p10k_config_opts+=('no_brace_expand') +'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand' + +() { + emulate -L zsh -o extended_glob + + # Unset all configuration options. This allows you to apply configuration changes without + # restarting zsh. Edit ~/.p10k.zsh and type `source ~/.p10k.zsh`. + unset -m '(POWERLEVEL9K_*|DEFAULT_USER)~POWERLEVEL9K_GITSTATUS_DIR' + + # Zsh >= 5.1 is required. + [[ $ZSH_VERSION == (5.<1->*|<6->.*) ]] || return + + # The list of segments shown on the left. Fill it with the most important segments. + typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=( + # =========================[ Line #1 ]========================= + # os_icon # os identifier + dir # current directory + vcs # git status + # =========================[ Line #2 ]========================= + newline # \n + prompt_char # prompt symbol + ) + + # The list of segments shown on the right. Fill it with less important segments. + # Right prompt on the last prompt line (where you are typing your commands) gets + # automatically hidden when the input line reaches it. Right prompt above the + # last prompt line gets hidden if it would overlap with left prompt. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=( + # =========================[ Line #1 ]========================= + status # exit code of the last command + command_execution_time # duration of the last command + background_jobs # presence of background jobs + direnv # direnv status (https://direnv.net/) + asdf # asdf version manager (https://github.com/asdf-vm/asdf) + virtualenv # python virtual environment (https://docs.python.org/3/library/venv.html) + anaconda # conda environment (https://conda.io/) + pyenv # python environment (https://github.com/pyenv/pyenv) + goenv # go environment (https://github.com/syndbg/goenv) + nodenv # node.js version from nodenv (https://github.com/nodenv/nodenv) + nvm # node.js version from nvm (https://github.com/nvm-sh/nvm) + nodeenv # node.js environment (https://github.com/ekalinin/nodeenv) + # node_version # node.js version + # go_version # go version (https://golang.org) + # rust_version # rustc version (https://www.rust-lang.org) + # dotnet_version # .NET version (https://dotnet.microsoft.com) + # php_version # php version (https://www.php.net/) + # laravel_version # laravel php framework version (https://laravel.com/) + # java_version # java version (https://www.java.com/) + # package # name@version from package.json (https://docs.npmjs.com/files/package.json) + rbenv # ruby version from rbenv (https://github.com/rbenv/rbenv) + rvm # ruby version from rvm (https://rvm.io) + fvm # flutter version management (https://github.com/leoafarias/fvm) + luaenv # lua version from luaenv (https://github.com/cehoffman/luaenv) + jenv # java version from jenv (https://github.com/jenv/jenv) + plenv # perl version from plenv (https://github.com/tokuhirom/plenv) + perlbrew # perl version from perlbrew (https://github.com/gugod/App-perlbrew) + phpenv # php version from phpenv (https://github.com/phpenv/phpenv) + scalaenv # scala version from scalaenv (https://github.com/scalaenv/scalaenv) + haskell_stack # haskell version from stack (https://haskellstack.org/) + kubecontext # current kubernetes context (https://kubernetes.io/) + terraform # terraform workspace (https://www.terraform.io) + # terraform_version # terraform version (https://www.terraform.io) + aws # aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) + aws_eb_env # aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) + azure # azure account name (https://docs.microsoft.com/en-us/cli/azure) + gcloud # google cloud cli account and project (https://cloud.google.com/) + google_app_cred # google application credentials (https://cloud.google.com/docs/authentication/production) + toolbox # toolbox name (https://github.com/containers/toolbox) + context # user@hostname + nordvpn # nordvpn connection status, linux only (https://nordvpn.com/) + ranger # ranger shell (https://github.com/ranger/ranger) + nnn # nnn shell (https://github.com/jarun/nnn) + lf # lf shell (https://github.com/gokcehan/lf) + xplr # xplr shell (https://github.com/sayanarijit/xplr) + vim_shell # vim shell indicator (:sh) + midnight_commander # midnight commander shell (https://midnight-commander.org/) + nix_shell # nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) + chezmoi_shell # chezmoi shell (https://www.chezmoi.io/) + # vpn_ip # virtual private network indicator + # load # CPU load + # disk_usage # disk usage + # ram # free RAM + # swap # used swap + todo # todo items (https://github.com/todotxt/todo.txt-cli) + timewarrior # timewarrior tracking status (https://timewarrior.net/) + taskwarrior # taskwarrior task count (https://taskwarrior.org/) + per_directory_history # Oh My Zsh per-directory-history local/global indicator + # cpu_arch # CPU architecture + # time # current time + # =========================[ Line #2 ]========================= + newline # \n + # ip # ip address and bandwidth usage for a specified network interface + # public_ip # public IP address + # proxy # system-wide http/https/ftp proxy + # battery # internal battery + # wifi # wifi speed + # example # example user-defined segment (see prompt_example function below) + ) + + # Defines character set used by powerlevel10k. It's best to let `p10k configure` set it for you. + typeset -g POWERLEVEL9K_MODE=nerdfont-complete + # When set to `moderate`, some icons will have an extra space after them. This is meant to avoid + # icon overlap when using non-monospace fonts. When set to `none`, spaces are not added. + typeset -g POWERLEVEL9K_ICON_PADDING=none + + # Basic style options that define the overall look of your prompt. You probably don't want to + # change them. + typeset -g POWERLEVEL9K_BACKGROUND= # transparent background + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_{LEFT,RIGHT}_WHITESPACE= # no surrounding whitespace + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SUBSEGMENT_SEPARATOR=' ' # separate segments with a space + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SEGMENT_SEPARATOR= # no end-of-line symbol + + # When set to true, icons appear before content on both sides of the prompt. When set + # to false, icons go after content. If empty or not set, icons go before content in the left + # prompt and after content in the right prompt. + # + # You can also override it for a specific segment: + # + # POWERLEVEL9K_STATUS_ICON_BEFORE_CONTENT=false + # + # Or for a specific segment in specific state: + # + # POWERLEVEL9K_DIR_NOT_WRITABLE_ICON_BEFORE_CONTENT=false + typeset -g POWERLEVEL9K_ICON_BEFORE_CONTENT=true + + # Add an empty line before each prompt. + typeset -g POWERLEVEL9K_PROMPT_ADD_NEWLINE=true + + # Connect left prompt lines with these symbols. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_PREFIX= + typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_PREFIX= + typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX= + # Connect right prompt lines with these symbols. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_SUFFIX= + typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_SUFFIX= + typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_SUFFIX= + + # The left end of left prompt. + typeset -g POWERLEVEL9K_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL= + # The right end of right prompt. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_LAST_SEGMENT_END_SYMBOL= + + # Ruler, a.k.a. the horizontal line before each prompt. If you set it to true, you'll + # probably want to set POWERLEVEL9K_PROMPT_ADD_NEWLINE=false above and + # POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' ' below. + typeset -g POWERLEVEL9K_SHOW_RULER=false + typeset -g POWERLEVEL9K_RULER_CHAR='─' # reasonable alternative: '·' + typeset -g POWERLEVEL9K_RULER_FOREGROUND=7 + + # Filler between left and right prompt on the first prompt line. You can set it to '·' or '─' + # to make it easier to see the alignment between left and right prompt and to separate prompt + # from command output. It serves the same purpose as ruler (see above) without increasing + # the number of prompt lines. You'll probably want to set POWERLEVEL9K_SHOW_RULER=false + # if using this. You might also like POWERLEVEL9K_PROMPT_ADD_NEWLINE=false for more compact + # prompt. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' ' + if [[ $POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR != ' ' ]]; then + # The color of the filler. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_FOREGROUND=7 + # Add a space between the end of left prompt and the filler. + typeset -g POWERLEVEL9K_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL=' ' + # Add a space between the filler and the start of right prompt. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL=' ' + # Start filler from the edge of the screen if there are no left segments on the first line. + typeset -g POWERLEVEL9K_EMPTY_LINE_LEFT_PROMPT_FIRST_SEGMENT_END_SYMBOL='%{%}' + # End filler on the edge of the screen if there are no right segments on the first line. + typeset -g POWERLEVEL9K_EMPTY_LINE_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL='%{%}' + fi + + #################################[ os_icon: os identifier ]################################## + # OS identifier color. + typeset -g POWERLEVEL9K_OS_ICON_FOREGROUND= + # Custom icon. + # typeset -g POWERLEVEL9K_OS_ICON_CONTENT_EXPANSION='⭐' + + ################################[ prompt_char: prompt symbol ]################################ + # Green prompt symbol if the last command succeeded. + typeset -g POWERLEVEL9K_PROMPT_CHAR_OK_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=2 + # Red prompt symbol if the last command failed. + typeset -g POWERLEVEL9K_PROMPT_CHAR_ERROR_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=1 + # Default prompt symbol. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION='❯' + # Prompt symbol in command vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VICMD_CONTENT_EXPANSION='❮' + # Prompt symbol in visual vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIVIS_CONTENT_EXPANSION='V' + # Prompt symbol in overwrite vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIOWR_CONTENT_EXPANSION='▶' + typeset -g POWERLEVEL9K_PROMPT_CHAR_OVERWRITE_STATE=true + # No line terminator if prompt_char is the last segment. + typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL='' + # No line introducer if prompt_char is the first segment. + typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL= + + ##################################[ dir: current directory ]################################## + # Default current directory color. + typeset -g POWERLEVEL9K_DIR_FOREGROUND=4 + # If directory is too long, shorten some of its segments to the shortest possible unique + # prefix. The shortened directory can be tab-completed to the original. + typeset -g POWERLEVEL9K_SHORTEN_STRATEGY=truncate_to_unique + # Replace removed segment suffixes with this symbol. + typeset -g POWERLEVEL9K_SHORTEN_DELIMITER= + # Color of the shortened directory segments. + typeset -g POWERLEVEL9K_DIR_SHORTENED_FOREGROUND=4 + # Color of the anchor directory segments. Anchor segments are never shortened. The first + # segment is always an anchor. + typeset -g POWERLEVEL9K_DIR_ANCHOR_FOREGROUND=4 + # Set to true to display anchor directory segments in bold. + typeset -g POWERLEVEL9K_DIR_ANCHOR_BOLD=false + # Don't shorten directories that contain any of these files. They are anchors. + local anchor_files=( + .bzr + .citc + .git + .hg + .node-version + .python-version + .go-version + .ruby-version + .lua-version + .java-version + .perl-version + .php-version + .tool-versions + .shorten_folder_marker + .svn + .terraform + CVS + Cargo.toml + composer.json + go.mod + package.json + stack.yaml + ) + typeset -g POWERLEVEL9K_SHORTEN_FOLDER_MARKER="(${(j:|:)anchor_files})" + # If set to "first" ("last"), remove everything before the first (last) subdirectory that contains + # files matching $POWERLEVEL9K_SHORTEN_FOLDER_MARKER. For example, when the current directory is + # /foo/bar/git_repo/nested_git_repo/baz, prompt will display git_repo/nested_git_repo/baz (first) + # or nested_git_repo/baz (last). This assumes that git_repo and nested_git_repo contain markers + # and other directories don't. + # + # Optionally, "first" and "last" can be followed by ":" where is an integer. + # This moves the truncation point to the right (positive offset) or to the left (negative offset) + # relative to the marker. Plain "first" and "last" are equivalent to "first:0" and "last:0" + # respectively. + typeset -g POWERLEVEL9K_DIR_TRUNCATE_BEFORE_MARKER=false + # Don't shorten this many last directory segments. They are anchors. + typeset -g POWERLEVEL9K_SHORTEN_DIR_LENGTH=1 + # Shorten directory if it's longer than this even if there is space for it. The value can + # be either absolute (e.g., '80') or a percentage of terminal width (e.g, '50%'). If empty, + # directory will be shortened only when prompt doesn't fit or when other parameters demand it + # (see POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS and POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT below). + # If set to `0`, directory will always be shortened to its minimum length. + typeset -g POWERLEVEL9K_DIR_MAX_LENGTH=80 + # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least this + # many columns for typing commands. + typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS=40 + # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least + # COLUMNS * POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT * 0.01 columns for typing commands. + typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT=50 + # If set to true, embed a hyperlink into the directory. Useful for quickly + # opening a directory in the file manager simply by clicking the link. + # Can also be handy when the directory is shortened, as it allows you to see + # the full directory that was used in previous commands. + typeset -g POWERLEVEL9K_DIR_HYPERLINK=false + + # Enable special styling for non-writable directories. See POWERLEVEL9K_LOCK_ICON and + # POWERLEVEL9K_DIR_CLASSES below. + typeset -g POWERLEVEL9K_DIR_SHOW_WRITABLE=v2 + + # Enable special styling for non-writable and non-existent directories. See POWERLEVEL9K_LOCK_ICON + # and POWERLEVEL9K_DIR_CLASSES below. + typeset -g POWERLEVEL9K_DIR_SHOW_WRITABLE=v3 + + # The default icon shown next to non-writable and non-existent directories when + # POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3. + # typeset -g POWERLEVEL9K_LOCK_ICON='⭐' + + # POWERLEVEL9K_DIR_CLASSES allows you to specify custom icons and colors for different + # directories. It must be an array with 3 * N elements. Each triplet consists of: + # + # 1. A pattern against which the current directory ($PWD) is matched. Matching is done with + # extended_glob option enabled. + # 2. Directory class for the purpose of styling. + # 3. An empty string. + # + # Triplets are tried in order. The first triplet whose pattern matches $PWD wins. + # + # If POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3, non-writable and non-existent directories + # acquire class suffix _NOT_WRITABLE and NON_EXISTENT respectively. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_DIR_CLASSES=( + # '~/work(|/*)' WORK '' + # '~(|/*)' HOME '' + # '*' DEFAULT '') + # + # Whenever the current directory is ~/work or a subdirectory of ~/work, it gets styled with one + # of the following classes depending on its writability and existence: WORK, WORK_NOT_WRITABLE or + # WORK_NON_EXISTENT. + # + # Simply assigning classes to directories doesn't have any visible effects. It merely gives you an + # option to define custom colors and icons for different directory classes. + # + # # Styling for WORK. + # typeset -g POWERLEVEL9K_DIR_WORK_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_DIR_WORK_FOREGROUND=4 + # typeset -g POWERLEVEL9K_DIR_WORK_SHORTENED_FOREGROUND=4 + # typeset -g POWERLEVEL9K_DIR_WORK_ANCHOR_FOREGROUND=4 + # + # # Styling for WORK_NOT_WRITABLE. + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND=4 + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_SHORTENED_FOREGROUND=4 + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_ANCHOR_FOREGROUND=4# + # + # Styling for WORK_NON_EXISTENT. + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_FOREGROUND=4 + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_SHORTENED_FOREGROUND=4 + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_ANCHOR_FOREGROUND=4 + # + # If a styling parameter isn't explicitly defined for some class, it falls back to the classless + # parameter. For example, if POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND is not set, it falls + # back to POWERLEVEL9K_DIR_FOREGROUND. + # + # typeset -g POWERLEVEL9K_DIR_CLASSES=() + + # Custom prefix. + # typeset -g POWERLEVEL9K_DIR_PREFIX='%fin ' + + #####################################[ vcs: git status ]###################################### + # Branch icon. Set this parameter to '\UE0A0 ' for the popular Powerline branch icon. + typeset -g POWERLEVEL9K_VCS_BRANCH_ICON= + + # Untracked files icon. It's really a question mark, your font isn't broken. + # Change the value of this parameter to show a different icon. + typeset -g POWERLEVEL9K_VCS_UNTRACKED_ICON='?' + + # Formatter for Git status. + # + # Example output: master wip ⇣42⇡42 *42 merge ~42 +42 !42 ?42. + # + # You can edit the function to customize how Git status looks. + # + # VCS_STATUS_* parameters are set by gitstatus plugin. See reference: + # https://github.com/romkatv/gitstatus/blob/master/gitstatus.plugin.zsh. + function my_git_formatter() { + emulate -L zsh + + if [[ -n $P9K_CONTENT ]]; then + # If P9K_CONTENT is not empty, use it. It's either "loading" or from vcs_info (not from + # gitstatus plugin). VCS_STATUS_* parameters are not available in this case. + typeset -g my_git_format=$P9K_CONTENT + return + fi + + if (( $1 )); then + # Styling for up-to-date Git status. + local meta='%f' # default foreground + local clean='%2F' # green foreground + local modified='%3F' # yellow foreground + local untracked='%4F' # blue foreground + local conflicted='%1F' # red foreground + else + # Styling for incomplete and stale Git status. + local meta='%f' # default foreground + local clean='%f' # default foreground + local modified='%f' # default foreground + local untracked='%f' # default foreground + local conflicted='%f' # default foreground + fi + + local res + + if [[ -n $VCS_STATUS_LOCAL_BRANCH ]]; then + local branch=${(V)VCS_STATUS_LOCAL_BRANCH} + # If local branch name is at most 32 characters long, show it in full. + # Otherwise show the first 12 … the last 12. + # Tip: To always show local branch name in full without truncation, delete the next line. + (( $#branch > 32 )) && branch[13,-13]="…" # <-- this line + res+="${clean}${(g::)POWERLEVEL9K_VCS_BRANCH_ICON}${branch//\%/%%}" + fi + + if [[ -n $VCS_STATUS_TAG + # Show tag only if not on a branch. + # Tip: To always show tag, delete the next line. + && -z $VCS_STATUS_LOCAL_BRANCH # <-- this line + ]]; then + local tag=${(V)VCS_STATUS_TAG} + # If tag name is at most 32 characters long, show it in full. + # Otherwise show the first 12 … the last 12. + # Tip: To always show tag name in full without truncation, delete the next line. + (( $#tag > 32 )) && tag[13,-13]="…" # <-- this line + res+="${meta}#${clean}${tag//\%/%%}" + fi + + # Display the current Git commit if there is no branch and no tag. + # Tip: To always display the current Git commit, delete the next line. + [[ -z $VCS_STATUS_LOCAL_BRANCH && -z $VCS_STATUS_TAG ]] && # <-- this line + res+="${meta}@${clean}${VCS_STATUS_COMMIT[1,8]}" + + # Show tracking branch name if it differs from local branch. + if [[ -n ${VCS_STATUS_REMOTE_BRANCH:#$VCS_STATUS_LOCAL_BRANCH} ]]; then + res+="${meta}:${clean}${(V)VCS_STATUS_REMOTE_BRANCH//\%/%%}" + fi + + # Display "wip" if the latest commit's summary contains "wip" or "WIP". + if [[ $VCS_STATUS_COMMIT_SUMMARY == (|*[^[:alnum:]])(wip|WIP)(|[^[:alnum:]]*) ]]; then + res+=" ${modified}wip" + fi + + if (( VCS_STATUS_COMMITS_AHEAD || VCS_STATUS_COMMITS_BEHIND )); then + # ⇣42 if behind the remote. + (( VCS_STATUS_COMMITS_BEHIND )) && res+=" ${clean}⇣${VCS_STATUS_COMMITS_BEHIND}" + # ⇡42 if ahead of the remote; no leading space if also behind the remote: ⇣42⇡42. + (( VCS_STATUS_COMMITS_AHEAD && !VCS_STATUS_COMMITS_BEHIND )) && res+=" " + (( VCS_STATUS_COMMITS_AHEAD )) && res+="${clean}⇡${VCS_STATUS_COMMITS_AHEAD}" + elif [[ -n $VCS_STATUS_REMOTE_BRANCH ]]; then + # Tip: Uncomment the next line to display '=' if up to date with the remote. + # res+=" ${clean}=" + fi + + # ⇠42 if behind the push remote. + (( VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=" ${clean}⇠${VCS_STATUS_PUSH_COMMITS_BEHIND}" + (( VCS_STATUS_PUSH_COMMITS_AHEAD && !VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=" " + # ⇢42 if ahead of the push remote; no leading space if also behind: ⇠42⇢42. + (( VCS_STATUS_PUSH_COMMITS_AHEAD )) && res+="${clean}⇢${VCS_STATUS_PUSH_COMMITS_AHEAD}" + # *42 if have stashes. + (( VCS_STATUS_STASHES )) && res+=" ${clean}*${VCS_STATUS_STASHES}" + # 'merge' if the repo is in an unusual state. + [[ -n $VCS_STATUS_ACTION ]] && res+=" ${conflicted}${VCS_STATUS_ACTION}" + # ~42 if have merge conflicts. + (( VCS_STATUS_NUM_CONFLICTED )) && res+=" ${conflicted}~${VCS_STATUS_NUM_CONFLICTED}" + # +42 if have staged changes. + (( VCS_STATUS_NUM_STAGED )) && res+=" ${modified}+${VCS_STATUS_NUM_STAGED}" + # !42 if have unstaged changes. + (( VCS_STATUS_NUM_UNSTAGED )) && res+=" ${modified}!${VCS_STATUS_NUM_UNSTAGED}" + # ?42 if have untracked files. It's really a question mark, your font isn't broken. + # See POWERLEVEL9K_VCS_UNTRACKED_ICON above if you want to use a different icon. + # Remove the next line if you don't want to see untracked files at all. + (( VCS_STATUS_NUM_UNTRACKED )) && res+=" ${untracked}${(g::)POWERLEVEL9K_VCS_UNTRACKED_ICON}${VCS_STATUS_NUM_UNTRACKED}" + # "─" if the number of unstaged files is unknown. This can happen due to + # POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY (see below) being set to a non-negative number lower + # than the number of files in the Git index, or due to bash.showDirtyState being set to false + # in the repository config. The number of staged and untracked files may also be unknown + # in this case. + (( VCS_STATUS_HAS_UNSTAGED == -1 )) && res+=" ${modified}─" + + typeset -g my_git_format=$res + } + functions -M my_git_formatter 2>/dev/null + + # Don't count the number of unstaged, untracked and conflicted files in Git repositories with + # more than this many files in the index. Negative value means infinity. + # + # If you are working in Git repositories with tens of millions of files and seeing performance + # sagging, try setting POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY to a number lower than the output + # of `git ls-files | wc -l`. Alternatively, add `bash.showDirtyState = false` to the repository's + # config: `git config bash.showDirtyState false`. + typeset -g POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY=-1 + + # Don't show Git status in prompt for repositories whose workdir matches this pattern. + # For example, if set to '~', the Git repository at $HOME/.git will be ignored. + # Multiple patterns can be combined with '|': '~(|/foo)|/bar/baz/*'. + typeset -g POWERLEVEL9K_VCS_DISABLED_WORKDIR_PATTERN='~' + + # Disable the default Git status formatting. + typeset -g POWERLEVEL9K_VCS_DISABLE_GITSTATUS_FORMATTING=true + # Install our own Git status formatter. + typeset -g POWERLEVEL9K_VCS_CONTENT_EXPANSION='${$((my_git_formatter(1)))+${my_git_format}}' + typeset -g POWERLEVEL9K_VCS_LOADING_CONTENT_EXPANSION='${$((my_git_formatter(0)))+${my_git_format}}' + # Enable counters for staged, unstaged, etc. + typeset -g POWERLEVEL9K_VCS_{STAGED,UNSTAGED,UNTRACKED,CONFLICTED,COMMITS_AHEAD,COMMITS_BEHIND}_MAX_NUM=-1 + + # Icon color. + typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_COLOR=2 + typeset -g POWERLEVEL9K_VCS_LOADING_VISUAL_IDENTIFIER_COLOR= + # Custom icon. + # typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_VCS_PREFIX='%fon ' + + # Show status of repositories of these types. You can add svn and/or hg if you are + # using them. If you do, your prompt may become slow even when your current directory + # isn't in an svn or hg repository. + typeset -g POWERLEVEL9K_VCS_BACKENDS=(git) + + # These settings are used for repositories other than Git or when gitstatusd fails and + # Powerlevel10k has to fall back to using vcs_info. + typeset -g POWERLEVEL9K_VCS_CLEAN_FOREGROUND=2 + typeset -g POWERLEVEL9K_VCS_UNTRACKED_FOREGROUND=2 + typeset -g POWERLEVEL9K_VCS_MODIFIED_FOREGROUND=3 + + ##########################[ status: exit code of the last command ]########################### + # Enable OK_PIPE, ERROR_PIPE and ERROR_SIGNAL status states to allow us to enable, disable and + # style them independently from the regular OK and ERROR state. + typeset -g POWERLEVEL9K_STATUS_EXTENDED_STATES=true + + # Status on success. No content, just an icon. No need to show it if prompt_char is enabled as + # it will signify success by turning green. + typeset -g POWERLEVEL9K_STATUS_OK=false + typeset -g POWERLEVEL9K_STATUS_OK_FOREGROUND=2 + typeset -g POWERLEVEL9K_STATUS_OK_VISUAL_IDENTIFIER_EXPANSION='✔' + + # Status when some part of a pipe command fails but the overall exit status is zero. It may look + # like this: 1|0. + typeset -g POWERLEVEL9K_STATUS_OK_PIPE=true + typeset -g POWERLEVEL9K_STATUS_OK_PIPE_FOREGROUND=2 + typeset -g POWERLEVEL9K_STATUS_OK_PIPE_VISUAL_IDENTIFIER_EXPANSION='✔' + + # Status when it's just an error code (e.g., '1'). No need to show it if prompt_char is enabled as + # it will signify error by turning red. + typeset -g POWERLEVEL9K_STATUS_ERROR=false + typeset -g POWERLEVEL9K_STATUS_ERROR_FOREGROUND=1 + typeset -g POWERLEVEL9K_STATUS_ERROR_VISUAL_IDENTIFIER_EXPANSION='✘' + + # Status when the last command was terminated by a signal. + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL=true + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_FOREGROUND=1 + # Use terse signal names: "INT" instead of "SIGINT(2)". + typeset -g POWERLEVEL9K_STATUS_VERBOSE_SIGNAME=false + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_VISUAL_IDENTIFIER_EXPANSION='✘' + + # Status when some part of a pipe command fails and the overall exit status is also non-zero. + # It may look like this: 1|0. + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE=true + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_FOREGROUND=1 + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_VISUAL_IDENTIFIER_EXPANSION='✘' + + ###################[ command_execution_time: duration of the last command ]################### + # Show duration of the last command if takes at least this many seconds. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD=3 + # Show this many fractional digits. Zero means round to seconds. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PRECISION=0 + # Execution time color. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FOREGROUND=3 + # Duration format: 1d 2h 3m 4s. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FORMAT='d h m s' + # Custom icon. + # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PREFIX='%ftook ' + + #######################[ background_jobs: presence of background jobs ]####################### + # Don't show the number of background jobs. + typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VERBOSE=false + # Background jobs color. + typeset -g POWERLEVEL9K_BACKGROUND_JOBS_FOREGROUND=1 + # Custom icon. + # typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######################[ direnv: direnv status (https://direnv.net/) ]######################## + # Direnv color. + typeset -g POWERLEVEL9K_DIRENV_FOREGROUND=3 + # Custom icon. + # typeset -g POWERLEVEL9K_DIRENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###############[ asdf: asdf version manager (https://github.com/asdf-vm/asdf) ]############### + # Default asdf color. Only used to display tools for which there is no color override (see below). + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_FOREGROUND. + typeset -g POWERLEVEL9K_ASDF_FOREGROUND=6 + + # There are four parameters that can be used to hide asdf tools. Each parameter describes + # conditions under which a tool gets hidden. Parameters can hide tools but not unhide them. If at + # least one parameter decides to hide a tool, that tool gets hidden. If no parameter decides to + # hide a tool, it gets shown. + # + # Special note on the difference between POWERLEVEL9K_ASDF_SOURCES and + # POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW. Consider the effect of the following commands: + # + # asdf local python 3.8.1 + # asdf global python 3.8.1 + # + # After running both commands the current python version is 3.8.1 and its source is "local" as + # it takes precedence over "global". If POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW is set to false, + # it'll hide python version in this case because 3.8.1 is the same as the global version. + # POWERLEVEL9K_ASDF_SOURCES will hide python version only if the value of this parameter doesn't + # contain "local". + + # Hide tool versions that don't come from one of these sources. + # + # Available sources: + # + # - shell `asdf current` says "set by ASDF_${TOOL}_VERSION environment variable" + # - local `asdf current` says "set by /some/not/home/directory/file" + # - global `asdf current` says "set by /home/username/file" + # + # Note: If this parameter is set to (shell local global), it won't hide tools. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SOURCES. + typeset -g POWERLEVEL9K_ASDF_SOURCES=(shell local global) + + # If set to false, hide tool versions that are the same as global. + # + # Note: The name of this parameter doesn't reflect its meaning at all. + # Note: If this parameter is set to true, it won't hide tools. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_PROMPT_ALWAYS_SHOW. + typeset -g POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW=false + + # If set to false, hide tool versions that are equal to "system". + # + # Note: If this parameter is set to true, it won't hide tools. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_SYSTEM. + typeset -g POWERLEVEL9K_ASDF_SHOW_SYSTEM=true + + # If set to non-empty value, hide tools unless there is a file matching the specified file pattern + # in the current directory, or its parent directory, or its grandparent directory, and so on. + # + # Note: If this parameter is set to empty value, it won't hide tools. + # Note: SHOW_ON_UPGLOB isn't specific to asdf. It works with all prompt segments. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_ON_UPGLOB. + # + # Example: Hide nodejs version when there is no package.json and no *.js files in the current + # directory, in `..`, in `../..` and so on. + # + # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.js|package.json' + typeset -g POWERLEVEL9K_ASDF_SHOW_ON_UPGLOB= + + # Ruby version from asdf. + typeset -g POWERLEVEL9K_ASDF_RUBY_FOREGROUND=1 + # typeset -g POWERLEVEL9K_ASDF_RUBY_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_RUBY_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Python version from asdf. + typeset -g POWERLEVEL9K_ASDF_PYTHON_FOREGROUND=6 + # typeset -g POWERLEVEL9K_ASDF_PYTHON_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_PYTHON_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Go version from asdf. + typeset -g POWERLEVEL9K_ASDF_GOLANG_FOREGROUND=6 + # typeset -g POWERLEVEL9K_ASDF_GOLANG_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_GOLANG_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Node.js version from asdf. + typeset -g POWERLEVEL9K_ASDF_NODEJS_FOREGROUND=2 + # typeset -g POWERLEVEL9K_ASDF_NODEJS_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Rust version from asdf. + typeset -g POWERLEVEL9K_ASDF_RUST_FOREGROUND=4 + # typeset -g POWERLEVEL9K_ASDF_RUST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_RUST_SHOW_ON_UPGLOB='*.foo|*.bar' + + # .NET Core version from asdf. + typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_FOREGROUND=5 + # typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Flutter version from asdf. + typeset -g POWERLEVEL9K_ASDF_FLUTTER_FOREGROUND=4 + # typeset -g POWERLEVEL9K_ASDF_FLUTTER_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_FLUTTER_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Lua version from asdf. + typeset -g POWERLEVEL9K_ASDF_LUA_FOREGROUND=4 + # typeset -g POWERLEVEL9K_ASDF_LUA_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_LUA_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Java version from asdf. + typeset -g POWERLEVEL9K_ASDF_JAVA_FOREGROUND=4 + # typeset -g POWERLEVEL9K_ASDF_JAVA_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_JAVA_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Perl version from asdf. + typeset -g POWERLEVEL9K_ASDF_PERL_FOREGROUND=6 + # typeset -g POWERLEVEL9K_ASDF_PERL_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_PERL_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Erlang version from asdf. + typeset -g POWERLEVEL9K_ASDF_ERLANG_FOREGROUND=1 + # typeset -g POWERLEVEL9K_ASDF_ERLANG_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_ERLANG_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Elixir version from asdf. + typeset -g POWERLEVEL9K_ASDF_ELIXIR_FOREGROUND=5 + # typeset -g POWERLEVEL9K_ASDF_ELIXIR_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_ELIXIR_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Postgres version from asdf. + typeset -g POWERLEVEL9K_ASDF_POSTGRES_FOREGROUND=6 + # typeset -g POWERLEVEL9K_ASDF_POSTGRES_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_POSTGRES_SHOW_ON_UPGLOB='*.foo|*.bar' + + # PHP version from asdf. + typeset -g POWERLEVEL9K_ASDF_PHP_FOREGROUND=5 + # typeset -g POWERLEVEL9K_ASDF_PHP_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_PHP_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Haskell version from asdf. + typeset -g POWERLEVEL9K_ASDF_HASKELL_FOREGROUND=3 + # typeset -g POWERLEVEL9K_ASDF_HASKELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_HASKELL_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Julia version from asdf. + typeset -g POWERLEVEL9K_ASDF_JULIA_FOREGROUND=2 + # typeset -g POWERLEVEL9K_ASDF_JULIA_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_JULIA_SHOW_ON_UPGLOB='*.foo|*.bar' + + ##########[ nordvpn: nordvpn connection status, linux only (https://nordvpn.com/) ]########### + # NordVPN connection indicator color. + typeset -g POWERLEVEL9K_NORDVPN_FOREGROUND=6 + # Hide NordVPN connection indicator when not connected. + typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_CONTENT_EXPANSION= + typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_VISUAL_IDENTIFIER_EXPANSION= + # Custom icon. + # typeset -g POWERLEVEL9K_NORDVPN_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #################[ ranger: ranger shell (https://github.com/ranger/ranger) ]################## + # Ranger shell color. + typeset -g POWERLEVEL9K_RANGER_FOREGROUND=3 + # Custom icon. + # typeset -g POWERLEVEL9K_RANGER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################[ nnn: nnn shell (https://github.com/jarun/nnn) ]####################### + # Nnn shell color. + typeset -g POWERLEVEL9K_NNN_FOREGROUND=3 + # Custom icon. + # typeset -g POWERLEVEL9K_NNN_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################[ lf: lf shell (https://github.com/gokcehan/lf) ]####################### + # lf shell color. + typeset -g POWERLEVEL9K_LF_FOREGROUND=3 + # Custom icon. + # typeset -g POWERLEVEL9K_LF_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################[ xplr: xplr shell (https://github.com/sayanarijit/xplr) ]################## + # xplr shell color. + typeset -g POWERLEVEL9K_XPLR_FOREGROUND=3 + # Custom icon. + # typeset -g POWERLEVEL9K_XPLR_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########################[ vim_shell: vim shell indicator (:sh) ]########################### + # Vim shell indicator color. + typeset -g POWERLEVEL9K_VIM_SHELL_FOREGROUND=3 + # Custom icon. + # typeset -g POWERLEVEL9K_VIM_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######[ midnight_commander: midnight commander shell (https://midnight-commander.org/) ]###### + # Midnight Commander shell color. + typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_FOREGROUND=3 + # Custom icon. + # typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #[ nix_shell: nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) ]## + # Nix shell color. + typeset -g POWERLEVEL9K_NIX_SHELL_FOREGROUND=4 + + # Display the icon of nix_shell if PATH contains a subdirectory of /nix/store. + # typeset -g POWERLEVEL9K_NIX_SHELL_INFER_FROM_PATH=false + + # Tip: If you want to see just the icon without "pure" and "impure", uncomment the next line. + # typeset -g POWERLEVEL9K_NIX_SHELL_CONTENT_EXPANSION= + + # Custom icon. + # typeset -g POWERLEVEL9K_NIX_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################[ chezmoi_shell: chezmoi shell (https://www.chezmoi.io/) ]################## + # chezmoi shell color. + typeset -g POWERLEVEL9K_CHEZMOI_SHELL_FOREGROUND=4 + # Custom icon. + # typeset -g POWERLEVEL9K_CHEZMOI_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################################[ disk_usage: disk usage ]################################## + # Colors for different levels of disk usage. + typeset -g POWERLEVEL9K_DISK_USAGE_NORMAL_FOREGROUND=2 + typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_FOREGROUND=3 + typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_FOREGROUND=1 + # Thresholds for different levels of disk usage (percentage points). + typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL=90 + typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_LEVEL=95 + # If set to true, hide disk usage when below $POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL percent. + typeset -g POWERLEVEL9K_DISK_USAGE_ONLY_WARNING=false + # Custom icon. + # typeset -g POWERLEVEL9K_DISK_USAGE_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################################[ ram: free RAM ]####################################### + # RAM color. + typeset -g POWERLEVEL9K_RAM_FOREGROUND=2 + # Custom icon. + # typeset -g POWERLEVEL9K_RAM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #####################################[ swap: used swap ]###################################### + # Swap color. + typeset -g POWERLEVEL9K_SWAP_FOREGROUND=3 + # Custom icon. + # typeset -g POWERLEVEL9K_SWAP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################################[ load: CPU load ]###################################### + # Show average CPU load over this many last minutes. Valid values are 1, 5 and 15. + typeset -g POWERLEVEL9K_LOAD_WHICH=5 + # Load color when load is under 50%. + typeset -g POWERLEVEL9K_LOAD_NORMAL_FOREGROUND=2 + # Load color when load is between 50% and 70%. + typeset -g POWERLEVEL9K_LOAD_WARNING_FOREGROUND=3 + # Load color when load is over 70%. + typeset -g POWERLEVEL9K_LOAD_CRITICAL_FOREGROUND=1 + # Custom icon. + # typeset -g POWERLEVEL9K_LOAD_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ todo: todo items (https://github.com/todotxt/todo.txt-cli) ]################ + # Todo color. + typeset -g POWERLEVEL9K_TODO_FOREGROUND=4 + # Hide todo when the total number of tasks is zero. + typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_TOTAL=true + # Hide todo when the number of tasks after filtering is zero. + typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_FILTERED=false + + # Todo format. The following parameters are available within the expansion. + # + # - P9K_TODO_TOTAL_TASK_COUNT The total number of tasks. + # - P9K_TODO_FILTERED_TASK_COUNT The number of tasks after filtering. + # + # These variables correspond to the last line of the output of `todo.sh -p ls`: + # + # TODO: 24 of 42 tasks shown + # + # Here 24 is P9K_TODO_FILTERED_TASK_COUNT and 42 is P9K_TODO_TOTAL_TASK_COUNT. + # + # typeset -g POWERLEVEL9K_TODO_CONTENT_EXPANSION='$P9K_TODO_FILTERED_TASK_COUNT' + + # Custom icon. + # typeset -g POWERLEVEL9K_TODO_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ timewarrior: timewarrior tracking status (https://timewarrior.net/) ]############ + # Timewarrior color. + typeset -g POWERLEVEL9K_TIMEWARRIOR_FOREGROUND=4 + # If the tracked task is longer than 24 characters, truncate and append "…". + # Tip: To always display tasks without truncation, delete the following parameter. + # Tip: To hide task names and display just the icon when time tracking is enabled, set the + # value of the following parameter to "". + typeset -g POWERLEVEL9K_TIMEWARRIOR_CONTENT_EXPANSION='${P9K_CONTENT:0:24}${${P9K_CONTENT:24}:+…}' + + # Custom icon. + # typeset -g POWERLEVEL9K_TIMEWARRIOR_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##############[ taskwarrior: taskwarrior task count (https://taskwarrior.org/) ]############## + # Taskwarrior color. + typeset -g POWERLEVEL9K_TASKWARRIOR_FOREGROUND=6 + + # Taskwarrior segment format. The following parameters are available within the expansion. + # + # - P9K_TASKWARRIOR_PENDING_COUNT The number of pending tasks: `task +PENDING count`. + # - P9K_TASKWARRIOR_OVERDUE_COUNT The number of overdue tasks: `task +OVERDUE count`. + # + # Zero values are represented as empty parameters. + # + # The default format: + # + # '${P9K_TASKWARRIOR_OVERDUE_COUNT:+"!$P9K_TASKWARRIOR_OVERDUE_COUNT/"}$P9K_TASKWARRIOR_PENDING_COUNT' + # + # typeset -g POWERLEVEL9K_TASKWARRIOR_CONTENT_EXPANSION='$P9K_TASKWARRIOR_PENDING_COUNT' + + # Custom icon. + # typeset -g POWERLEVEL9K_TASKWARRIOR_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######[ per_directory_history: Oh My Zsh per-directory-history local/global indicator ]####### + # Color when using local/global history. + typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_FOREGROUND=5 + typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_FOREGROUND=3 + + # Tip: Uncomment the next two lines to hide "local"/"global" text and leave just the icon. + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_CONTENT_EXPANSION='' + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_CONTENT_EXPANSION='' + + # Custom icon. + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################################[ cpu_arch: CPU architecture ]################################ + # CPU architecture color. + typeset -g POWERLEVEL9K_CPU_ARCH_FOREGROUND=3 + + # Hide the segment when on a specific CPU architecture. + # typeset -g POWERLEVEL9K_CPU_ARCH_X86_64_CONTENT_EXPANSION= + # typeset -g POWERLEVEL9K_CPU_ARCH_X86_64_VISUAL_IDENTIFIER_EXPANSION= + + # Custom icon. + # typeset -g POWERLEVEL9K_CPU_ARCH_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################################[ context: user@hostname ]################################## + # Context color when running with privileges. + typeset -g POWERLEVEL9K_CONTEXT_ROOT_FOREGROUND=1 + # Context color in SSH without privileges. + typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_FOREGROUND=7 + # Default context color (no privileges, no SSH). + typeset -g POWERLEVEL9K_CONTEXT_FOREGROUND=7 + + # Context format when running with privileges: bold user@hostname. + typeset -g POWERLEVEL9K_CONTEXT_ROOT_TEMPLATE='%B%n@%m' + # Context format when in SSH without privileges: user@hostname. + typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_TEMPLATE='%n@%m' + # Default context format (no privileges, no SSH): user@hostname. + typeset -g POWERLEVEL9K_CONTEXT_TEMPLATE='%n@%m' + + # Don't show context unless running with privileges or in SSH. + # Tip: Remove the next line to always show context. + typeset -g POWERLEVEL9K_CONTEXT_{DEFAULT,SUDO}_{CONTENT,VISUAL_IDENTIFIER}_EXPANSION= + + # Custom icon. + # typeset -g POWERLEVEL9K_CONTEXT_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_CONTEXT_PREFIX='%fwith ' + + ###[ virtualenv: python virtual environment (https://docs.python.org/3/library/venv.html) ]### + # Python virtual environment color. + typeset -g POWERLEVEL9K_VIRTUALENV_FOREGROUND=6 + # Don't show Python version next to the virtual environment name. + typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_PYTHON_VERSION=false + # If set to "false", won't show virtualenv if pyenv is already shown. + # If set to "if-different", won't show virtualenv if it's the same as pyenv. + typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_WITH_PYENV=false + # Separate environment name from Python version only with a space. + typeset -g POWERLEVEL9K_VIRTUALENV_{LEFT,RIGHT}_DELIMITER= + # Custom icon. + # typeset -g POWERLEVEL9K_VIRTUALENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #####################[ anaconda: conda environment (https://conda.io/) ]###################### + # Anaconda environment color. + typeset -g POWERLEVEL9K_ANACONDA_FOREGROUND=6 + + # Anaconda segment format. The following parameters are available within the expansion. + # + # - CONDA_PREFIX Absolute path to the active Anaconda/Miniconda environment. + # - CONDA_DEFAULT_ENV Name of the active Anaconda/Miniconda environment. + # - CONDA_PROMPT_MODIFIER Configurable prompt modifier (see below). + # - P9K_ANACONDA_PYTHON_VERSION Current python version (python --version). + # + # CONDA_PROMPT_MODIFIER can be configured with the following command: + # + # conda config --set env_prompt '({default_env}) ' + # + # The last argument is a Python format string that can use the following variables: + # + # - prefix The same as CONDA_PREFIX. + # - default_env The same as CONDA_DEFAULT_ENV. + # - name The last segment of CONDA_PREFIX. + # - stacked_env Comma-separated list of names in the environment stack. The first element is + # always the same as default_env. + # + # Note: '({default_env}) ' is the default value of env_prompt. + # + # The default value of POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION expands to $CONDA_PROMPT_MODIFIER + # without the surrounding parentheses, or to the last path component of CONDA_PREFIX if the former + # is empty. + typeset -g POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION='${${${${CONDA_PROMPT_MODIFIER#\(}% }%\)}:-${CONDA_PREFIX:t}}' + + # Custom icon. + # typeset -g POWERLEVEL9K_ANACONDA_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ pyenv: python environment (https://github.com/pyenv/pyenv) ]################ + # Pyenv color. + typeset -g POWERLEVEL9K_PYENV_FOREGROUND=6 + # Hide python version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_PYENV_SOURCES=(shell local global) + # If set to false, hide python version if it's the same as global: + # $(pyenv version-name) == $(pyenv global). + typeset -g POWERLEVEL9K_PYENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide python version if it's equal to "system". + typeset -g POWERLEVEL9K_PYENV_SHOW_SYSTEM=true + + # Pyenv segment format. The following parameters are available within the expansion. + # + # - P9K_CONTENT Current pyenv environment (pyenv version-name). + # - P9K_PYENV_PYTHON_VERSION Current python version (python --version). + # + # The default format has the following logic: + # + # 1. Display just "$P9K_CONTENT" if it's equal to "$P9K_PYENV_PYTHON_VERSION" or + # starts with "$P9K_PYENV_PYTHON_VERSION/". + # 2. Otherwise display "$P9K_CONTENT $P9K_PYENV_PYTHON_VERSION". + typeset -g POWERLEVEL9K_PYENV_CONTENT_EXPANSION='${P9K_CONTENT}${${P9K_CONTENT:#$P9K_PYENV_PYTHON_VERSION(|/*)}:+ $P9K_PYENV_PYTHON_VERSION}' + + # Custom icon. + # typeset -g POWERLEVEL9K_PYENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ goenv: go environment (https://github.com/syndbg/goenv) ]################ + # Goenv color. + typeset -g POWERLEVEL9K_GOENV_FOREGROUND=6 + # Hide go version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_GOENV_SOURCES=(shell local global) + # If set to false, hide go version if it's the same as global: + # $(goenv version-name) == $(goenv global). + typeset -g POWERLEVEL9K_GOENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide go version if it's equal to "system". + typeset -g POWERLEVEL9K_GOENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_GOENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ nodenv: node.js version from nodenv (https://github.com/nodenv/nodenv) ]########## + # Nodenv color. + typeset -g POWERLEVEL9K_NODENV_FOREGROUND=2 + # Hide node version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_NODENV_SOURCES=(shell local global) + # If set to false, hide node version if it's the same as global: + # $(nodenv version-name) == $(nodenv global). + typeset -g POWERLEVEL9K_NODENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide node version if it's equal to "system". + typeset -g POWERLEVEL9K_NODENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_NODENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##############[ nvm: node.js version from nvm (https://github.com/nvm-sh/nvm) ]############### + # Nvm color. + typeset -g POWERLEVEL9K_NVM_FOREGROUND=2 + # If set to false, hide node version if it's the same as default: + # $(nvm version current) == $(nvm version default). + typeset -g POWERLEVEL9K_NVM_PROMPT_ALWAYS_SHOW=false + # If set to false, hide node version if it's equal to "system". + typeset -g POWERLEVEL9K_NVM_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_NVM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ############[ nodeenv: node.js environment (https://github.com/ekalinin/nodeenv) ]############ + # Nodeenv color. + typeset -g POWERLEVEL9K_NODEENV_FOREGROUND=2 + # Don't show Node version next to the environment name. + typeset -g POWERLEVEL9K_NODEENV_SHOW_NODE_VERSION=false + # Separate environment name from Node version only with a space. + typeset -g POWERLEVEL9K_NODEENV_{LEFT,RIGHT}_DELIMITER= + # Custom icon. + # typeset -g POWERLEVEL9K_NODEENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##############################[ node_version: node.js version ]############################### + # Node version color. + typeset -g POWERLEVEL9K_NODE_VERSION_FOREGROUND=2 + # Show node version only when in a directory tree containing package.json. + typeset -g POWERLEVEL9K_NODE_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_NODE_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######################[ go_version: go version (https://golang.org) ]######################## + # Go version color. + typeset -g POWERLEVEL9K_GO_VERSION_FOREGROUND=6 + # Show go version only when in a go project subdirectory. + typeset -g POWERLEVEL9K_GO_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_GO_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #################[ rust_version: rustc version (https://www.rust-lang.org) ]################## + # Rust version color. + typeset -g POWERLEVEL9K_RUST_VERSION_FOREGROUND=4 + # Show rust version only when in a rust project subdirectory. + typeset -g POWERLEVEL9K_RUST_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_RUST_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###############[ dotnet_version: .NET version (https://dotnet.microsoft.com) ]################ + # .NET version color. + typeset -g POWERLEVEL9K_DOTNET_VERSION_FOREGROUND=5 + # Show .NET version only when in a .NET project subdirectory. + typeset -g POWERLEVEL9K_DOTNET_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_DOTNET_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #####################[ php_version: php version (https://www.php.net/) ]###################### + # PHP version color. + typeset -g POWERLEVEL9K_PHP_VERSION_FOREGROUND=5 + # Show PHP version only when in a PHP project subdirectory. + typeset -g POWERLEVEL9K_PHP_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_PHP_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ laravel_version: laravel php framework version (https://laravel.com/) ]########### + # Laravel version color. + typeset -g POWERLEVEL9K_LARAVEL_VERSION_FOREGROUND=1 + # Custom icon. + # typeset -g POWERLEVEL9K_LARAVEL_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ####################[ java_version: java version (https://www.java.com/) ]#################### + # Java version color. + typeset -g POWERLEVEL9K_JAVA_VERSION_FOREGROUND=4 + # Show java version only when in a java project subdirectory. + typeset -g POWERLEVEL9K_JAVA_VERSION_PROJECT_ONLY=true + # Show brief version. + typeset -g POWERLEVEL9K_JAVA_VERSION_FULL=false + # Custom icon. + # typeset -g POWERLEVEL9K_JAVA_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###[ package: name@version from package.json (https://docs.npmjs.com/files/package.json) ]#### + # Package color. + typeset -g POWERLEVEL9K_PACKAGE_FOREGROUND=6 + # Package format. The following parameters are available within the expansion. + # + # - P9K_PACKAGE_NAME The value of `name` field in package.json. + # - P9K_PACKAGE_VERSION The value of `version` field in package.json. + # + # typeset -g POWERLEVEL9K_PACKAGE_CONTENT_EXPANSION='${P9K_PACKAGE_NAME//\%/%%}@${P9K_PACKAGE_VERSION//\%/%%}' + # Custom icon. + # typeset -g POWERLEVEL9K_PACKAGE_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #############[ rbenv: ruby version from rbenv (https://github.com/rbenv/rbenv) ]############## + # Rbenv color. + typeset -g POWERLEVEL9K_RBENV_FOREGROUND=1 + # Hide ruby version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_RBENV_SOURCES=(shell local global) + # If set to false, hide ruby version if it's the same as global: + # $(rbenv version-name) == $(rbenv global). + typeset -g POWERLEVEL9K_RBENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide ruby version if it's equal to "system". + typeset -g POWERLEVEL9K_RBENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_RBENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######################[ rvm: ruby version from rvm (https://rvm.io) ]######################## + # Rvm color. + typeset -g POWERLEVEL9K_RVM_FOREGROUND=1 + # Don't show @gemset at the end. + typeset -g POWERLEVEL9K_RVM_SHOW_GEMSET=false + # Don't show ruby- at the front. + typeset -g POWERLEVEL9K_RVM_SHOW_PREFIX=false + # Custom icon. + # typeset -g POWERLEVEL9K_RVM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ fvm: flutter version management (https://github.com/leoafarias/fvm) ]############ + # Fvm color. + typeset -g POWERLEVEL9K_FVM_FOREGROUND=4 + # Custom icon. + # typeset -g POWERLEVEL9K_FVM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ luaenv: lua version from luaenv (https://github.com/cehoffman/luaenv) ]########### + # Lua color. + typeset -g POWERLEVEL9K_LUAENV_FOREGROUND=4 + # Hide lua version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_LUAENV_SOURCES=(shell local global) + # If set to false, hide lua version if it's the same as global: + # $(luaenv version-name) == $(luaenv global). + typeset -g POWERLEVEL9K_LUAENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide lua version if it's equal to "system". + typeset -g POWERLEVEL9K_LUAENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_LUAENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###############[ jenv: java version from jenv (https://github.com/jenv/jenv) ]################ + # Java color. + typeset -g POWERLEVEL9K_JENV_FOREGROUND=4 + # Hide java version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_JENV_SOURCES=(shell local global) + # If set to false, hide java version if it's the same as global: + # $(jenv version-name) == $(jenv global). + typeset -g POWERLEVEL9K_JENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide java version if it's equal to "system". + typeset -g POWERLEVEL9K_JENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_JENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ plenv: perl version from plenv (https://github.com/tokuhirom/plenv) ]############ + # Perl color. + typeset -g POWERLEVEL9K_PLENV_FOREGROUND=6 + # Hide perl version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_PLENV_SOURCES=(shell local global) + # If set to false, hide perl version if it's the same as global: + # $(plenv version-name) == $(plenv global). + typeset -g POWERLEVEL9K_PLENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide perl version if it's equal to "system". + typeset -g POWERLEVEL9K_PLENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_PLENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ perlbrew: perl version from perlbrew (https://github.com/gugod/App-perlbrew) ]############ + # Perlbrew color. + typeset -g POWERLEVEL9K_PERLBREW_FOREGROUND=67 + # Show perlbrew version only when in a perl project subdirectory. + typeset -g POWERLEVEL9K_PERLBREW_PROJECT_ONLY=true + # Don't show "perl-" at the front. + typeset -g POWERLEVEL9K_PERLBREW_SHOW_PREFIX=false + # Custom icon. + # typeset -g POWERLEVEL9K_PERLBREW_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ############[ phpenv: php version from phpenv (https://github.com/phpenv/phpenv) ]############ + # PHP color. + typeset -g POWERLEVEL9K_PHPENV_FOREGROUND=5 + # Hide php version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_PHPENV_SOURCES=(shell local global) + # If set to false, hide php version if it's the same as global: + # $(phpenv version-name) == $(phpenv global). + typeset -g POWERLEVEL9K_PHPENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide php version if it's equal to "system". + typeset -g POWERLEVEL9K_PHPENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_PHPENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######[ scalaenv: scala version from scalaenv (https://github.com/scalaenv/scalaenv) ]####### + # Scala color. + typeset -g POWERLEVEL9K_SCALAENV_FOREGROUND=1 + # Hide scala version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_SCALAENV_SOURCES=(shell local global) + # If set to false, hide scala version if it's the same as global: + # $(scalaenv version-name) == $(scalaenv global). + typeset -g POWERLEVEL9K_SCALAENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide scala version if it's equal to "system". + typeset -g POWERLEVEL9K_SCALAENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_SCALAENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ haskell_stack: haskell version from stack (https://haskellstack.org/) ]########### + # Haskell color. + typeset -g POWERLEVEL9K_HASKELL_STACK_FOREGROUND=3 + # Hide haskell version if it doesn't come from one of these sources. + # + # shell: version is set by STACK_YAML + # local: version is set by stack.yaml up the directory tree + # global: version is set by the implicit global project (~/.stack/global-project/stack.yaml) + typeset -g POWERLEVEL9K_HASKELL_STACK_SOURCES=(shell local) + # If set to false, hide haskell version if it's the same as in the implicit global project. + typeset -g POWERLEVEL9K_HASKELL_STACK_ALWAYS_SHOW=true + # Custom icon. + # typeset -g POWERLEVEL9K_HASKELL_STACK_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #############[ kubecontext: current kubernetes context (https://kubernetes.io/) ]############# + # Show kubecontext only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show kubecontext. + typeset -g POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND='kubectl|helm|kubens|kubectx|oc|istioctl|kogito|k9s|helmfile|flux|fluxctl|stern|kubeseal|skaffold|kubent|kubecolor|cmctl|sparkctl' + + # Kubernetes context classes for the purpose of using different colors, icons and expansions with + # different contexts. + # + # POWERLEVEL9K_KUBECONTEXT_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current kubernetes context gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_KUBECONTEXT_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_KUBECONTEXT_CLASSES defines the context class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' DEFAULT) + # + # If your current kubernetes context is "deathray-testing/default", its class is TEST + # because "deathray-testing/default" doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_FOREGROUND=3 + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' DEFAULT) + typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_FOREGROUND=5 + # typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Use POWERLEVEL9K_KUBECONTEXT_CONTENT_EXPANSION to specify the content displayed by kubecontext + # segment. Parameter expansions are very flexible and fast, too. See reference: + # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion. + # + # Within the expansion the following parameters are always available: + # + # - P9K_CONTENT The content that would've been displayed if there was no content + # expansion defined. + # - P9K_KUBECONTEXT_NAME The current context's name. Corresponds to column NAME in the + # output of `kubectl config get-contexts`. + # - P9K_KUBECONTEXT_CLUSTER The current context's cluster. Corresponds to column CLUSTER in the + # output of `kubectl config get-contexts`. + # - P9K_KUBECONTEXT_NAMESPACE The current context's namespace. Corresponds to column NAMESPACE + # in the output of `kubectl config get-contexts`. If there is no + # namespace, the parameter is set to "default". + # - P9K_KUBECONTEXT_USER The current context's user. Corresponds to column AUTHINFO in the + # output of `kubectl config get-contexts`. + # + # If the context points to Google Kubernetes Engine (GKE) or Elastic Kubernetes Service (EKS), + # the following extra parameters are available: + # + # - P9K_KUBECONTEXT_CLOUD_NAME Either "gke" or "eks". + # - P9K_KUBECONTEXT_CLOUD_ACCOUNT Account/project ID. + # - P9K_KUBECONTEXT_CLOUD_ZONE Availability zone. + # - P9K_KUBECONTEXT_CLOUD_CLUSTER Cluster. + # + # P9K_KUBECONTEXT_CLOUD_* parameters are derived from P9K_KUBECONTEXT_CLUSTER. For example, + # if P9K_KUBECONTEXT_CLUSTER is "gke_my-account_us-east1-a_my-cluster-01": + # + # - P9K_KUBECONTEXT_CLOUD_NAME=gke + # - P9K_KUBECONTEXT_CLOUD_ACCOUNT=my-account + # - P9K_KUBECONTEXT_CLOUD_ZONE=us-east1-a + # - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01 + # + # If P9K_KUBECONTEXT_CLUSTER is "arn:aws:eks:us-east-1:123456789012:cluster/my-cluster-01": + # + # - P9K_KUBECONTEXT_CLOUD_NAME=eks + # - P9K_KUBECONTEXT_CLOUD_ACCOUNT=123456789012 + # - P9K_KUBECONTEXT_CLOUD_ZONE=us-east-1 + # - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01 + typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION= + # Show P9K_KUBECONTEXT_CLOUD_CLUSTER if it's not empty and fall back to P9K_KUBECONTEXT_NAME. + POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${P9K_KUBECONTEXT_CLOUD_CLUSTER:-${P9K_KUBECONTEXT_NAME}}' + # Append the current context's namespace if it's not "default". + POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${${:-/$P9K_KUBECONTEXT_NAMESPACE}:#/default}' + + # Custom prefix. + # typeset -g POWERLEVEL9K_KUBECONTEXT_PREFIX='%fat ' + + ################[ terraform: terraform workspace (https://www.terraform.io) ]################# + # Don't show terraform workspace if it's literally "default". + typeset -g POWERLEVEL9K_TERRAFORM_SHOW_DEFAULT=false + # POWERLEVEL9K_TERRAFORM_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current terraform workspace gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_TERRAFORM_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_TERRAFORM_CLASSES defines the workspace class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' OTHER) + # + # If your current terraform workspace is "project_test", its class is TEST because "project_test" + # doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_FOREGROUND=2 + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' OTHER) + typeset -g POWERLEVEL9K_TERRAFORM_OTHER_FOREGROUND=4 + # typeset -g POWERLEVEL9K_TERRAFORM_OTHER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #############[ terraform_version: terraform version (https://www.terraform.io) ]############## + # Terraform version color. + typeset -g POWERLEVEL9K_TERRAFORM_VERSION_FOREGROUND=4 + # Custom icon. + # typeset -g POWERLEVEL9K_TERRAFORM_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #[ aws: aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) ]# + # Show aws only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show aws. + typeset -g POWERLEVEL9K_AWS_SHOW_ON_COMMAND='aws|awless|terraform|pulumi|terragrunt' + + # POWERLEVEL9K_AWS_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current AWS profile gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_AWS_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_AWS_CLASSES defines the profile class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_AWS_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' DEFAULT) + # + # If your current AWS profile is "company_test", its class is TEST + # because "company_test" doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_AWS_TEST_FOREGROUND=2 + # typeset -g POWERLEVEL9K_AWS_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_AWS_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_AWS_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' DEFAULT) + typeset -g POWERLEVEL9K_AWS_DEFAULT_FOREGROUND=3 + # typeset -g POWERLEVEL9K_AWS_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # AWS segment format. The following parameters are available within the expansion. + # + # - P9K_AWS_PROFILE The name of the current AWS profile. + # - P9K_AWS_REGION The region associated with the current AWS profile. + typeset -g POWERLEVEL9K_AWS_CONTENT_EXPANSION='${P9K_AWS_PROFILE//\%/%%}${P9K_AWS_REGION:+ ${P9K_AWS_REGION//\%/%%}}' + + #[ aws_eb_env: aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) ]# + # AWS Elastic Beanstalk environment color. + typeset -g POWERLEVEL9K_AWS_EB_ENV_FOREGROUND=2 + # Custom icon. + # typeset -g POWERLEVEL9K_AWS_EB_ENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ azure: azure account name (https://docs.microsoft.com/en-us/cli/azure) ]########## + # Show azure only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show azure. + typeset -g POWERLEVEL9K_AZURE_SHOW_ON_COMMAND='az|terraform|pulumi|terragrunt' + + # POWERLEVEL9K_AZURE_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current azure account name gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_AZURE_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_AZURE_CLASSES defines the account class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_AZURE_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' OTHER) + # + # If your current azure account is "company_test", its class is TEST because "company_test" + # doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_AZURE_TEST_FOREGROUND=2 + # typeset -g POWERLEVEL9K_AZURE_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_AZURE_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_AZURE_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' OTHER) + + # Azure account name color. + typeset -g POWERLEVEL9K_AZURE_OTHER_FOREGROUND=4 + # Custom icon. + # typeset -g POWERLEVEL9K_AZURE_OTHER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ gcloud: google cloud account and project (https://cloud.google.com/) ]########### + # Show gcloud only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show gcloud. + typeset -g POWERLEVEL9K_GCLOUD_SHOW_ON_COMMAND='gcloud|gcs|gsutil' + # Google cloud color. + typeset -g POWERLEVEL9K_GCLOUD_FOREGROUND=4 + + # Google cloud format. Change the value of POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION and/or + # POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION if the default is too verbose or not informative + # enough. You can use the following parameters in the expansions. Each of them corresponds to the + # output of `gcloud` tool. + # + # Parameter | Source + # -------------------------|-------------------------------------------------------------------- + # P9K_GCLOUD_CONFIGURATION | gcloud config configurations list --format='value(name)' + # P9K_GCLOUD_ACCOUNT | gcloud config get-value account + # P9K_GCLOUD_PROJECT_ID | gcloud config get-value project + # P9K_GCLOUD_PROJECT_NAME | gcloud projects describe $P9K_GCLOUD_PROJECT_ID --format='value(name)' + # + # Note: ${VARIABLE//\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced with '%%'. + # + # Obtaining project name requires sending a request to Google servers. This can take a long time + # and even fail. When project name is unknown, P9K_GCLOUD_PROJECT_NAME is not set and gcloud + # prompt segment is in state PARTIAL. When project name gets known, P9K_GCLOUD_PROJECT_NAME gets + # set and gcloud prompt segment transitions to state COMPLETE. + # + # You can customize the format, icon and colors of gcloud segment separately for states PARTIAL + # and COMPLETE. You can also hide gcloud in state PARTIAL by setting + # POWERLEVEL9K_GCLOUD_PARTIAL_VISUAL_IDENTIFIER_EXPANSION and + # POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION to empty. + typeset -g POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_ID//\%/%%}' + typeset -g POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_NAME//\%/%%}' + + # Send a request to Google (by means of `gcloud projects describe ...`) to obtain project name + # this often. Negative value disables periodic polling. In this mode project name is retrieved + # only when the current configuration, account or project id changes. + typeset -g POWERLEVEL9K_GCLOUD_REFRESH_PROJECT_NAME_SECONDS=60 + + # Custom icon. + # typeset -g POWERLEVEL9K_GCLOUD_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #[ google_app_cred: google application credentials (https://cloud.google.com/docs/authentication/production) ]# + # Show google_app_cred only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show google_app_cred. + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_SHOW_ON_COMMAND='terraform|pulumi|terragrunt' + + # Google application credentials classes for the purpose of using different colors, icons and + # expansions with different credentials. + # + # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES is an array with even number of elements. The first + # element in each pair defines a pattern against which the current kubernetes context gets + # matched. More specifically, it's P9K_CONTENT prior to the application of context expansion + # (see below) that gets matched. If you unset all POWERLEVEL9K_GOOGLE_APP_CRED_*CONTENT_EXPANSION + # parameters, you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES defines the context class. Patterns are tried in order. + # The first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=( + # '*:*prod*:*' PROD + # '*:*test*:*' TEST + # '*' DEFAULT) + # + # If your current Google application credentials is "service_account deathray-testing x@y.com", + # its class is TEST because it doesn't match the pattern '* *prod* *' but does match '* *test* *'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_FOREGROUND=3 + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_CONTENT_EXPANSION='$P9K_GOOGLE_APP_CRED_PROJECT_ID' + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=( + # '*:*prod*:*' PROD # These values are examples that are unlikely + # '*:*test*:*' TEST # to match your needs. Customize them as needed. + '*' DEFAULT) + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_FOREGROUND=5 + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Use POWERLEVEL9K_GOOGLE_APP_CRED_CONTENT_EXPANSION to specify the content displayed by + # google_app_cred segment. Parameter expansions are very flexible and fast, too. See reference: + # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion. + # + # You can use the following parameters in the expansion. Each of them corresponds to one of the + # fields in the JSON file pointed to by GOOGLE_APPLICATION_CREDENTIALS. + # + # Parameter | JSON key file field + # ---------------------------------+--------------- + # P9K_GOOGLE_APP_CRED_TYPE | type + # P9K_GOOGLE_APP_CRED_PROJECT_ID | project_id + # P9K_GOOGLE_APP_CRED_CLIENT_EMAIL | client_email + # + # Note: ${VARIABLE//\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced by '%%'. + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_CONTENT_EXPANSION='${P9K_GOOGLE_APP_CRED_PROJECT_ID//\%/%%}' + + ##############[ toolbox: toolbox name (https://github.com/containers/toolbox) ]############### + # Toolbox color. + typeset -g POWERLEVEL9K_TOOLBOX_FOREGROUND=3 + # Don't display the name of the toolbox if it matches fedora-toolbox-*. + typeset -g POWERLEVEL9K_TOOLBOX_CONTENT_EXPANSION='${P9K_TOOLBOX_NAME:#fedora-toolbox-*}' + # Custom icon. + # typeset -g POWERLEVEL9K_TOOLBOX_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_TOOLBOX_PREFIX='%fin ' + + ###############################[ public_ip: public IP address ]############################### + # Public IP color. + typeset -g POWERLEVEL9K_PUBLIC_IP_FOREGROUND=6 + # Custom icon. + # typeset -g POWERLEVEL9K_PUBLIC_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ########################[ vpn_ip: virtual private network indicator ]######################### + # VPN IP color. + typeset -g POWERLEVEL9K_VPN_IP_FOREGROUND=3 + # When on VPN, show just an icon without the IP address. + # Tip: To display the private IP address when on VPN, remove the next line. + typeset -g POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION= + # Regular expression for the VPN network interface. Run `ifconfig` or `ip -4 a show` while on VPN + # to see the name of the interface. + typeset -g POWERLEVEL9K_VPN_IP_INTERFACE='(gpd|wg|(.*tun)|tailscale)[0-9]*|(zt.*)' + # If set to true, show one segment per matching network interface. If set to false, show only + # one segment corresponding to the first matching network interface. + # Tip: If you set it to true, you'll probably want to unset POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION. + typeset -g POWERLEVEL9K_VPN_IP_SHOW_ALL=false + # Custom icon. + # typeset -g POWERLEVEL9K_VPN_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ ip: ip address and bandwidth usage for a specified network interface ]########### + # IP color. + typeset -g POWERLEVEL9K_IP_FOREGROUND=4 + # The following parameters are accessible within the expansion: + # + # Parameter | Meaning + # ----------------------+------------------------------------------- + # P9K_IP_IP | IP address + # P9K_IP_INTERFACE | network interface + # P9K_IP_RX_BYTES | total number of bytes received + # P9K_IP_TX_BYTES | total number of bytes sent + # P9K_IP_RX_BYTES_DELTA | number of bytes received since last prompt + # P9K_IP_TX_BYTES_DELTA | number of bytes sent since last prompt + # P9K_IP_RX_RATE | receive rate (since last prompt) + # P9K_IP_TX_RATE | send rate (since last prompt) + typeset -g POWERLEVEL9K_IP_CONTENT_EXPANSION='$P9K_IP_IP${P9K_IP_RX_RATE:+ %2F⇣$P9K_IP_RX_RATE}${P9K_IP_TX_RATE:+ %3F⇡$P9K_IP_TX_RATE}' + # Show information for the first network interface whose name matches this regular expression. + # Run `ifconfig` or `ip -4 a show` to see the names of all network interfaces. + typeset -g POWERLEVEL9K_IP_INTERFACE='[ew].*' + # Custom icon. + # typeset -g POWERLEVEL9K_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #########################[ proxy: system-wide http/https/ftp proxy ]########################## + # Proxy color. + typeset -g POWERLEVEL9K_PROXY_FOREGROUND=2 + # Custom icon. + # typeset -g POWERLEVEL9K_PROXY_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################################[ battery: internal battery ]################################# + # Show battery in red when it's below this level and not connected to power supply. + typeset -g POWERLEVEL9K_BATTERY_LOW_THRESHOLD=20 + typeset -g POWERLEVEL9K_BATTERY_LOW_FOREGROUND=1 + # Show battery in green when it's charging or fully charged. + typeset -g POWERLEVEL9K_BATTERY_{CHARGING,CHARGED}_FOREGROUND=2 + # Show battery in yellow when it's discharging. + typeset -g POWERLEVEL9K_BATTERY_DISCONNECTED_FOREGROUND=3 + # Battery pictograms going from low to high level of charge. + typeset -g POWERLEVEL9K_BATTERY_STAGES=('%K{0}▁' '%K{0}▂' '%K{0}▃' '%K{0}▄' '%K{0}▅' '%K{0}▆' '%K{0}▇' '%K{0}█') + # Don't show the remaining time to charge/discharge. + typeset -g POWERLEVEL9K_BATTERY_VERBOSE=false + + #####################################[ wifi: wifi speed ]##################################### + # WiFi color. + typeset -g POWERLEVEL9K_WIFI_FOREGROUND=4 + # Custom icon. + # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Use different colors and icons depending on signal strength ($P9K_WIFI_BARS). + # + # # Wifi colors and icons for different signal strength levels (low to high). + # typeset -g my_wifi_fg=(4 4 4 4 4) # <-- change these values + # typeset -g my_wifi_icon=('WiFi' 'WiFi' 'WiFi' 'WiFi' 'WiFi') # <-- change these values + # + # typeset -g POWERLEVEL9K_WIFI_CONTENT_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}$P9K_WIFI_LAST_TX_RATE Mbps' + # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}${my_wifi_icon[P9K_WIFI_BARS+1]}' + # + # The following parameters are accessible within the expansions: + # + # Parameter | Meaning + # ----------------------+--------------- + # P9K_WIFI_SSID | service set identifier, a.k.a. network name + # P9K_WIFI_LINK_AUTH | authentication protocol such as "wpa2-psk" or "none"; empty if unknown + # P9K_WIFI_LAST_TX_RATE | wireless transmit rate in megabits per second + # P9K_WIFI_RSSI | signal strength in dBm, from -120 to 0 + # P9K_WIFI_NOISE | noise in dBm, from -120 to 0 + # P9K_WIFI_BARS | signal strength in bars, from 0 to 4 (derived from P9K_WIFI_RSSI and P9K_WIFI_NOISE) + + ####################################[ time: current time ]#################################### + # Current time color. + typeset -g POWERLEVEL9K_TIME_FOREGROUND=6 + # Format for the current time: 09:51:02. See `man 3 strftime`. + typeset -g POWERLEVEL9K_TIME_FORMAT='%D{%H:%M:%S}' + # If set to true, time will update when you hit enter. This way prompts for the past + # commands will contain the start times of their commands as opposed to the default + # behavior where they contain the end times of their preceding commands. + typeset -g POWERLEVEL9K_TIME_UPDATE_ON_COMMAND=false + # Custom icon. + # typeset -g POWERLEVEL9K_TIME_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_TIME_PREFIX='%fat ' + + # Example of a user-defined prompt segment. Function prompt_example will be called on every + # prompt if `example` prompt segment is added to POWERLEVEL9K_LEFT_PROMPT_ELEMENTS or + # POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS. It displays an icon and green text greeting the user. + # + # Type `p10k help segment` for documentation and a more sophisticated example. + function prompt_example() { + p10k segment -f 2 -i '⭐' -t 'hello, %n' + } + + # User-defined prompt segments may optionally provide an instant_prompt_* function. Its job + # is to generate the prompt segment for display in instant prompt. See + # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. + # + # Powerlevel10k will call instant_prompt_* at the same time as the regular prompt_* function + # and will record all `p10k segment` calls it makes. When displaying instant prompt, Powerlevel10k + # will replay these calls without actually calling instant_prompt_*. It is imperative that + # instant_prompt_* always makes the same `p10k segment` calls regardless of environment. If this + # rule is not observed, the content of instant prompt will be incorrect. + # + # Usually, you should either not define instant_prompt_* or simply call prompt_* from it. If + # instant_prompt_* is not defined for a segment, the segment won't be shown in instant prompt. + function instant_prompt_example() { + # Since prompt_example always makes the same `p10k segment` calls, we can call it from + # instant_prompt_example. This will give us the same `example` prompt segment in the instant + # and regular prompts. + prompt_example + } + + # User-defined prompt segments can be customized the same way as built-in segments. + # typeset -g POWERLEVEL9K_EXAMPLE_FOREGROUND=208 + # typeset -g POWERLEVEL9K_EXAMPLE_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Transient prompt works similarly to the builtin transient_rprompt option. It trims down prompt + # when accepting a command line. Supported values: + # + # - off: Don't change prompt when accepting a command line. + # - always: Trim down prompt when accepting a command line. + # - same-dir: Trim down prompt when accepting a command line unless this is the first command + # typed after changing current working directory. + typeset -g POWERLEVEL9K_TRANSIENT_PROMPT=off + + # Instant prompt mode. + # + # - off: Disable instant prompt. Choose this if you've tried instant prompt and found + # it incompatible with your zsh configuration files. + # - quiet: Enable instant prompt and don't print warnings when detecting console output + # during zsh initialization. Choose this if you've read and understood + # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. + # - verbose: Enable instant prompt and print a warning when detecting console output during + # zsh initialization. Choose this if you've never tried instant prompt, haven't + # seen the warning, or if you are unsure what this all means. + typeset -g POWERLEVEL9K_INSTANT_PROMPT=verbose + + # Hot reload allows you to change POWERLEVEL9K options after Powerlevel10k has been initialized. + # For example, you can type POWERLEVEL9K_BACKGROUND=red and see your prompt turn red. Hot reload + # can slow down prompt by 1-2 milliseconds, so it's better to keep it turned off unless you + # really need it. + typeset -g POWERLEVEL9K_DISABLE_HOT_RELOAD=true + + # If p10k is already loaded, reload configuration. + # This works even with POWERLEVEL9K_DISABLE_HOT_RELOAD=true. + (( ! $+functions[p10k] )) || p10k reload +} + +# Tell `p10k configure` which file it should overwrite. +typeset -g POWERLEVEL9K_CONFIG_FILE=${${(%):-%x}:a} + +(( ${#p10k_config_opts} )) && setopt ${p10k_config_opts[@]} +'builtin' 'unset' 'p10k_config_opts' diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-lean.zsh b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-lean.zsh new file mode 100644 index 00000000..7cb97e90 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-lean.zsh @@ -0,0 +1,1705 @@ +# Config for Powerlevel10k with lean prompt style. Type `p10k configure` to generate +# your own config based on it. +# +# Tip: Looking for a nice color? Here's a one-liner to print colormap. +# +# for i in {0..255}; do print -Pn "%K{$i} %k%F{$i}${(l:3::0:)i}%f " ${${(M)$((i%6)):#3}:+$'\n'}; done + +# Temporarily change options. +'builtin' 'local' '-a' 'p10k_config_opts' +[[ ! -o 'aliases' ]] || p10k_config_opts+=('aliases') +[[ ! -o 'sh_glob' ]] || p10k_config_opts+=('sh_glob') +[[ ! -o 'no_brace_expand' ]] || p10k_config_opts+=('no_brace_expand') +'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand' + +() { + emulate -L zsh -o extended_glob + + # Unset all configuration options. This allows you to apply configuration changes without + # restarting zsh. Edit ~/.p10k.zsh and type `source ~/.p10k.zsh`. + unset -m '(POWERLEVEL9K_*|DEFAULT_USER)~POWERLEVEL9K_GITSTATUS_DIR' + + # Zsh >= 5.1 is required. + [[ $ZSH_VERSION == (5.<1->*|<6->.*) ]] || return + + # The list of segments shown on the left. Fill it with the most important segments. + typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=( + # =========================[ Line #1 ]========================= + # os_icon # os identifier + dir # current directory + vcs # git status + # =========================[ Line #2 ]========================= + newline # \n + prompt_char # prompt symbol + ) + + # The list of segments shown on the right. Fill it with less important segments. + # Right prompt on the last prompt line (where you are typing your commands) gets + # automatically hidden when the input line reaches it. Right prompt above the + # last prompt line gets hidden if it would overlap with left prompt. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=( + # =========================[ Line #1 ]========================= + status # exit code of the last command + command_execution_time # duration of the last command + background_jobs # presence of background jobs + direnv # direnv status (https://direnv.net/) + asdf # asdf version manager (https://github.com/asdf-vm/asdf) + virtualenv # python virtual environment (https://docs.python.org/3/library/venv.html) + anaconda # conda environment (https://conda.io/) + pyenv # python environment (https://github.com/pyenv/pyenv) + goenv # go environment (https://github.com/syndbg/goenv) + nodenv # node.js version from nodenv (https://github.com/nodenv/nodenv) + nvm # node.js version from nvm (https://github.com/nvm-sh/nvm) + nodeenv # node.js environment (https://github.com/ekalinin/nodeenv) + # node_version # node.js version + # go_version # go version (https://golang.org) + # rust_version # rustc version (https://www.rust-lang.org) + # dotnet_version # .NET version (https://dotnet.microsoft.com) + # php_version # php version (https://www.php.net/) + # laravel_version # laravel php framework version (https://laravel.com/) + # java_version # java version (https://www.java.com/) + # package # name@version from package.json (https://docs.npmjs.com/files/package.json) + rbenv # ruby version from rbenv (https://github.com/rbenv/rbenv) + rvm # ruby version from rvm (https://rvm.io) + fvm # flutter version management (https://github.com/leoafarias/fvm) + luaenv # lua version from luaenv (https://github.com/cehoffman/luaenv) + jenv # java version from jenv (https://github.com/jenv/jenv) + plenv # perl version from plenv (https://github.com/tokuhirom/plenv) + perlbrew # perl version from perlbrew (https://github.com/gugod/App-perlbrew) + phpenv # php version from phpenv (https://github.com/phpenv/phpenv) + scalaenv # scala version from scalaenv (https://github.com/scalaenv/scalaenv) + haskell_stack # haskell version from stack (https://haskellstack.org/) + kubecontext # current kubernetes context (https://kubernetes.io/) + terraform # terraform workspace (https://www.terraform.io) + # terraform_version # terraform version (https://www.terraform.io) + aws # aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) + aws_eb_env # aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) + azure # azure account name (https://docs.microsoft.com/en-us/cli/azure) + gcloud # google cloud cli account and project (https://cloud.google.com/) + google_app_cred # google application credentials (https://cloud.google.com/docs/authentication/production) + toolbox # toolbox name (https://github.com/containers/toolbox) + context # user@hostname + nordvpn # nordvpn connection status, linux only (https://nordvpn.com/) + ranger # ranger shell (https://github.com/ranger/ranger) + nnn # nnn shell (https://github.com/jarun/nnn) + lf # lf shell (https://github.com/gokcehan/lf) + xplr # xplr shell (https://github.com/sayanarijit/xplr) + vim_shell # vim shell indicator (:sh) + midnight_commander # midnight commander shell (https://midnight-commander.org/) + nix_shell # nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) + chezmoi_shell # chezmoi shell (https://www.chezmoi.io/) + # vpn_ip # virtual private network indicator + # load # CPU load + # disk_usage # disk usage + # ram # free RAM + # swap # used swap + todo # todo items (https://github.com/todotxt/todo.txt-cli) + timewarrior # timewarrior tracking status (https://timewarrior.net/) + taskwarrior # taskwarrior task count (https://taskwarrior.org/) + per_directory_history # Oh My Zsh per-directory-history local/global indicator + # cpu_arch # CPU architecture + # time # current time + # =========================[ Line #2 ]========================= + newline + # ip # ip address and bandwidth usage for a specified network interface + # public_ip # public IP address + # proxy # system-wide http/https/ftp proxy + # battery # internal battery + # wifi # wifi speed + # example # example user-defined segment (see prompt_example function below) + ) + + # Defines character set used by powerlevel10k. It's best to let `p10k configure` set it for you. + typeset -g POWERLEVEL9K_MODE=nerdfont-complete + # When set to `moderate`, some icons will have an extra space after them. This is meant to avoid + # icon overlap when using non-monospace fonts. When set to `none`, spaces are not added. + typeset -g POWERLEVEL9K_ICON_PADDING=none + + # Basic style options that define the overall look of your prompt. You probably don't want to + # change them. + typeset -g POWERLEVEL9K_BACKGROUND= # transparent background + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_{LEFT,RIGHT}_WHITESPACE= # no surrounding whitespace + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SUBSEGMENT_SEPARATOR=' ' # separate segments with a space + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SEGMENT_SEPARATOR= # no end-of-line symbol + + # When set to true, icons appear before content on both sides of the prompt. When set + # to false, icons go after content. If empty or not set, icons go before content in the left + # prompt and after content in the right prompt. + # + # You can also override it for a specific segment: + # + # POWERLEVEL9K_STATUS_ICON_BEFORE_CONTENT=false + # + # Or for a specific segment in specific state: + # + # POWERLEVEL9K_DIR_NOT_WRITABLE_ICON_BEFORE_CONTENT=false + typeset -g POWERLEVEL9K_ICON_BEFORE_CONTENT=true + + # Add an empty line before each prompt. + typeset -g POWERLEVEL9K_PROMPT_ADD_NEWLINE=true + + # Connect left prompt lines with these symbols. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_PREFIX= + typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_PREFIX= + typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX= + # Connect right prompt lines with these symbols. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_SUFFIX= + typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_SUFFIX= + typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_SUFFIX= + + # The left end of left prompt. + typeset -g POWERLEVEL9K_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL= + # The right end of right prompt. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_LAST_SEGMENT_END_SYMBOL= + + # Ruler, a.k.a. the horizontal line before each prompt. If you set it to true, you'll + # probably want to set POWERLEVEL9K_PROMPT_ADD_NEWLINE=false above and + # POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' ' below. + typeset -g POWERLEVEL9K_SHOW_RULER=false + typeset -g POWERLEVEL9K_RULER_CHAR='─' # reasonable alternative: '·' + typeset -g POWERLEVEL9K_RULER_FOREGROUND=240 + + # Filler between left and right prompt on the first prompt line. You can set it to '·' or '─' + # to make it easier to see the alignment between left and right prompt and to separate prompt + # from command output. It serves the same purpose as ruler (see above) without increasing + # the number of prompt lines. You'll probably want to set POWERLEVEL9K_SHOW_RULER=false + # if using this. You might also like POWERLEVEL9K_PROMPT_ADD_NEWLINE=false for more compact + # prompt. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' ' + if [[ $POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR != ' ' ]]; then + # The color of the filler. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_FOREGROUND=240 + # Add a space between the end of left prompt and the filler. + typeset -g POWERLEVEL9K_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL=' ' + # Add a space between the filler and the start of right prompt. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL=' ' + # Start filler from the edge of the screen if there are no left segments on the first line. + typeset -g POWERLEVEL9K_EMPTY_LINE_LEFT_PROMPT_FIRST_SEGMENT_END_SYMBOL='%{%}' + # End filler on the edge of the screen if there are no right segments on the first line. + typeset -g POWERLEVEL9K_EMPTY_LINE_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL='%{%}' + fi + + #################################[ os_icon: os identifier ]################################## + # OS identifier color. + typeset -g POWERLEVEL9K_OS_ICON_FOREGROUND= + # Custom icon. + # typeset -g POWERLEVEL9K_OS_ICON_CONTENT_EXPANSION='⭐' + + ################################[ prompt_char: prompt symbol ]################################ + # Green prompt symbol if the last command succeeded. + typeset -g POWERLEVEL9K_PROMPT_CHAR_OK_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=76 + # Red prompt symbol if the last command failed. + typeset -g POWERLEVEL9K_PROMPT_CHAR_ERROR_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=196 + # Default prompt symbol. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION='❯' + # Prompt symbol in command vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VICMD_CONTENT_EXPANSION='❮' + # Prompt symbol in visual vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIVIS_CONTENT_EXPANSION='V' + # Prompt symbol in overwrite vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIOWR_CONTENT_EXPANSION='▶' + typeset -g POWERLEVEL9K_PROMPT_CHAR_OVERWRITE_STATE=true + # No line terminator if prompt_char is the last segment. + typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL='' + # No line introducer if prompt_char is the first segment. + typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL= + + ##################################[ dir: current directory ]################################## + # Default current directory color. + typeset -g POWERLEVEL9K_DIR_FOREGROUND=31 + # If directory is too long, shorten some of its segments to the shortest possible unique + # prefix. The shortened directory can be tab-completed to the original. + typeset -g POWERLEVEL9K_SHORTEN_STRATEGY=truncate_to_unique + # Replace removed segment suffixes with this symbol. + typeset -g POWERLEVEL9K_SHORTEN_DELIMITER= + # Color of the shortened directory segments. + typeset -g POWERLEVEL9K_DIR_SHORTENED_FOREGROUND=103 + # Color of the anchor directory segments. Anchor segments are never shortened. The first + # segment is always an anchor. + typeset -g POWERLEVEL9K_DIR_ANCHOR_FOREGROUND=39 + # Display anchor directory segments in bold. + typeset -g POWERLEVEL9K_DIR_ANCHOR_BOLD=true + # Don't shorten directories that contain any of these files. They are anchors. + local anchor_files=( + .bzr + .citc + .git + .hg + .node-version + .python-version + .go-version + .ruby-version + .lua-version + .java-version + .perl-version + .php-version + .tool-versions + .shorten_folder_marker + .svn + .terraform + CVS + Cargo.toml + composer.json + go.mod + package.json + stack.yaml + ) + typeset -g POWERLEVEL9K_SHORTEN_FOLDER_MARKER="(${(j:|:)anchor_files})" + # If set to "first" ("last"), remove everything before the first (last) subdirectory that contains + # files matching $POWERLEVEL9K_SHORTEN_FOLDER_MARKER. For example, when the current directory is + # /foo/bar/git_repo/nested_git_repo/baz, prompt will display git_repo/nested_git_repo/baz (first) + # or nested_git_repo/baz (last). This assumes that git_repo and nested_git_repo contain markers + # and other directories don't. + # + # Optionally, "first" and "last" can be followed by ":" where is an integer. + # This moves the truncation point to the right (positive offset) or to the left (negative offset) + # relative to the marker. Plain "first" and "last" are equivalent to "first:0" and "last:0" + # respectively. + typeset -g POWERLEVEL9K_DIR_TRUNCATE_BEFORE_MARKER=false + # Don't shorten this many last directory segments. They are anchors. + typeset -g POWERLEVEL9K_SHORTEN_DIR_LENGTH=1 + # Shorten directory if it's longer than this even if there is space for it. The value can + # be either absolute (e.g., '80') or a percentage of terminal width (e.g, '50%'). If empty, + # directory will be shortened only when prompt doesn't fit or when other parameters demand it + # (see POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS and POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT below). + # If set to `0`, directory will always be shortened to its minimum length. + typeset -g POWERLEVEL9K_DIR_MAX_LENGTH=80 + # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least this + # many columns for typing commands. + typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS=40 + # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least + # COLUMNS * POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT * 0.01 columns for typing commands. + typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT=50 + # If set to true, embed a hyperlink into the directory. Useful for quickly + # opening a directory in the file manager simply by clicking the link. + # Can also be handy when the directory is shortened, as it allows you to see + # the full directory that was used in previous commands. + typeset -g POWERLEVEL9K_DIR_HYPERLINK=false + + # Enable special styling for non-writable and non-existent directories. See POWERLEVEL9K_LOCK_ICON + # and POWERLEVEL9K_DIR_CLASSES below. + typeset -g POWERLEVEL9K_DIR_SHOW_WRITABLE=v3 + + # The default icon shown next to non-writable and non-existent directories when + # POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3. + # typeset -g POWERLEVEL9K_LOCK_ICON='⭐' + + # POWERLEVEL9K_DIR_CLASSES allows you to specify custom icons and colors for different + # directories. It must be an array with 3 * N elements. Each triplet consists of: + # + # 1. A pattern against which the current directory ($PWD) is matched. Matching is done with + # extended_glob option enabled. + # 2. Directory class for the purpose of styling. + # 3. An empty string. + # + # Triplets are tried in order. The first triplet whose pattern matches $PWD wins. + # + # If POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3, non-writable and non-existent directories + # acquire class suffix _NOT_WRITABLE and NON_EXISTENT respectively. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_DIR_CLASSES=( + # '~/work(|/*)' WORK '' + # '~(|/*)' HOME '' + # '*' DEFAULT '') + # + # Whenever the current directory is ~/work or a subdirectory of ~/work, it gets styled with one + # of the following classes depending on its writability and existence: WORK, WORK_NOT_WRITABLE or + # WORK_NON_EXISTENT. + # + # Simply assigning classes to directories doesn't have any visible effects. It merely gives you an + # option to define custom colors and icons for different directory classes. + # + # # Styling for WORK. + # typeset -g POWERLEVEL9K_DIR_WORK_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_DIR_WORK_FOREGROUND=31 + # typeset -g POWERLEVEL9K_DIR_WORK_SHORTENED_FOREGROUND=103 + # typeset -g POWERLEVEL9K_DIR_WORK_ANCHOR_FOREGROUND=39 + # + # # Styling for WORK_NOT_WRITABLE. + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND=31 + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_SHORTENED_FOREGROUND=103 + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_ANCHOR_FOREGROUND=39 + # + # # Styling for WORK_NON_EXISTENT. + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_FOREGROUND=31 + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_SHORTENED_FOREGROUND=103 + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_ANCHOR_FOREGROUND=39 + # + # If a styling parameter isn't explicitly defined for some class, it falls back to the classless + # parameter. For example, if POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND is not set, it falls + # back to POWERLEVEL9K_DIR_FOREGROUND. + # + # typeset -g POWERLEVEL9K_DIR_CLASSES=() + + # Custom prefix. + # typeset -g POWERLEVEL9K_DIR_PREFIX='%fin ' + + #####################################[ vcs: git status ]###################################### + # Branch icon. Set this parameter to '\UE0A0 ' for the popular Powerline branch icon. + typeset -g POWERLEVEL9K_VCS_BRANCH_ICON= + + # Untracked files icon. It's really a question mark, your font isn't broken. + # Change the value of this parameter to show a different icon. + typeset -g POWERLEVEL9K_VCS_UNTRACKED_ICON='?' + + # Formatter for Git status. + # + # Example output: master wip ⇣42⇡42 *42 merge ~42 +42 !42 ?42. + # + # You can edit the function to customize how Git status looks. + # + # VCS_STATUS_* parameters are set by gitstatus plugin. See reference: + # https://github.com/romkatv/gitstatus/blob/master/gitstatus.plugin.zsh. + function my_git_formatter() { + emulate -L zsh + + if [[ -n $P9K_CONTENT ]]; then + # If P9K_CONTENT is not empty, use it. It's either "loading" or from vcs_info (not from + # gitstatus plugin). VCS_STATUS_* parameters are not available in this case. + typeset -g my_git_format=$P9K_CONTENT + return + fi + + if (( $1 )); then + # Styling for up-to-date Git status. + local meta='%f' # default foreground + local clean='%76F' # green foreground + local modified='%178F' # yellow foreground + local untracked='%39F' # blue foreground + local conflicted='%196F' # red foreground + else + # Styling for incomplete and stale Git status. + local meta='%244F' # grey foreground + local clean='%244F' # grey foreground + local modified='%244F' # grey foreground + local untracked='%244F' # grey foreground + local conflicted='%244F' # grey foreground + fi + + local res + + if [[ -n $VCS_STATUS_LOCAL_BRANCH ]]; then + local branch=${(V)VCS_STATUS_LOCAL_BRANCH} + # If local branch name is at most 32 characters long, show it in full. + # Otherwise show the first 12 … the last 12. + # Tip: To always show local branch name in full without truncation, delete the next line. + (( $#branch > 32 )) && branch[13,-13]="…" # <-- this line + res+="${clean}${(g::)POWERLEVEL9K_VCS_BRANCH_ICON}${branch//\%/%%}" + fi + + if [[ -n $VCS_STATUS_TAG + # Show tag only if not on a branch. + # Tip: To always show tag, delete the next line. + && -z $VCS_STATUS_LOCAL_BRANCH # <-- this line + ]]; then + local tag=${(V)VCS_STATUS_TAG} + # If tag name is at most 32 characters long, show it in full. + # Otherwise show the first 12 … the last 12. + # Tip: To always show tag name in full without truncation, delete the next line. + (( $#tag > 32 )) && tag[13,-13]="…" # <-- this line + res+="${meta}#${clean}${tag//\%/%%}" + fi + + # Display the current Git commit if there is no branch and no tag. + # Tip: To always display the current Git commit, delete the next line. + [[ -z $VCS_STATUS_LOCAL_BRANCH && -z $VCS_STATUS_TAG ]] && # <-- this line + res+="${meta}@${clean}${VCS_STATUS_COMMIT[1,8]}" + + # Show tracking branch name if it differs from local branch. + if [[ -n ${VCS_STATUS_REMOTE_BRANCH:#$VCS_STATUS_LOCAL_BRANCH} ]]; then + res+="${meta}:${clean}${(V)VCS_STATUS_REMOTE_BRANCH//\%/%%}" + fi + + # Display "wip" if the latest commit's summary contains "wip" or "WIP". + if [[ $VCS_STATUS_COMMIT_SUMMARY == (|*[^[:alnum:]])(wip|WIP)(|[^[:alnum:]]*) ]]; then + res+=" ${modified}wip" + fi + + if (( VCS_STATUS_COMMITS_AHEAD || VCS_STATUS_COMMITS_BEHIND )); then + # ⇣42 if behind the remote. + (( VCS_STATUS_COMMITS_BEHIND )) && res+=" ${clean}⇣${VCS_STATUS_COMMITS_BEHIND}" + # ⇡42 if ahead of the remote; no leading space if also behind the remote: ⇣42⇡42. + (( VCS_STATUS_COMMITS_AHEAD && !VCS_STATUS_COMMITS_BEHIND )) && res+=" " + (( VCS_STATUS_COMMITS_AHEAD )) && res+="${clean}⇡${VCS_STATUS_COMMITS_AHEAD}" + elif [[ -n $VCS_STATUS_REMOTE_BRANCH ]]; then + # Tip: Uncomment the next line to display '=' if up to date with the remote. + # res+=" ${clean}=" + fi + + # ⇠42 if behind the push remote. + (( VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=" ${clean}⇠${VCS_STATUS_PUSH_COMMITS_BEHIND}" + (( VCS_STATUS_PUSH_COMMITS_AHEAD && !VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=" " + # ⇢42 if ahead of the push remote; no leading space if also behind: ⇠42⇢42. + (( VCS_STATUS_PUSH_COMMITS_AHEAD )) && res+="${clean}⇢${VCS_STATUS_PUSH_COMMITS_AHEAD}" + # *42 if have stashes. + (( VCS_STATUS_STASHES )) && res+=" ${clean}*${VCS_STATUS_STASHES}" + # 'merge' if the repo is in an unusual state. + [[ -n $VCS_STATUS_ACTION ]] && res+=" ${conflicted}${VCS_STATUS_ACTION}" + # ~42 if have merge conflicts. + (( VCS_STATUS_NUM_CONFLICTED )) && res+=" ${conflicted}~${VCS_STATUS_NUM_CONFLICTED}" + # +42 if have staged changes. + (( VCS_STATUS_NUM_STAGED )) && res+=" ${modified}+${VCS_STATUS_NUM_STAGED}" + # !42 if have unstaged changes. + (( VCS_STATUS_NUM_UNSTAGED )) && res+=" ${modified}!${VCS_STATUS_NUM_UNSTAGED}" + # ?42 if have untracked files. It's really a question mark, your font isn't broken. + # See POWERLEVEL9K_VCS_UNTRACKED_ICON above if you want to use a different icon. + # Remove the next line if you don't want to see untracked files at all. + (( VCS_STATUS_NUM_UNTRACKED )) && res+=" ${untracked}${(g::)POWERLEVEL9K_VCS_UNTRACKED_ICON}${VCS_STATUS_NUM_UNTRACKED}" + # "─" if the number of unstaged files is unknown. This can happen due to + # POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY (see below) being set to a non-negative number lower + # than the number of files in the Git index, or due to bash.showDirtyState being set to false + # in the repository config. The number of staged and untracked files may also be unknown + # in this case. + (( VCS_STATUS_HAS_UNSTAGED == -1 )) && res+=" ${modified}─" + + typeset -g my_git_format=$res + } + functions -M my_git_formatter 2>/dev/null + + # Don't count the number of unstaged, untracked and conflicted files in Git repositories with + # more than this many files in the index. Negative value means infinity. + # + # If you are working in Git repositories with tens of millions of files and seeing performance + # sagging, try setting POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY to a number lower than the output + # of `git ls-files | wc -l`. Alternatively, add `bash.showDirtyState = false` to the repository's + # config: `git config bash.showDirtyState false`. + typeset -g POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY=-1 + + # Don't show Git status in prompt for repositories whose workdir matches this pattern. + # For example, if set to '~', the Git repository at $HOME/.git will be ignored. + # Multiple patterns can be combined with '|': '~(|/foo)|/bar/baz/*'. + typeset -g POWERLEVEL9K_VCS_DISABLED_WORKDIR_PATTERN='~' + + # Disable the default Git status formatting. + typeset -g POWERLEVEL9K_VCS_DISABLE_GITSTATUS_FORMATTING=true + # Install our own Git status formatter. + typeset -g POWERLEVEL9K_VCS_CONTENT_EXPANSION='${$((my_git_formatter(1)))+${my_git_format}}' + typeset -g POWERLEVEL9K_VCS_LOADING_CONTENT_EXPANSION='${$((my_git_formatter(0)))+${my_git_format}}' + # Enable counters for staged, unstaged, etc. + typeset -g POWERLEVEL9K_VCS_{STAGED,UNSTAGED,UNTRACKED,CONFLICTED,COMMITS_AHEAD,COMMITS_BEHIND}_MAX_NUM=-1 + + # Icon color. + typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_COLOR=76 + typeset -g POWERLEVEL9K_VCS_LOADING_VISUAL_IDENTIFIER_COLOR=244 + # Custom icon. + # typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_VCS_PREFIX='%fon ' + + # Show status of repositories of these types. You can add svn and/or hg if you are + # using them. If you do, your prompt may become slow even when your current directory + # isn't in an svn or hg repository. + typeset -g POWERLEVEL9K_VCS_BACKENDS=(git) + + # These settings are used for repositories other than Git or when gitstatusd fails and + # Powerlevel10k has to fall back to using vcs_info. + typeset -g POWERLEVEL9K_VCS_CLEAN_FOREGROUND=76 + typeset -g POWERLEVEL9K_VCS_UNTRACKED_FOREGROUND=76 + typeset -g POWERLEVEL9K_VCS_MODIFIED_FOREGROUND=178 + + ##########################[ status: exit code of the last command ]########################### + # Enable OK_PIPE, ERROR_PIPE and ERROR_SIGNAL status states to allow us to enable, disable and + # style them independently from the regular OK and ERROR state. + typeset -g POWERLEVEL9K_STATUS_EXTENDED_STATES=true + + # Status on success. No content, just an icon. No need to show it if prompt_char is enabled as + # it will signify success by turning green. + typeset -g POWERLEVEL9K_STATUS_OK=false + typeset -g POWERLEVEL9K_STATUS_OK_FOREGROUND=70 + typeset -g POWERLEVEL9K_STATUS_OK_VISUAL_IDENTIFIER_EXPANSION='✔' + + # Status when some part of a pipe command fails but the overall exit status is zero. It may look + # like this: 1|0. + typeset -g POWERLEVEL9K_STATUS_OK_PIPE=true + typeset -g POWERLEVEL9K_STATUS_OK_PIPE_FOREGROUND=70 + typeset -g POWERLEVEL9K_STATUS_OK_PIPE_VISUAL_IDENTIFIER_EXPANSION='✔' + + # Status when it's just an error code (e.g., '1'). No need to show it if prompt_char is enabled as + # it will signify error by turning red. + typeset -g POWERLEVEL9K_STATUS_ERROR=false + typeset -g POWERLEVEL9K_STATUS_ERROR_FOREGROUND=160 + typeset -g POWERLEVEL9K_STATUS_ERROR_VISUAL_IDENTIFIER_EXPANSION='✘' + + # Status when the last command was terminated by a signal. + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL=true + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_FOREGROUND=160 + # Use terse signal names: "INT" instead of "SIGINT(2)". + typeset -g POWERLEVEL9K_STATUS_VERBOSE_SIGNAME=false + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_VISUAL_IDENTIFIER_EXPANSION='✘' + + # Status when some part of a pipe command fails and the overall exit status is also non-zero. + # It may look like this: 1|0. + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE=true + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_FOREGROUND=160 + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_VISUAL_IDENTIFIER_EXPANSION='✘' + + ###################[ command_execution_time: duration of the last command ]################### + # Show duration of the last command if takes at least this many seconds. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD=3 + # Show this many fractional digits. Zero means round to seconds. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PRECISION=0 + # Execution time color. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FOREGROUND=101 + # Duration format: 1d 2h 3m 4s. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FORMAT='d h m s' + # Custom icon. + # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PREFIX='%ftook ' + + #######################[ background_jobs: presence of background jobs ]####################### + # Don't show the number of background jobs. + typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VERBOSE=false + # Background jobs color. + typeset -g POWERLEVEL9K_BACKGROUND_JOBS_FOREGROUND=70 + # Custom icon. + # typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######################[ direnv: direnv status (https://direnv.net/) ]######################## + # Direnv color. + typeset -g POWERLEVEL9K_DIRENV_FOREGROUND=178 + # Custom icon. + # typeset -g POWERLEVEL9K_DIRENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###############[ asdf: asdf version manager (https://github.com/asdf-vm/asdf) ]############### + # Default asdf color. Only used to display tools for which there is no color override (see below). + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_FOREGROUND. + typeset -g POWERLEVEL9K_ASDF_FOREGROUND=66 + + # There are four parameters that can be used to hide asdf tools. Each parameter describes + # conditions under which a tool gets hidden. Parameters can hide tools but not unhide them. If at + # least one parameter decides to hide a tool, that tool gets hidden. If no parameter decides to + # hide a tool, it gets shown. + # + # Special note on the difference between POWERLEVEL9K_ASDF_SOURCES and + # POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW. Consider the effect of the following commands: + # + # asdf local python 3.8.1 + # asdf global python 3.8.1 + # + # After running both commands the current python version is 3.8.1 and its source is "local" as + # it takes precedence over "global". If POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW is set to false, + # it'll hide python version in this case because 3.8.1 is the same as the global version. + # POWERLEVEL9K_ASDF_SOURCES will hide python version only if the value of this parameter doesn't + # contain "local". + + # Hide tool versions that don't come from one of these sources. + # + # Available sources: + # + # - shell `asdf current` says "set by ASDF_${TOOL}_VERSION environment variable" + # - local `asdf current` says "set by /some/not/home/directory/file" + # - global `asdf current` says "set by /home/username/file" + # + # Note: If this parameter is set to (shell local global), it won't hide tools. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SOURCES. + typeset -g POWERLEVEL9K_ASDF_SOURCES=(shell local global) + + # If set to false, hide tool versions that are the same as global. + # + # Note: The name of this parameter doesn't reflect its meaning at all. + # Note: If this parameter is set to true, it won't hide tools. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_PROMPT_ALWAYS_SHOW. + typeset -g POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW=false + + # If set to false, hide tool versions that are equal to "system". + # + # Note: If this parameter is set to true, it won't hide tools. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_SYSTEM. + typeset -g POWERLEVEL9K_ASDF_SHOW_SYSTEM=true + + # If set to non-empty value, hide tools unless there is a file matching the specified file pattern + # in the current directory, or its parent directory, or its grandparent directory, and so on. + # + # Note: If this parameter is set to empty value, it won't hide tools. + # Note: SHOW_ON_UPGLOB isn't specific to asdf. It works with all prompt segments. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_ON_UPGLOB. + # + # Example: Hide nodejs version when there is no package.json and no *.js files in the current + # directory, in `..`, in `../..` and so on. + # + # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.js|package.json' + typeset -g POWERLEVEL9K_ASDF_SHOW_ON_UPGLOB= + + # Ruby version from asdf. + typeset -g POWERLEVEL9K_ASDF_RUBY_FOREGROUND=168 + # typeset -g POWERLEVEL9K_ASDF_RUBY_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_RUBY_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Python version from asdf. + typeset -g POWERLEVEL9K_ASDF_PYTHON_FOREGROUND=37 + # typeset -g POWERLEVEL9K_ASDF_PYTHON_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_PYTHON_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Go version from asdf. + typeset -g POWERLEVEL9K_ASDF_GOLANG_FOREGROUND=37 + # typeset -g POWERLEVEL9K_ASDF_GOLANG_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_GOLANG_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Node.js version from asdf. + typeset -g POWERLEVEL9K_ASDF_NODEJS_FOREGROUND=70 + # typeset -g POWERLEVEL9K_ASDF_NODEJS_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Rust version from asdf. + typeset -g POWERLEVEL9K_ASDF_RUST_FOREGROUND=37 + # typeset -g POWERLEVEL9K_ASDF_RUST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_RUST_SHOW_ON_UPGLOB='*.foo|*.bar' + + # .NET Core version from asdf. + typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_FOREGROUND=134 + # typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_DOTNET_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Flutter version from asdf. + typeset -g POWERLEVEL9K_ASDF_FLUTTER_FOREGROUND=38 + # typeset -g POWERLEVEL9K_ASDF_FLUTTER_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_FLUTTER_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Lua version from asdf. + typeset -g POWERLEVEL9K_ASDF_LUA_FOREGROUND=32 + # typeset -g POWERLEVEL9K_ASDF_LUA_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_LUA_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Java version from asdf. + typeset -g POWERLEVEL9K_ASDF_JAVA_FOREGROUND=32 + # typeset -g POWERLEVEL9K_ASDF_JAVA_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_JAVA_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Perl version from asdf. + typeset -g POWERLEVEL9K_ASDF_PERL_FOREGROUND=67 + # typeset -g POWERLEVEL9K_ASDF_PERL_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_PERL_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Erlang version from asdf. + typeset -g POWERLEVEL9K_ASDF_ERLANG_FOREGROUND=125 + # typeset -g POWERLEVEL9K_ASDF_ERLANG_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_ERLANG_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Elixir version from asdf. + typeset -g POWERLEVEL9K_ASDF_ELIXIR_FOREGROUND=129 + # typeset -g POWERLEVEL9K_ASDF_ELIXIR_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_ELIXIR_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Postgres version from asdf. + typeset -g POWERLEVEL9K_ASDF_POSTGRES_FOREGROUND=31 + # typeset -g POWERLEVEL9K_ASDF_POSTGRES_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_POSTGRES_SHOW_ON_UPGLOB='*.foo|*.bar' + + # PHP version from asdf. + typeset -g POWERLEVEL9K_ASDF_PHP_FOREGROUND=99 + # typeset -g POWERLEVEL9K_ASDF_PHP_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_PHP_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Haskell version from asdf. + typeset -g POWERLEVEL9K_ASDF_HASKELL_FOREGROUND=172 + # typeset -g POWERLEVEL9K_ASDF_HASKELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_HASKELL_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Julia version from asdf. + typeset -g POWERLEVEL9K_ASDF_JULIA_FOREGROUND=70 + # typeset -g POWERLEVEL9K_ASDF_JULIA_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_JULIA_SHOW_ON_UPGLOB='*.foo|*.bar' + + ##########[ nordvpn: nordvpn connection status, linux only (https://nordvpn.com/) ]########### + # NordVPN connection indicator color. + typeset -g POWERLEVEL9K_NORDVPN_FOREGROUND=39 + # Hide NordVPN connection indicator when not connected. + typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_CONTENT_EXPANSION= + typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_VISUAL_IDENTIFIER_EXPANSION= + # Custom icon. + # typeset -g POWERLEVEL9K_NORDVPN_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #################[ ranger: ranger shell (https://github.com/ranger/ranger) ]################## + # Ranger shell color. + typeset -g POWERLEVEL9K_RANGER_FOREGROUND=178 + # Custom icon. + # typeset -g POWERLEVEL9K_RANGER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################[ nnn: nnn shell (https://github.com/jarun/nnn) ]####################### + # Nnn shell color. + typeset -g POWERLEVEL9K_NNN_FOREGROUND=72 + # Custom icon. + # typeset -g POWERLEVEL9K_NNN_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################[ lf: lf shell (https://github.com/gokcehan/lf) ]####################### + # lf shell color. + typeset -g POWERLEVEL9K_LF_FOREGROUND=72 + # Custom icon. + # typeset -g POWERLEVEL9K_LF_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################[ xplr: xplr shell (https://github.com/sayanarijit/xplr) ]################## + # xplr shell color. + typeset -g POWERLEVEL9K_XPLR_FOREGROUND=72 + # Custom icon. + # typeset -g POWERLEVEL9K_XPLR_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########################[ vim_shell: vim shell indicator (:sh) ]########################### + # Vim shell indicator color. + typeset -g POWERLEVEL9K_VIM_SHELL_FOREGROUND=34 + # Custom icon. + # typeset -g POWERLEVEL9K_VIM_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######[ midnight_commander: midnight commander shell (https://midnight-commander.org/) ]###### + # Midnight Commander shell color. + typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_FOREGROUND=178 + # Custom icon. + # typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #[ nix_shell: nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) ]## + # Nix shell color. + typeset -g POWERLEVEL9K_NIX_SHELL_FOREGROUND=74 + + # Display the icon of nix_shell if PATH contains a subdirectory of /nix/store. + # typeset -g POWERLEVEL9K_NIX_SHELL_INFER_FROM_PATH=false + + # Tip: If you want to see just the icon without "pure" and "impure", uncomment the next line. + # typeset -g POWERLEVEL9K_NIX_SHELL_CONTENT_EXPANSION= + + # Custom icon. + # typeset -g POWERLEVEL9K_NIX_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################[ chezmoi_shell: chezmoi shell (https://www.chezmoi.io/) ]################## + # chezmoi shell color. + typeset -g POWERLEVEL9K_CHEZMOI_SHELL_FOREGROUND=33 + # Custom icon. + # typeset -g POWERLEVEL9K_CHEZMOI_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################################[ disk_usage: disk usage ]################################## + # Colors for different levels of disk usage. + typeset -g POWERLEVEL9K_DISK_USAGE_NORMAL_FOREGROUND=35 + typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_FOREGROUND=220 + typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_FOREGROUND=160 + # Thresholds for different levels of disk usage (percentage points). + typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL=90 + typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_LEVEL=95 + # If set to true, hide disk usage when below $POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL percent. + typeset -g POWERLEVEL9K_DISK_USAGE_ONLY_WARNING=false + # Custom icon. + # typeset -g POWERLEVEL9K_DISK_USAGE_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################################[ ram: free RAM ]####################################### + # RAM color. + typeset -g POWERLEVEL9K_RAM_FOREGROUND=66 + # Custom icon. + # typeset -g POWERLEVEL9K_RAM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #####################################[ swap: used swap ]###################################### + # Swap color. + typeset -g POWERLEVEL9K_SWAP_FOREGROUND=96 + # Custom icon. + # typeset -g POWERLEVEL9K_SWAP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################################[ load: CPU load ]###################################### + # Show average CPU load over this many last minutes. Valid values are 1, 5 and 15. + typeset -g POWERLEVEL9K_LOAD_WHICH=5 + # Load color when load is under 50%. + typeset -g POWERLEVEL9K_LOAD_NORMAL_FOREGROUND=66 + # Load color when load is between 50% and 70%. + typeset -g POWERLEVEL9K_LOAD_WARNING_FOREGROUND=178 + # Load color when load is over 70%. + typeset -g POWERLEVEL9K_LOAD_CRITICAL_FOREGROUND=166 + # Custom icon. + # typeset -g POWERLEVEL9K_LOAD_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ todo: todo items (https://github.com/todotxt/todo.txt-cli) ]################ + # Todo color. + typeset -g POWERLEVEL9K_TODO_FOREGROUND=110 + # Hide todo when the total number of tasks is zero. + typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_TOTAL=true + # Hide todo when the number of tasks after filtering is zero. + typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_FILTERED=false + + # Todo format. The following parameters are available within the expansion. + # + # - P9K_TODO_TOTAL_TASK_COUNT The total number of tasks. + # - P9K_TODO_FILTERED_TASK_COUNT The number of tasks after filtering. + # + # These variables correspond to the last line of the output of `todo.sh -p ls`: + # + # TODO: 24 of 42 tasks shown + # + # Here 24 is P9K_TODO_FILTERED_TASK_COUNT and 42 is P9K_TODO_TOTAL_TASK_COUNT. + # + # typeset -g POWERLEVEL9K_TODO_CONTENT_EXPANSION='$P9K_TODO_FILTERED_TASK_COUNT' + + # Custom icon. + # typeset -g POWERLEVEL9K_TODO_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ timewarrior: timewarrior tracking status (https://timewarrior.net/) ]############ + # Timewarrior color. + typeset -g POWERLEVEL9K_TIMEWARRIOR_FOREGROUND=110 + # If the tracked task is longer than 24 characters, truncate and append "…". + # Tip: To always display tasks without truncation, delete the following parameter. + # Tip: To hide task names and display just the icon when time tracking is enabled, set the + # value of the following parameter to "". + typeset -g POWERLEVEL9K_TIMEWARRIOR_CONTENT_EXPANSION='${P9K_CONTENT:0:24}${${P9K_CONTENT:24}:+…}' + + # Custom icon. + # typeset -g POWERLEVEL9K_TIMEWARRIOR_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##############[ taskwarrior: taskwarrior task count (https://taskwarrior.org/) ]############## + # Taskwarrior color. + typeset -g POWERLEVEL9K_TASKWARRIOR_FOREGROUND=74 + + # Taskwarrior segment format. The following parameters are available within the expansion. + # + # - P9K_TASKWARRIOR_PENDING_COUNT The number of pending tasks: `task +PENDING count`. + # - P9K_TASKWARRIOR_OVERDUE_COUNT The number of overdue tasks: `task +OVERDUE count`. + # + # Zero values are represented as empty parameters. + # + # The default format: + # + # '${P9K_TASKWARRIOR_OVERDUE_COUNT:+"!$P9K_TASKWARRIOR_OVERDUE_COUNT/"}$P9K_TASKWARRIOR_PENDING_COUNT' + # + # typeset -g POWERLEVEL9K_TASKWARRIOR_CONTENT_EXPANSION='$P9K_TASKWARRIOR_PENDING_COUNT' + + # Custom icon. + # typeset -g POWERLEVEL9K_TASKWARRIOR_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######[ per_directory_history: Oh My Zsh per-directory-history local/global indicator ]####### + # Color when using local/global history. + typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_FOREGROUND=135 + typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_FOREGROUND=130 + + # Tip: Uncomment the next two lines to hide "local"/"global" text and leave just the icon. + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_CONTENT_EXPANSION='' + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_CONTENT_EXPANSION='' + + # Custom icon. + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################################[ cpu_arch: CPU architecture ]################################ + # CPU architecture color. + typeset -g POWERLEVEL9K_CPU_ARCH_FOREGROUND=172 + + # Hide the segment when on a specific CPU architecture. + # typeset -g POWERLEVEL9K_CPU_ARCH_X86_64_CONTENT_EXPANSION= + # typeset -g POWERLEVEL9K_CPU_ARCH_X86_64_VISUAL_IDENTIFIER_EXPANSION= + + # Custom icon. + # typeset -g POWERLEVEL9K_CPU_ARCH_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################################[ context: user@hostname ]################################## + # Context color when running with privileges. + typeset -g POWERLEVEL9K_CONTEXT_ROOT_FOREGROUND=178 + # Context color in SSH without privileges. + typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_FOREGROUND=180 + # Default context color (no privileges, no SSH). + typeset -g POWERLEVEL9K_CONTEXT_FOREGROUND=180 + + # Context format when running with privileges: bold user@hostname. + typeset -g POWERLEVEL9K_CONTEXT_ROOT_TEMPLATE='%B%n@%m' + # Context format when in SSH without privileges: user@hostname. + typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_TEMPLATE='%n@%m' + # Default context format (no privileges, no SSH): user@hostname. + typeset -g POWERLEVEL9K_CONTEXT_TEMPLATE='%n@%m' + + # Don't show context unless running with privileges or in SSH. + # Tip: Remove the next line to always show context. + typeset -g POWERLEVEL9K_CONTEXT_{DEFAULT,SUDO}_{CONTENT,VISUAL_IDENTIFIER}_EXPANSION= + + # Custom icon. + # typeset -g POWERLEVEL9K_CONTEXT_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_CONTEXT_PREFIX='%fwith ' + + ###[ virtualenv: python virtual environment (https://docs.python.org/3/library/venv.html) ]### + # Python virtual environment color. + typeset -g POWERLEVEL9K_VIRTUALENV_FOREGROUND=37 + # Don't show Python version next to the virtual environment name. + typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_PYTHON_VERSION=false + # If set to "false", won't show virtualenv if pyenv is already shown. + # If set to "if-different", won't show virtualenv if it's the same as pyenv. + typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_WITH_PYENV=false + # Separate environment name from Python version only with a space. + typeset -g POWERLEVEL9K_VIRTUALENV_{LEFT,RIGHT}_DELIMITER= + # Custom icon. + # typeset -g POWERLEVEL9K_VIRTUALENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #####################[ anaconda: conda environment (https://conda.io/) ]###################### + # Anaconda environment color. + typeset -g POWERLEVEL9K_ANACONDA_FOREGROUND=37 + + # Anaconda segment format. The following parameters are available within the expansion. + # + # - CONDA_PREFIX Absolute path to the active Anaconda/Miniconda environment. + # - CONDA_DEFAULT_ENV Name of the active Anaconda/Miniconda environment. + # - CONDA_PROMPT_MODIFIER Configurable prompt modifier (see below). + # - P9K_ANACONDA_PYTHON_VERSION Current python version (python --version). + # + # CONDA_PROMPT_MODIFIER can be configured with the following command: + # + # conda config --set env_prompt '({default_env}) ' + # + # The last argument is a Python format string that can use the following variables: + # + # - prefix The same as CONDA_PREFIX. + # - default_env The same as CONDA_DEFAULT_ENV. + # - name The last segment of CONDA_PREFIX. + # - stacked_env Comma-separated list of names in the environment stack. The first element is + # always the same as default_env. + # + # Note: '({default_env}) ' is the default value of env_prompt. + # + # The default value of POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION expands to $CONDA_PROMPT_MODIFIER + # without the surrounding parentheses, or to the last path component of CONDA_PREFIX if the former + # is empty. + typeset -g POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION='${${${${CONDA_PROMPT_MODIFIER#\(}% }%\)}:-${CONDA_PREFIX:t}}' + + # Custom icon. + # typeset -g POWERLEVEL9K_ANACONDA_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ pyenv: python environment (https://github.com/pyenv/pyenv) ]################ + # Pyenv color. + typeset -g POWERLEVEL9K_PYENV_FOREGROUND=37 + # Hide python version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_PYENV_SOURCES=(shell local global) + # If set to false, hide python version if it's the same as global: + # $(pyenv version-name) == $(pyenv global). + typeset -g POWERLEVEL9K_PYENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide python version if it's equal to "system". + typeset -g POWERLEVEL9K_PYENV_SHOW_SYSTEM=true + + # Pyenv segment format. The following parameters are available within the expansion. + # + # - P9K_CONTENT Current pyenv environment (pyenv version-name). + # - P9K_PYENV_PYTHON_VERSION Current python version (python --version). + # + # The default format has the following logic: + # + # 1. Display just "$P9K_CONTENT" if it's equal to "$P9K_PYENV_PYTHON_VERSION" or + # starts with "$P9K_PYENV_PYTHON_VERSION/". + # 2. Otherwise display "$P9K_CONTENT $P9K_PYENV_PYTHON_VERSION". + typeset -g POWERLEVEL9K_PYENV_CONTENT_EXPANSION='${P9K_CONTENT}${${P9K_CONTENT:#$P9K_PYENV_PYTHON_VERSION(|/*)}:+ $P9K_PYENV_PYTHON_VERSION}' + + # Custom icon. + # typeset -g POWERLEVEL9K_PYENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ goenv: go environment (https://github.com/syndbg/goenv) ]################ + # Goenv color. + typeset -g POWERLEVEL9K_GOENV_FOREGROUND=37 + # Hide go version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_GOENV_SOURCES=(shell local global) + # If set to false, hide go version if it's the same as global: + # $(goenv version-name) == $(goenv global). + typeset -g POWERLEVEL9K_GOENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide go version if it's equal to "system". + typeset -g POWERLEVEL9K_GOENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_GOENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ nodenv: node.js version from nodenv (https://github.com/nodenv/nodenv) ]########## + # Nodenv color. + typeset -g POWERLEVEL9K_NODENV_FOREGROUND=70 + # Hide node version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_NODENV_SOURCES=(shell local global) + # If set to false, hide node version if it's the same as global: + # $(nodenv version-name) == $(nodenv global). + typeset -g POWERLEVEL9K_NODENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide node version if it's equal to "system". + typeset -g POWERLEVEL9K_NODENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_NODENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##############[ nvm: node.js version from nvm (https://github.com/nvm-sh/nvm) ]############### + # Nvm color. + typeset -g POWERLEVEL9K_NVM_FOREGROUND=70 + # If set to false, hide node version if it's the same as default: + # $(nvm version current) == $(nvm version default). + typeset -g POWERLEVEL9K_NVM_PROMPT_ALWAYS_SHOW=false + # If set to false, hide node version if it's equal to "system". + typeset -g POWERLEVEL9K_NVM_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_NVM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ############[ nodeenv: node.js environment (https://github.com/ekalinin/nodeenv) ]############ + # Nodeenv color. + typeset -g POWERLEVEL9K_NODEENV_FOREGROUND=70 + # Don't show Node version next to the environment name. + typeset -g POWERLEVEL9K_NODEENV_SHOW_NODE_VERSION=false + # Separate environment name from Node version only with a space. + typeset -g POWERLEVEL9K_NODEENV_{LEFT,RIGHT}_DELIMITER= + # Custom icon. + # typeset -g POWERLEVEL9K_NODEENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##############################[ node_version: node.js version ]############################### + # Node version color. + typeset -g POWERLEVEL9K_NODE_VERSION_FOREGROUND=70 + # Show node version only when in a directory tree containing package.json. + typeset -g POWERLEVEL9K_NODE_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_NODE_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######################[ go_version: go version (https://golang.org) ]######################## + # Go version color. + typeset -g POWERLEVEL9K_GO_VERSION_FOREGROUND=37 + # Show go version only when in a go project subdirectory. + typeset -g POWERLEVEL9K_GO_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_GO_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #################[ rust_version: rustc version (https://www.rust-lang.org) ]################## + # Rust version color. + typeset -g POWERLEVEL9K_RUST_VERSION_FOREGROUND=37 + # Show rust version only when in a rust project subdirectory. + typeset -g POWERLEVEL9K_RUST_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_RUST_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###############[ dotnet_version: .NET version (https://dotnet.microsoft.com) ]################ + # .NET version color. + typeset -g POWERLEVEL9K_DOTNET_VERSION_FOREGROUND=134 + # Show .NET version only when in a .NET project subdirectory. + typeset -g POWERLEVEL9K_DOTNET_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_DOTNET_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #####################[ php_version: php version (https://www.php.net/) ]###################### + # PHP version color. + typeset -g POWERLEVEL9K_PHP_VERSION_FOREGROUND=99 + # Show PHP version only when in a PHP project subdirectory. + typeset -g POWERLEVEL9K_PHP_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_PHP_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ laravel_version: laravel php framework version (https://laravel.com/) ]########### + # Laravel version color. + typeset -g POWERLEVEL9K_LARAVEL_VERSION_FOREGROUND=161 + # Custom icon. + # typeset -g POWERLEVEL9K_LARAVEL_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ####################[ java_version: java version (https://www.java.com/) ]#################### + # Java version color. + typeset -g POWERLEVEL9K_JAVA_VERSION_FOREGROUND=32 + # Show java version only when in a java project subdirectory. + typeset -g POWERLEVEL9K_JAVA_VERSION_PROJECT_ONLY=true + # Show brief version. + typeset -g POWERLEVEL9K_JAVA_VERSION_FULL=false + # Custom icon. + # typeset -g POWERLEVEL9K_JAVA_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###[ package: name@version from package.json (https://docs.npmjs.com/files/package.json) ]#### + # Package color. + typeset -g POWERLEVEL9K_PACKAGE_FOREGROUND=117 + # Package format. The following parameters are available within the expansion. + # + # - P9K_PACKAGE_NAME The value of `name` field in package.json. + # - P9K_PACKAGE_VERSION The value of `version` field in package.json. + # + # typeset -g POWERLEVEL9K_PACKAGE_CONTENT_EXPANSION='${P9K_PACKAGE_NAME//\%/%%}@${P9K_PACKAGE_VERSION//\%/%%}' + # Custom icon. + # typeset -g POWERLEVEL9K_PACKAGE_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #############[ rbenv: ruby version from rbenv (https://github.com/rbenv/rbenv) ]############## + # Rbenv color. + typeset -g POWERLEVEL9K_RBENV_FOREGROUND=168 + # Hide ruby version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_RBENV_SOURCES=(shell local global) + # If set to false, hide ruby version if it's the same as global: + # $(rbenv version-name) == $(rbenv global). + typeset -g POWERLEVEL9K_RBENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide ruby version if it's equal to "system". + typeset -g POWERLEVEL9K_RBENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_RBENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######################[ rvm: ruby version from rvm (https://rvm.io) ]######################## + # Rvm color. + typeset -g POWERLEVEL9K_RVM_FOREGROUND=168 + # Don't show @gemset at the end. + typeset -g POWERLEVEL9K_RVM_SHOW_GEMSET=false + # Don't show ruby- at the front. + typeset -g POWERLEVEL9K_RVM_SHOW_PREFIX=false + # Custom icon. + # typeset -g POWERLEVEL9K_RVM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ fvm: flutter version management (https://github.com/leoafarias/fvm) ]############ + # Fvm color. + typeset -g POWERLEVEL9K_FVM_FOREGROUND=38 + # Custom icon. + # typeset -g POWERLEVEL9K_FVM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ luaenv: lua version from luaenv (https://github.com/cehoffman/luaenv) ]########### + # Lua color. + typeset -g POWERLEVEL9K_LUAENV_FOREGROUND=32 + # Hide lua version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_LUAENV_SOURCES=(shell local global) + # If set to false, hide lua version if it's the same as global: + # $(luaenv version-name) == $(luaenv global). + typeset -g POWERLEVEL9K_LUAENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide lua version if it's equal to "system". + typeset -g POWERLEVEL9K_LUAENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_LUAENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###############[ jenv: java version from jenv (https://github.com/jenv/jenv) ]################ + # Java color. + typeset -g POWERLEVEL9K_JENV_FOREGROUND=32 + # Hide java version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_JENV_SOURCES=(shell local global) + # If set to false, hide java version if it's the same as global: + # $(jenv version-name) == $(jenv global). + typeset -g POWERLEVEL9K_JENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide java version if it's equal to "system". + typeset -g POWERLEVEL9K_JENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_JENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ plenv: perl version from plenv (https://github.com/tokuhirom/plenv) ]############ + # Perl color. + typeset -g POWERLEVEL9K_PLENV_FOREGROUND=67 + # Hide perl version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_PLENV_SOURCES=(shell local global) + # If set to false, hide perl version if it's the same as global: + # $(plenv version-name) == $(plenv global). + typeset -g POWERLEVEL9K_PLENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide perl version if it's equal to "system". + typeset -g POWERLEVEL9K_PLENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_PLENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ perlbrew: perl version from perlbrew (https://github.com/gugod/App-perlbrew) ]############ + # Perlbrew color. + typeset -g POWERLEVEL9K_PERLBREW_FOREGROUND=67 + # Show perlbrew version only when in a perl project subdirectory. + typeset -g POWERLEVEL9K_PERLBREW_PROJECT_ONLY=true + # Don't show "perl-" at the front. + typeset -g POWERLEVEL9K_PERLBREW_SHOW_PREFIX=false + # Custom icon. + # typeset -g POWERLEVEL9K_PERLBREW_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ############[ phpenv: php version from phpenv (https://github.com/phpenv/phpenv) ]############ + # PHP color. + typeset -g POWERLEVEL9K_PHPENV_FOREGROUND=99 + # Hide php version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_PHPENV_SOURCES=(shell local global) + # If set to false, hide php version if it's the same as global: + # $(phpenv version-name) == $(phpenv global). + typeset -g POWERLEVEL9K_PHPENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide php version if it's equal to "system". + typeset -g POWERLEVEL9K_PHPENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_PHPENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######[ scalaenv: scala version from scalaenv (https://github.com/scalaenv/scalaenv) ]####### + # Scala color. + typeset -g POWERLEVEL9K_SCALAENV_FOREGROUND=160 + # Hide scala version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_SCALAENV_SOURCES=(shell local global) + # If set to false, hide scala version if it's the same as global: + # $(scalaenv version-name) == $(scalaenv global). + typeset -g POWERLEVEL9K_SCALAENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide scala version if it's equal to "system". + typeset -g POWERLEVEL9K_SCALAENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_SCALAENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ haskell_stack: haskell version from stack (https://haskellstack.org/) ]########### + # Haskell color. + typeset -g POWERLEVEL9K_HASKELL_STACK_FOREGROUND=172 + # Hide haskell version if it doesn't come from one of these sources. + # + # shell: version is set by STACK_YAML + # local: version is set by stack.yaml up the directory tree + # global: version is set by the implicit global project (~/.stack/global-project/stack.yaml) + typeset -g POWERLEVEL9K_HASKELL_STACK_SOURCES=(shell local) + # If set to false, hide haskell version if it's the same as in the implicit global project. + typeset -g POWERLEVEL9K_HASKELL_STACK_ALWAYS_SHOW=true + # Custom icon. + # typeset -g POWERLEVEL9K_HASKELL_STACK_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #############[ kubecontext: current kubernetes context (https://kubernetes.io/) ]############# + # Show kubecontext only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show kubecontext. + typeset -g POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND='kubectl|helm|kubens|kubectx|oc|istioctl|kogito|k9s|helmfile|flux|fluxctl|stern|kubeseal|skaffold|kubent|kubecolor|cmctl|sparkctl' + + # Kubernetes context classes for the purpose of using different colors, icons and expansions with + # different contexts. + # + # POWERLEVEL9K_KUBECONTEXT_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current kubernetes context gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_KUBECONTEXT_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_KUBECONTEXT_CLASSES defines the context class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' DEFAULT) + # + # If your current kubernetes context is "deathray-testing/default", its class is TEST + # because "deathray-testing/default" doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_FOREGROUND=28 + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' DEFAULT) + typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_FOREGROUND=134 + # typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Use POWERLEVEL9K_KUBECONTEXT_CONTENT_EXPANSION to specify the content displayed by kubecontext + # segment. Parameter expansions are very flexible and fast, too. See reference: + # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion. + # + # Within the expansion the following parameters are always available: + # + # - P9K_CONTENT The content that would've been displayed if there was no content + # expansion defined. + # - P9K_KUBECONTEXT_NAME The current context's name. Corresponds to column NAME in the + # output of `kubectl config get-contexts`. + # - P9K_KUBECONTEXT_CLUSTER The current context's cluster. Corresponds to column CLUSTER in the + # output of `kubectl config get-contexts`. + # - P9K_KUBECONTEXT_NAMESPACE The current context's namespace. Corresponds to column NAMESPACE + # in the output of `kubectl config get-contexts`. If there is no + # namespace, the parameter is set to "default". + # - P9K_KUBECONTEXT_USER The current context's user. Corresponds to column AUTHINFO in the + # output of `kubectl config get-contexts`. + # + # If the context points to Google Kubernetes Engine (GKE) or Elastic Kubernetes Service (EKS), + # the following extra parameters are available: + # + # - P9K_KUBECONTEXT_CLOUD_NAME Either "gke" or "eks". + # - P9K_KUBECONTEXT_CLOUD_ACCOUNT Account/project ID. + # - P9K_KUBECONTEXT_CLOUD_ZONE Availability zone. + # - P9K_KUBECONTEXT_CLOUD_CLUSTER Cluster. + # + # P9K_KUBECONTEXT_CLOUD_* parameters are derived from P9K_KUBECONTEXT_CLUSTER. For example, + # if P9K_KUBECONTEXT_CLUSTER is "gke_my-account_us-east1-a_my-cluster-01": + # + # - P9K_KUBECONTEXT_CLOUD_NAME=gke + # - P9K_KUBECONTEXT_CLOUD_ACCOUNT=my-account + # - P9K_KUBECONTEXT_CLOUD_ZONE=us-east1-a + # - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01 + # + # If P9K_KUBECONTEXT_CLUSTER is "arn:aws:eks:us-east-1:123456789012:cluster/my-cluster-01": + # + # - P9K_KUBECONTEXT_CLOUD_NAME=eks + # - P9K_KUBECONTEXT_CLOUD_ACCOUNT=123456789012 + # - P9K_KUBECONTEXT_CLOUD_ZONE=us-east-1 + # - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01 + typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION= + # Show P9K_KUBECONTEXT_CLOUD_CLUSTER if it's not empty and fall back to P9K_KUBECONTEXT_NAME. + POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${P9K_KUBECONTEXT_CLOUD_CLUSTER:-${P9K_KUBECONTEXT_NAME}}' + # Append the current context's namespace if it's not "default". + POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${${:-/$P9K_KUBECONTEXT_NAMESPACE}:#/default}' + + # Custom prefix. + # typeset -g POWERLEVEL9K_KUBECONTEXT_PREFIX='%fat ' + + ################[ terraform: terraform workspace (https://www.terraform.io) ]################# + # Don't show terraform workspace if it's literally "default". + typeset -g POWERLEVEL9K_TERRAFORM_SHOW_DEFAULT=false + # POWERLEVEL9K_TERRAFORM_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current terraform workspace gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_TERRAFORM_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_TERRAFORM_CLASSES defines the workspace class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' OTHER) + # + # If your current terraform workspace is "project_test", its class is TEST because "project_test" + # doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_FOREGROUND=28 + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' OTHER) + typeset -g POWERLEVEL9K_TERRAFORM_OTHER_FOREGROUND=38 + # typeset -g POWERLEVEL9K_TERRAFORM_OTHER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #############[ terraform_version: terraform version (https://www.terraform.io) ]############## + # Terraform version color. + typeset -g POWERLEVEL9K_TERRAFORM_VERSION_FOREGROUND=38 + # Custom icon. + # typeset -g POWERLEVEL9K_TERRAFORM_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #[ aws: aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) ]# + # Show aws only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show aws. + typeset -g POWERLEVEL9K_AWS_SHOW_ON_COMMAND='aws|awless|terraform|pulumi|terragrunt' + + # POWERLEVEL9K_AWS_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current AWS profile gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_AWS_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_AWS_CLASSES defines the profile class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_AWS_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' DEFAULT) + # + # If your current AWS profile is "company_test", its class is TEST + # because "company_test" doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_AWS_TEST_FOREGROUND=28 + # typeset -g POWERLEVEL9K_AWS_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_AWS_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_AWS_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' DEFAULT) + typeset -g POWERLEVEL9K_AWS_DEFAULT_FOREGROUND=208 + # typeset -g POWERLEVEL9K_AWS_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # AWS segment format. The following parameters are available within the expansion. + # + # - P9K_AWS_PROFILE The name of the current AWS profile. + # - P9K_AWS_REGION The region associated with the current AWS profile. + typeset -g POWERLEVEL9K_AWS_CONTENT_EXPANSION='${P9K_AWS_PROFILE//\%/%%}${P9K_AWS_REGION:+ ${P9K_AWS_REGION//\%/%%}}' + + #[ aws_eb_env: aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) ]# + # AWS Elastic Beanstalk environment color. + typeset -g POWERLEVEL9K_AWS_EB_ENV_FOREGROUND=70 + # Custom icon. + # typeset -g POWERLEVEL9K_AWS_EB_ENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ azure: azure account name (https://docs.microsoft.com/en-us/cli/azure) ]########## + # Show azure only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show azure. + typeset -g POWERLEVEL9K_AZURE_SHOW_ON_COMMAND='az|terraform|pulumi|terragrunt' + + # POWERLEVEL9K_AZURE_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current azure account name gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_AZURE_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_AZURE_CLASSES defines the account class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_AZURE_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' OTHER) + # + # If your current azure account is "company_test", its class is TEST because "company_test" + # doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_AZURE_TEST_FOREGROUND=28 + # typeset -g POWERLEVEL9K_AZURE_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_AZURE_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_AZURE_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' OTHER) + + # Azure account name color. + typeset -g POWERLEVEL9K_AZURE_OTHER_FOREGROUND=32 + # Custom icon. + # typeset -g POWERLEVEL9K_AZURE_OTHER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ gcloud: google cloud account and project (https://cloud.google.com/) ]########### + # Show gcloud only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show gcloud. + typeset -g POWERLEVEL9K_GCLOUD_SHOW_ON_COMMAND='gcloud|gcs|gsutil' + # Google cloud color. + typeset -g POWERLEVEL9K_GCLOUD_FOREGROUND=32 + + # Google cloud format. Change the value of POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION and/or + # POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION if the default is too verbose or not informative + # enough. You can use the following parameters in the expansions. Each of them corresponds to the + # output of `gcloud` tool. + # + # Parameter | Source + # -------------------------|-------------------------------------------------------------------- + # P9K_GCLOUD_CONFIGURATION | gcloud config configurations list --format='value(name)' + # P9K_GCLOUD_ACCOUNT | gcloud config get-value account + # P9K_GCLOUD_PROJECT_ID | gcloud config get-value project + # P9K_GCLOUD_PROJECT_NAME | gcloud projects describe $P9K_GCLOUD_PROJECT_ID --format='value(name)' + # + # Note: ${VARIABLE//\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced with '%%'. + # + # Obtaining project name requires sending a request to Google servers. This can take a long time + # and even fail. When project name is unknown, P9K_GCLOUD_PROJECT_NAME is not set and gcloud + # prompt segment is in state PARTIAL. When project name gets known, P9K_GCLOUD_PROJECT_NAME gets + # set and gcloud prompt segment transitions to state COMPLETE. + # + # You can customize the format, icon and colors of gcloud segment separately for states PARTIAL + # and COMPLETE. You can also hide gcloud in state PARTIAL by setting + # POWERLEVEL9K_GCLOUD_PARTIAL_VISUAL_IDENTIFIER_EXPANSION and + # POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION to empty. + typeset -g POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_ID//\%/%%}' + typeset -g POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_NAME//\%/%%}' + + # Send a request to Google (by means of `gcloud projects describe ...`) to obtain project name + # this often. Negative value disables periodic polling. In this mode project name is retrieved + # only when the current configuration, account or project id changes. + typeset -g POWERLEVEL9K_GCLOUD_REFRESH_PROJECT_NAME_SECONDS=60 + + # Custom icon. + # typeset -g POWERLEVEL9K_GCLOUD_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #[ google_app_cred: google application credentials (https://cloud.google.com/docs/authentication/production) ]# + # Show google_app_cred only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show google_app_cred. + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_SHOW_ON_COMMAND='terraform|pulumi|terragrunt' + + # Google application credentials classes for the purpose of using different colors, icons and + # expansions with different credentials. + # + # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES is an array with even number of elements. The first + # element in each pair defines a pattern against which the current kubernetes context gets + # matched. More specifically, it's P9K_CONTENT prior to the application of context expansion + # (see below) that gets matched. If you unset all POWERLEVEL9K_GOOGLE_APP_CRED_*CONTENT_EXPANSION + # parameters, you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES defines the context class. Patterns are tried in order. + # The first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=( + # '*:*prod*:*' PROD + # '*:*test*:*' TEST + # '*' DEFAULT) + # + # If your current Google application credentials is "service_account deathray-testing x@y.com", + # its class is TEST because it doesn't match the pattern '* *prod* *' but does match '* *test* *'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_FOREGROUND=28 + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_CONTENT_EXPANSION='$P9K_GOOGLE_APP_CRED_PROJECT_ID' + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=( + # '*:*prod*:*' PROD # These values are examples that are unlikely + # '*:*test*:*' TEST # to match your needs. Customize them as needed. + '*' DEFAULT) + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_FOREGROUND=32 + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Use POWERLEVEL9K_GOOGLE_APP_CRED_CONTENT_EXPANSION to specify the content displayed by + # google_app_cred segment. Parameter expansions are very flexible and fast, too. See reference: + # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion. + # + # You can use the following parameters in the expansion. Each of them corresponds to one of the + # fields in the JSON file pointed to by GOOGLE_APPLICATION_CREDENTIALS. + # + # Parameter | JSON key file field + # ---------------------------------+--------------- + # P9K_GOOGLE_APP_CRED_TYPE | type + # P9K_GOOGLE_APP_CRED_PROJECT_ID | project_id + # P9K_GOOGLE_APP_CRED_CLIENT_EMAIL | client_email + # + # Note: ${VARIABLE//\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced by '%%'. + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_CONTENT_EXPANSION='${P9K_GOOGLE_APP_CRED_PROJECT_ID//\%/%%}' + + ##############[ toolbox: toolbox name (https://github.com/containers/toolbox) ]############### + # Toolbox color. + typeset -g POWERLEVEL9K_TOOLBOX_FOREGROUND=178 + # Don't display the name of the toolbox if it matches fedora-toolbox-*. + typeset -g POWERLEVEL9K_TOOLBOX_CONTENT_EXPANSION='${P9K_TOOLBOX_NAME:#fedora-toolbox-*}' + # Custom icon. + # typeset -g POWERLEVEL9K_TOOLBOX_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_TOOLBOX_PREFIX='%fin ' + + ###############################[ public_ip: public IP address ]############################### + # Public IP color. + typeset -g POWERLEVEL9K_PUBLIC_IP_FOREGROUND=94 + # Custom icon. + # typeset -g POWERLEVEL9K_PUBLIC_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ########################[ vpn_ip: virtual private network indicator ]######################### + # VPN IP color. + typeset -g POWERLEVEL9K_VPN_IP_FOREGROUND=81 + # When on VPN, show just an icon without the IP address. + # Tip: To display the private IP address when on VPN, remove the next line. + typeset -g POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION= + # Regular expression for the VPN network interface. Run `ifconfig` or `ip -4 a show` while on VPN + # to see the name of the interface. + typeset -g POWERLEVEL9K_VPN_IP_INTERFACE='(gpd|wg|(.*tun)|tailscale)[0-9]*|(zt.*)' + # If set to true, show one segment per matching network interface. If set to false, show only + # one segment corresponding to the first matching network interface. + # Tip: If you set it to true, you'll probably want to unset POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION. + typeset -g POWERLEVEL9K_VPN_IP_SHOW_ALL=false + # Custom icon. + # typeset -g POWERLEVEL9K_VPN_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ ip: ip address and bandwidth usage for a specified network interface ]########### + # IP color. + typeset -g POWERLEVEL9K_IP_FOREGROUND=38 + # The following parameters are accessible within the expansion: + # + # Parameter | Meaning + # ----------------------+------------------------------------------- + # P9K_IP_IP | IP address + # P9K_IP_INTERFACE | network interface + # P9K_IP_RX_BYTES | total number of bytes received + # P9K_IP_TX_BYTES | total number of bytes sent + # P9K_IP_RX_BYTES_DELTA | number of bytes received since last prompt + # P9K_IP_TX_BYTES_DELTA | number of bytes sent since last prompt + # P9K_IP_RX_RATE | receive rate (since last prompt) + # P9K_IP_TX_RATE | send rate (since last prompt) + typeset -g POWERLEVEL9K_IP_CONTENT_EXPANSION='$P9K_IP_IP${P9K_IP_RX_RATE:+ %70F⇣$P9K_IP_RX_RATE}${P9K_IP_TX_RATE:+ %215F⇡$P9K_IP_TX_RATE}' + # Show information for the first network interface whose name matches this regular expression. + # Run `ifconfig` or `ip -4 a show` to see the names of all network interfaces. + typeset -g POWERLEVEL9K_IP_INTERFACE='[ew].*' + # Custom icon. + # typeset -g POWERLEVEL9K_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #########################[ proxy: system-wide http/https/ftp proxy ]########################## + # Proxy color. + typeset -g POWERLEVEL9K_PROXY_FOREGROUND=68 + # Custom icon. + # typeset -g POWERLEVEL9K_PROXY_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################################[ battery: internal battery ]################################# + # Show battery in red when it's below this level and not connected to power supply. + typeset -g POWERLEVEL9K_BATTERY_LOW_THRESHOLD=20 + typeset -g POWERLEVEL9K_BATTERY_LOW_FOREGROUND=160 + # Show battery in green when it's charging or fully charged. + typeset -g POWERLEVEL9K_BATTERY_{CHARGING,CHARGED}_FOREGROUND=70 + # Show battery in yellow when it's discharging. + typeset -g POWERLEVEL9K_BATTERY_DISCONNECTED_FOREGROUND=178 + # Battery pictograms going from low to high level of charge. + typeset -g POWERLEVEL9K_BATTERY_STAGES=('%K{232}▁' '%K{232}▂' '%K{232}▃' '%K{232}▄' '%K{232}▅' '%K{232}▆' '%K{232}▇' '%K{232}█') + # Don't show the remaining time to charge/discharge. + typeset -g POWERLEVEL9K_BATTERY_VERBOSE=false + + #####################################[ wifi: wifi speed ]##################################### + # WiFi color. + typeset -g POWERLEVEL9K_WIFI_FOREGROUND=68 + # Custom icon. + # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Use different colors and icons depending on signal strength ($P9K_WIFI_BARS). + # + # # Wifi colors and icons for different signal strength levels (low to high). + # typeset -g my_wifi_fg=(68 68 68 68 68) # <-- change these values + # typeset -g my_wifi_icon=('WiFi' 'WiFi' 'WiFi' 'WiFi' 'WiFi') # <-- change these values + # + # typeset -g POWERLEVEL9K_WIFI_CONTENT_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}$P9K_WIFI_LAST_TX_RATE Mbps' + # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}${my_wifi_icon[P9K_WIFI_BARS+1]}' + # + # The following parameters are accessible within the expansions: + # + # Parameter | Meaning + # ----------------------+--------------- + # P9K_WIFI_SSID | service set identifier, a.k.a. network name + # P9K_WIFI_LINK_AUTH | authentication protocol such as "wpa2-psk" or "none"; empty if unknown + # P9K_WIFI_LAST_TX_RATE | wireless transmit rate in megabits per second + # P9K_WIFI_RSSI | signal strength in dBm, from -120 to 0 + # P9K_WIFI_NOISE | noise in dBm, from -120 to 0 + # P9K_WIFI_BARS | signal strength in bars, from 0 to 4 (derived from P9K_WIFI_RSSI and P9K_WIFI_NOISE) + + ####################################[ time: current time ]#################################### + # Current time color. + typeset -g POWERLEVEL9K_TIME_FOREGROUND=66 + # Format for the current time: 09:51:02. See `man 3 strftime`. + typeset -g POWERLEVEL9K_TIME_FORMAT='%D{%H:%M:%S}' + # If set to true, time will update when you hit enter. This way prompts for the past + # commands will contain the start times of their commands as opposed to the default + # behavior where they contain the end times of their preceding commands. + typeset -g POWERLEVEL9K_TIME_UPDATE_ON_COMMAND=false + # Custom icon. + # typeset -g POWERLEVEL9K_TIME_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_TIME_PREFIX='%fat ' + + # Example of a user-defined prompt segment. Function prompt_example will be called on every + # prompt if `example` prompt segment is added to POWERLEVEL9K_LEFT_PROMPT_ELEMENTS or + # POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS. It displays an icon and orange text greeting the user. + # + # Type `p10k help segment` for documentation and a more sophisticated example. + function prompt_example() { + p10k segment -f 208 -i '⭐' -t 'hello, %n' + } + + # User-defined prompt segments may optionally provide an instant_prompt_* function. Its job + # is to generate the prompt segment for display in instant prompt. See + # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. + # + # Powerlevel10k will call instant_prompt_* at the same time as the regular prompt_* function + # and will record all `p10k segment` calls it makes. When displaying instant prompt, Powerlevel10k + # will replay these calls without actually calling instant_prompt_*. It is imperative that + # instant_prompt_* always makes the same `p10k segment` calls regardless of environment. If this + # rule is not observed, the content of instant prompt will be incorrect. + # + # Usually, you should either not define instant_prompt_* or simply call prompt_* from it. If + # instant_prompt_* is not defined for a segment, the segment won't be shown in instant prompt. + function instant_prompt_example() { + # Since prompt_example always makes the same `p10k segment` calls, we can call it from + # instant_prompt_example. This will give us the same `example` prompt segment in the instant + # and regular prompts. + prompt_example + } + + # User-defined prompt segments can be customized the same way as built-in segments. + # typeset -g POWERLEVEL9K_EXAMPLE_FOREGROUND=208 + # typeset -g POWERLEVEL9K_EXAMPLE_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Transient prompt works similarly to the builtin transient_rprompt option. It trims down prompt + # when accepting a command line. Supported values: + # + # - off: Don't change prompt when accepting a command line. + # - always: Trim down prompt when accepting a command line. + # - same-dir: Trim down prompt when accepting a command line unless this is the first command + # typed after changing current working directory. + typeset -g POWERLEVEL9K_TRANSIENT_PROMPT=off + + # Instant prompt mode. + # + # - off: Disable instant prompt. Choose this if you've tried instant prompt and found + # it incompatible with your zsh configuration files. + # - quiet: Enable instant prompt and don't print warnings when detecting console output + # during zsh initialization. Choose this if you've read and understood + # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. + # - verbose: Enable instant prompt and print a warning when detecting console output during + # zsh initialization. Choose this if you've never tried instant prompt, haven't + # seen the warning, or if you are unsure what this all means. + typeset -g POWERLEVEL9K_INSTANT_PROMPT=verbose + + # Hot reload allows you to change POWERLEVEL9K options after Powerlevel10k has been initialized. + # For example, you can type POWERLEVEL9K_BACKGROUND=red and see your prompt turn red. Hot reload + # can slow down prompt by 1-2 milliseconds, so it's better to keep it turned off unless you + # really need it. + typeset -g POWERLEVEL9K_DISABLE_HOT_RELOAD=true + + # If p10k is already loaded, reload configuration. + # This works even with POWERLEVEL9K_DISABLE_HOT_RELOAD=true. + (( ! $+functions[p10k] )) || p10k reload +} + +# Tell `p10k configure` which file it should overwrite. +typeset -g POWERLEVEL9K_CONFIG_FILE=${${(%):-%x}:a} + +(( ${#p10k_config_opts} )) && setopt ${p10k_config_opts[@]} +'builtin' 'unset' 'p10k_config_opts' diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-pure.zsh b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-pure.zsh new file mode 100644 index 00000000..97c1a207 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-pure.zsh @@ -0,0 +1,193 @@ +# Config file for Powerlevel10k with the style of Pure (https://github.com/sindresorhus/pure). +# +# Differences from Pure: +# +# - Git: +# - `@c4d3ec2c` instead of something like `v1.4.0~11` when in detached HEAD state. +# - No automatic `git fetch` (the same as in Pure with `PURE_GIT_PULL=0`). +# +# Apart from the differences listed above, the replication of Pure prompt is exact. This includes +# even the questionable parts. For example, just like in Pure, there is no indication of Git status +# being stale; prompt symbol is the same in command, visual and overwrite vi modes; when prompt +# doesn't fit on one line, it wraps around with no attempt to shorten it. +# +# If you like the general style of Pure but not particularly attached to all its quirks, type +# `p10k configure` and pick "Lean" style. This will give you slick minimalist prompt while taking +# advantage of Powerlevel10k features that aren't present in Pure. + +# Temporarily change options. +'builtin' 'local' '-a' 'p10k_config_opts' +[[ ! -o 'aliases' ]] || p10k_config_opts+=('aliases') +[[ ! -o 'sh_glob' ]] || p10k_config_opts+=('sh_glob') +[[ ! -o 'no_brace_expand' ]] || p10k_config_opts+=('no_brace_expand') +'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand' + +() { + emulate -L zsh -o extended_glob + + # Unset all configuration options. + unset -m '(POWERLEVEL9K_*|DEFAULT_USER)~POWERLEVEL9K_GITSTATUS_DIR' + + # Zsh >= 5.1 is required. + [[ $ZSH_VERSION == (5.<1->*|<6->.*) ]] || return + + # Prompt colors. + local grey=242 + local red=1 + local yellow=3 + local blue=4 + local magenta=5 + local cyan=6 + local white=7 + + # Left prompt segments. + typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=( + # =========================[ Line #1 ]========================= + context # user@host + dir # current directory + vcs # git status + command_execution_time # previous command duration + # =========================[ Line #2 ]========================= + newline # \n + virtualenv # python virtual environment + prompt_char # prompt symbol + ) + + # Right prompt segments. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=( + # =========================[ Line #1 ]========================= + # command_execution_time # previous command duration + # virtualenv # python virtual environment + # context # user@host + # time # current time + # =========================[ Line #2 ]========================= + newline # \n + ) + + # Basic style options that define the overall prompt look. + typeset -g POWERLEVEL9K_BACKGROUND= # transparent background + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_{LEFT,RIGHT}_WHITESPACE= # no surrounding whitespace + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SUBSEGMENT_SEPARATOR=' ' # separate segments with a space + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SEGMENT_SEPARATOR= # no end-of-line symbol + typeset -g POWERLEVEL9K_VISUAL_IDENTIFIER_EXPANSION= # no segment icons + + # Add an empty line before each prompt except the first. This doesn't emulate the bug + # in Pure that makes prompt drift down whenever you use the Alt-C binding from fzf or similar. + typeset -g POWERLEVEL9K_PROMPT_ADD_NEWLINE=true + + # Magenta prompt symbol if the last command succeeded. + typeset -g POWERLEVEL9K_PROMPT_CHAR_OK_{VIINS,VICMD,VIVIS}_FOREGROUND=$magenta + # Red prompt symbol if the last command failed. + typeset -g POWERLEVEL9K_PROMPT_CHAR_ERROR_{VIINS,VICMD,VIVIS}_FOREGROUND=$red + # Default prompt symbol. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION='❯' + # Prompt symbol in command vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VICMD_CONTENT_EXPANSION='❮' + # Prompt symbol in visual vi mode is the same as in command mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIVIS_CONTENT_EXPANSION='❮' + # Prompt symbol in overwrite vi mode is the same as in command mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_OVERWRITE_STATE=false + + # Grey Python Virtual Environment. + typeset -g POWERLEVEL9K_VIRTUALENV_FOREGROUND=$grey + # Don't show Python version. + typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_PYTHON_VERSION=false + typeset -g POWERLEVEL9K_VIRTUALENV_{LEFT,RIGHT}_DELIMITER= + + # Blue current directory. + typeset -g POWERLEVEL9K_DIR_FOREGROUND=$blue + + # Context format when root: user@host. The first part white, the rest grey. + typeset -g POWERLEVEL9K_CONTEXT_ROOT_TEMPLATE="%F{$white}%n%f%F{$grey}@%m%f" + # Context format when not root: user@host. The whole thing grey. + typeset -g POWERLEVEL9K_CONTEXT_TEMPLATE="%F{$grey}%n@%m%f" + # Don't show context unless root or in SSH. + typeset -g POWERLEVEL9K_CONTEXT_{DEFAULT,SUDO}_CONTENT_EXPANSION= + + # Show previous command duration only if it's >= 5s. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD=5 + # Don't show fractional seconds. Thus, 7s rather than 7.3s. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PRECISION=0 + # Duration format: 1d 2h 3m 4s. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FORMAT='d h m s' + # Yellow previous command duration. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FOREGROUND=$yellow + + # Grey Git prompt. This makes stale prompts indistinguishable from up-to-date ones. + typeset -g POWERLEVEL9K_VCS_FOREGROUND=$grey + + # Disable async loading indicator to make directories that aren't Git repositories + # indistinguishable from large Git repositories without known state. + typeset -g POWERLEVEL9K_VCS_LOADING_TEXT= + + # Don't wait for Git status even for a millisecond, so that prompt always updates + # asynchronously when Git state changes. + typeset -g POWERLEVEL9K_VCS_MAX_SYNC_LATENCY_SECONDS=0 + + # Cyan ahead/behind arrows. + typeset -g POWERLEVEL9K_VCS_{INCOMING,OUTGOING}_CHANGESFORMAT_FOREGROUND=$cyan + # Don't show remote branch, current tag or stashes. + typeset -g POWERLEVEL9K_VCS_GIT_HOOKS=(vcs-detect-changes git-untracked git-aheadbehind) + # Don't show the branch icon. + typeset -g POWERLEVEL9K_VCS_BRANCH_ICON= + # When in detached HEAD state, show @commit where branch normally goes. + typeset -g POWERLEVEL9K_VCS_COMMIT_ICON='@' + # Don't show staged, unstaged, untracked indicators. + typeset -g POWERLEVEL9K_VCS_{STAGED,UNSTAGED,UNTRACKED}_ICON= + # Show '*' when there are staged, unstaged or untracked files. + typeset -g POWERLEVEL9K_VCS_DIRTY_ICON='*' + # Show '⇣' if local branch is behind remote. + typeset -g POWERLEVEL9K_VCS_INCOMING_CHANGES_ICON=':⇣' + # Show '⇡' if local branch is ahead of remote. + typeset -g POWERLEVEL9K_VCS_OUTGOING_CHANGES_ICON=':⇡' + # Don't show the number of commits next to the ahead/behind arrows. + typeset -g POWERLEVEL9K_VCS_{COMMITS_AHEAD,COMMITS_BEHIND}_MAX_NUM=1 + # Remove space between '⇣' and '⇡' and all trailing spaces. + typeset -g POWERLEVEL9K_VCS_CONTENT_EXPANSION='${${${P9K_CONTENT/⇣* :⇡/⇣⇡}// }//:/ }' + + # Grey current time. + typeset -g POWERLEVEL9K_TIME_FOREGROUND=$grey + # Format for the current time: 09:51:02. See `man 3 strftime`. + typeset -g POWERLEVEL9K_TIME_FORMAT='%D{%H:%M:%S}' + # If set to true, time will update when you hit enter. This way prompts for the past + # commands will contain the start times of their commands rather than the end times of + # their preceding commands. + typeset -g POWERLEVEL9K_TIME_UPDATE_ON_COMMAND=false + + # Transient prompt works similarly to the builtin transient_rprompt option. It trims down prompt + # when accepting a command line. Supported values: + # + # - off: Don't change prompt when accepting a command line. + # - always: Trim down prompt when accepting a command line. + # - same-dir: Trim down prompt when accepting a command line unless this is the first command + # typed after changing current working directory. + typeset -g POWERLEVEL9K_TRANSIENT_PROMPT=off + + # Instant prompt mode. + # + # - off: Disable instant prompt. Choose this if you've tried instant prompt and found + # it incompatible with your zsh configuration files. + # - quiet: Enable instant prompt and don't print warnings when detecting console output + # during zsh initialization. Choose this if you've read and understood + # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. + # - verbose: Enable instant prompt and print a warning when detecting console output during + # zsh initialization. Choose this if you've never tried instant prompt, haven't + # seen the warning, or if you are unsure what this all means. + typeset -g POWERLEVEL9K_INSTANT_PROMPT=verbose + + # Hot reload allows you to change POWERLEVEL9K options after Powerlevel10k has been initialized. + # For example, you can type POWERLEVEL9K_BACKGROUND=red and see your prompt turn red. Hot reload + # can slow down prompt by 1-2 milliseconds, so it's better to keep it turned off unless you + # really need it. + typeset -g POWERLEVEL9K_DISABLE_HOT_RELOAD=true + + # If p10k is already loaded, reload configuration. + # This works even with POWERLEVEL9K_DISABLE_HOT_RELOAD=true. + (( ! $+functions[p10k] )) || p10k reload +} + +# Tell `p10k configure` which file it should overwrite. +typeset -g POWERLEVEL9K_CONFIG_FILE=${${(%):-%x}:a} + +(( ${#p10k_config_opts} )) && setopt ${p10k_config_opts[@]} +'builtin' 'unset' 'p10k_config_opts' diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-rainbow.zsh b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-rainbow.zsh new file mode 100644 index 00000000..ab36838f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-rainbow.zsh @@ -0,0 +1,1825 @@ +# Config for Powerlevel10k with powerline prompt style with colorful background. +# Type `p10k configure` to generate your own config based on it. +# +# Tip: Looking for a nice color? Here's a one-liner to print colormap. +# +# for i in {0..255}; do print -Pn "%K{$i} %k%F{$i}${(l:3::0:)i}%f " ${${(M)$((i%6)):#3}:+$'\n'}; done + +# Temporarily change options. +'builtin' 'local' '-a' 'p10k_config_opts' +[[ ! -o 'aliases' ]] || p10k_config_opts+=('aliases') +[[ ! -o 'sh_glob' ]] || p10k_config_opts+=('sh_glob') +[[ ! -o 'no_brace_expand' ]] || p10k_config_opts+=('no_brace_expand') +'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand' + +() { + emulate -L zsh -o extended_glob + + # Unset all configuration options. This allows you to apply configuration changes without + # restarting zsh. Edit ~/.p10k.zsh and type `source ~/.p10k.zsh`. + unset -m '(POWERLEVEL9K_*|DEFAULT_USER)~POWERLEVEL9K_GITSTATUS_DIR' + + # Zsh >= 5.1 is required. + [[ $ZSH_VERSION == (5.<1->*|<6->.*) ]] || return + + # The list of segments shown on the left. Fill it with the most important segments. + typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=( + # =========================[ Line #1 ]========================= + # os_icon # os identifier + dir # current directory + vcs # git status + # =========================[ Line #2 ]========================= + newline # \n + # prompt_char # prompt symbol + ) + + # The list of segments shown on the right. Fill it with less important segments. + # Right prompt on the last prompt line (where you are typing your commands) gets + # automatically hidden when the input line reaches it. Right prompt above the + # last prompt line gets hidden if it would overlap with left prompt. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=( + # =========================[ Line #1 ]========================= + status # exit code of the last command + command_execution_time # duration of the last command + background_jobs # presence of background jobs + direnv # direnv status (https://direnv.net/) + asdf # asdf version manager (https://github.com/asdf-vm/asdf) + virtualenv # python virtual environment (https://docs.python.org/3/library/venv.html) + anaconda # conda environment (https://conda.io/) + pyenv # python environment (https://github.com/pyenv/pyenv) + goenv # go environment (https://github.com/syndbg/goenv) + nodenv # node.js version from nodenv (https://github.com/nodenv/nodenv) + nvm # node.js version from nvm (https://github.com/nvm-sh/nvm) + nodeenv # node.js environment (https://github.com/ekalinin/nodeenv) + # node_version # node.js version + # go_version # go version (https://golang.org) + # rust_version # rustc version (https://www.rust-lang.org) + # dotnet_version # .NET version (https://dotnet.microsoft.com) + # php_version # php version (https://www.php.net/) + # laravel_version # laravel php framework version (https://laravel.com/) + # java_version # java version (https://www.java.com/) + # package # name@version from package.json (https://docs.npmjs.com/files/package.json) + rbenv # ruby version from rbenv (https://github.com/rbenv/rbenv) + rvm # ruby version from rvm (https://rvm.io) + fvm # flutter version management (https://github.com/leoafarias/fvm) + luaenv # lua version from luaenv (https://github.com/cehoffman/luaenv) + jenv # java version from jenv (https://github.com/jenv/jenv) + plenv # perl version from plenv (https://github.com/tokuhirom/plenv) + perlbrew # perl version from perlbrew (https://github.com/gugod/App-perlbrew) + phpenv # php version from phpenv (https://github.com/phpenv/phpenv) + scalaenv # scala version from scalaenv (https://github.com/scalaenv/scalaenv) + haskell_stack # haskell version from stack (https://haskellstack.org/) + kubecontext # current kubernetes context (https://kubernetes.io/) + terraform # terraform workspace (https://www.terraform.io) + # terraform_version # terraform version (https://www.terraform.io) + aws # aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) + aws_eb_env # aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) + azure # azure account name (https://docs.microsoft.com/en-us/cli/azure) + gcloud # google cloud cli account and project (https://cloud.google.com/) + google_app_cred # google application credentials (https://cloud.google.com/docs/authentication/production) + toolbox # toolbox name (https://github.com/containers/toolbox) + context # user@hostname + nordvpn # nordvpn connection status, linux only (https://nordvpn.com/) + ranger # ranger shell (https://github.com/ranger/ranger) + nnn # nnn shell (https://github.com/jarun/nnn) + lf # lf shell (https://github.com/gokcehan/lf) + xplr # xplr shell (https://github.com/sayanarijit/xplr) + vim_shell # vim shell indicator (:sh) + midnight_commander # midnight commander shell (https://midnight-commander.org/) + nix_shell # nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) + chezmoi_shell # chezmoi shell (https://www.chezmoi.io/) + # vi_mode # vi mode (you don't need this if you've enabled prompt_char) + # vpn_ip # virtual private network indicator + # load # CPU load + # disk_usage # disk usage + # ram # free RAM + # swap # used swap + todo # todo items (https://github.com/todotxt/todo.txt-cli) + timewarrior # timewarrior tracking status (https://timewarrior.net/) + taskwarrior # taskwarrior task count (https://taskwarrior.org/) + per_directory_history # Oh My Zsh per-directory-history local/global indicator + # cpu_arch # CPU architecture + # time # current time + # =========================[ Line #2 ]========================= + newline + # ip # ip address and bandwidth usage for a specified network interface + # public_ip # public IP address + # proxy # system-wide http/https/ftp proxy + # battery # internal battery + # wifi # wifi speed + # example # example user-defined segment (see prompt_example function below) + ) + + # Defines character set used by powerlevel10k. It's best to let `p10k configure` set it for you. + typeset -g POWERLEVEL9K_MODE=nerdfont-complete + # When set to `moderate`, some icons will have an extra space after them. This is meant to avoid + # icon overlap when using non-monospace fonts. When set to `none`, spaces are not added. + typeset -g POWERLEVEL9K_ICON_PADDING=none + + # When set to true, icons appear before content on both sides of the prompt. When set + # to false, icons go after content. If empty or not set, icons go before content in the left + # prompt and after content in the right prompt. + # + # You can also override it for a specific segment: + # + # POWERLEVEL9K_STATUS_ICON_BEFORE_CONTENT=false + # + # Or for a specific segment in specific state: + # + # POWERLEVEL9K_DIR_NOT_WRITABLE_ICON_BEFORE_CONTENT=false + typeset -g POWERLEVEL9K_ICON_BEFORE_CONTENT= + + # Add an empty line before each prompt. + typeset -g POWERLEVEL9K_PROMPT_ADD_NEWLINE=true + + # Connect left prompt lines with these symbols. You'll probably want to use the same color + # as POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_FOREGROUND below. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_PREFIX='%242F╭─' + typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_PREFIX='%242F├─' + typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_PREFIX='%242F╰─' + # Connect right prompt lines with these symbols. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_SUFFIX='%242F─╮' + typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_SUFFIX='%242F─┤' + typeset -g POWERLEVEL9K_MULTILINE_LAST_PROMPT_SUFFIX='%242F─╯' + + # Filler between left and right prompt on the first prompt line. You can set it to ' ', '·' or + # '─'. The last two make it easier to see the alignment between left and right prompt and to + # separate prompt from command output. You might want to set POWERLEVEL9K_PROMPT_ADD_NEWLINE=false + # for more compact prompt if using this option. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR=' ' + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_BACKGROUND= + typeset -g POWERLEVEL9K_MULTILINE_NEWLINE_PROMPT_GAP_BACKGROUND= + if [[ $POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_CHAR != ' ' ]]; then + # The color of the filler. You'll probably want to match the color of POWERLEVEL9K_MULTILINE + # ornaments defined above. + typeset -g POWERLEVEL9K_MULTILINE_FIRST_PROMPT_GAP_FOREGROUND=242 + # Start filler from the edge of the screen if there are no left segments on the first line. + typeset -g POWERLEVEL9K_EMPTY_LINE_LEFT_PROMPT_FIRST_SEGMENT_END_SYMBOL='%{%}' + # End filler on the edge of the screen if there are no right segments on the first line. + typeset -g POWERLEVEL9K_EMPTY_LINE_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL='%{%}' + fi + + # Separator between same-color segments on the left. + typeset -g POWERLEVEL9K_LEFT_SUBSEGMENT_SEPARATOR='\uE0B1' + # Separator between same-color segments on the right. + typeset -g POWERLEVEL9K_RIGHT_SUBSEGMENT_SEPARATOR='\uE0B3' + # Separator between different-color segments on the left. + typeset -g POWERLEVEL9K_LEFT_SEGMENT_SEPARATOR='\uE0B0' + # Separator between different-color segments on the right. + typeset -g POWERLEVEL9K_RIGHT_SEGMENT_SEPARATOR='\uE0B2' + # To remove a separator between two segments, add "_joined" to the second segment name. + # For example: POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=(os_icon context_joined) + + # The right end of left prompt. + typeset -g POWERLEVEL9K_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL='\uE0B0' + # The left end of right prompt. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_FIRST_SEGMENT_START_SYMBOL='\uE0B2' + # The left end of left prompt. + typeset -g POWERLEVEL9K_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL= + # The right end of right prompt. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_LAST_SEGMENT_END_SYMBOL= + # Left prompt terminator for lines without any segments. + typeset -g POWERLEVEL9K_EMPTY_LINE_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL= + + #################################[ os_icon: os identifier ]################################## + # OS identifier color. + typeset -g POWERLEVEL9K_OS_ICON_FOREGROUND=232 + typeset -g POWERLEVEL9K_OS_ICON_BACKGROUND=7 + # Custom icon. + # typeset -g POWERLEVEL9K_OS_ICON_CONTENT_EXPANSION='⭐' + + ################################[ prompt_char: prompt symbol ]################################ + # Transparent background. + typeset -g POWERLEVEL9K_PROMPT_CHAR_BACKGROUND= + # Green prompt symbol if the last command succeeded. + typeset -g POWERLEVEL9K_PROMPT_CHAR_OK_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=76 + # Red prompt symbol if the last command failed. + typeset -g POWERLEVEL9K_PROMPT_CHAR_ERROR_{VIINS,VICMD,VIVIS,VIOWR}_FOREGROUND=196 + # Default prompt symbol. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIINS_CONTENT_EXPANSION='❯' + # Prompt symbol in command vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VICMD_CONTENT_EXPANSION='❮' + # Prompt symbol in visual vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIVIS_CONTENT_EXPANSION='V' + # Prompt symbol in overwrite vi mode. + typeset -g POWERLEVEL9K_PROMPT_CHAR_{OK,ERROR}_VIOWR_CONTENT_EXPANSION='▶' + typeset -g POWERLEVEL9K_PROMPT_CHAR_OVERWRITE_STATE=true + # No line terminator if prompt_char is the last segment. + typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_LAST_SEGMENT_END_SYMBOL= + # No line introducer if prompt_char is the first segment. + typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_PROMPT_FIRST_SEGMENT_START_SYMBOL= + # No surrounding whitespace. + typeset -g POWERLEVEL9K_PROMPT_CHAR_LEFT_{LEFT,RIGHT}_WHITESPACE= + + ##################################[ dir: current directory ]################################## + # Current directory background color. + typeset -g POWERLEVEL9K_DIR_BACKGROUND=4 + # Default current directory foreground color. + typeset -g POWERLEVEL9K_DIR_FOREGROUND=254 + # If directory is too long, shorten some of its segments to the shortest possible unique + # prefix. The shortened directory can be tab-completed to the original. + typeset -g POWERLEVEL9K_SHORTEN_STRATEGY=truncate_to_unique + # Replace removed segment suffixes with this symbol. + typeset -g POWERLEVEL9K_SHORTEN_DELIMITER= + # Color of the shortened directory segments. + typeset -g POWERLEVEL9K_DIR_SHORTENED_FOREGROUND=250 + # Color of the anchor directory segments. Anchor segments are never shortened. The first + # segment is always an anchor. + typeset -g POWERLEVEL9K_DIR_ANCHOR_FOREGROUND=255 + # Display anchor directory segments in bold. + typeset -g POWERLEVEL9K_DIR_ANCHOR_BOLD=true + # Don't shorten directories that contain any of these files. They are anchors. + local anchor_files=( + .bzr + .citc + .git + .hg + .node-version + .python-version + .go-version + .ruby-version + .lua-version + .java-version + .perl-version + .php-version + .tool-versions + .shorten_folder_marker + .svn + .terraform + CVS + Cargo.toml + composer.json + go.mod + package.json + stack.yaml + ) + typeset -g POWERLEVEL9K_SHORTEN_FOLDER_MARKER="(${(j:|:)anchor_files})" + # If set to "first" ("last"), remove everything before the first (last) subdirectory that contains + # files matching $POWERLEVEL9K_SHORTEN_FOLDER_MARKER. For example, when the current directory is + # /foo/bar/git_repo/nested_git_repo/baz, prompt will display git_repo/nested_git_repo/baz (first) + # or nested_git_repo/baz (last). This assumes that git_repo and nested_git_repo contain markers + # and other directories don't. + # + # Optionally, "first" and "last" can be followed by ":" where is an integer. + # This moves the truncation point to the right (positive offset) or to the left (negative offset) + # relative to the marker. Plain "first" and "last" are equivalent to "first:0" and "last:0" + # respectively. + typeset -g POWERLEVEL9K_DIR_TRUNCATE_BEFORE_MARKER=false + # Don't shorten this many last directory segments. They are anchors. + typeset -g POWERLEVEL9K_SHORTEN_DIR_LENGTH=1 + # Shorten directory if it's longer than this even if there is space for it. The value can + # be either absolute (e.g., '80') or a percentage of terminal width (e.g, '50%'). If empty, + # directory will be shortened only when prompt doesn't fit or when other parameters demand it + # (see POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS and POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT below). + # If set to `0`, directory will always be shortened to its minimum length. + typeset -g POWERLEVEL9K_DIR_MAX_LENGTH=80 + # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least this + # many columns for typing commands. + typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS=40 + # When `dir` segment is on the last prompt line, try to shorten it enough to leave at least + # COLUMNS * POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT * 0.01 columns for typing commands. + typeset -g POWERLEVEL9K_DIR_MIN_COMMAND_COLUMNS_PCT=50 + # If set to true, embed a hyperlink into the directory. Useful for quickly + # opening a directory in the file manager simply by clicking the link. + # Can also be handy when the directory is shortened, as it allows you to see + # the full directory that was used in previous commands. + typeset -g POWERLEVEL9K_DIR_HYPERLINK=false + + # Enable special styling for non-writable and non-existent directories. See POWERLEVEL9K_LOCK_ICON + # and POWERLEVEL9K_DIR_CLASSES below. + typeset -g POWERLEVEL9K_DIR_SHOW_WRITABLE=v3 + + # The default icon shown next to non-writable and non-existent directories when + # POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3. + # typeset -g POWERLEVEL9K_LOCK_ICON='⭐' + + # POWERLEVEL9K_DIR_CLASSES allows you to specify custom icons and colors for different + # directories. It must be an array with 3 * N elements. Each triplet consists of: + # + # 1. A pattern against which the current directory ($PWD) is matched. Matching is done with + # extended_glob option enabled. + # 2. Directory class for the purpose of styling. + # 3. An empty string. + # + # Triplets are tried in order. The first triplet whose pattern matches $PWD wins. + # + # If POWERLEVEL9K_DIR_SHOW_WRITABLE is set to v3, non-writable and non-existent directories + # acquire class suffix _NOT_WRITABLE and NON_EXISTENT respectively. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_DIR_CLASSES=( + # '~/work(|/*)' WORK '' + # '~(|/*)' HOME '' + # '*' DEFAULT '') + # + # Whenever the current directory is ~/work or a subdirectory of ~/work, it gets styled with one + # of the following classes depending on its writability and existence: WORK, WORK_NOT_WRITABLE or + # WORK_NON_EXISTENT. + # + # Simply assigning classes to directories doesn't have any visible effects. It merely gives you an + # option to define custom colors and icons for different directory classes. + # + # # Styling for WORK. + # typeset -g POWERLEVEL9K_DIR_WORK_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_DIR_WORK_BACKGROUND=4 + # typeset -g POWERLEVEL9K_DIR_WORK_FOREGROUND=254 + # typeset -g POWERLEVEL9K_DIR_WORK_SHORTENED_FOREGROUND=250 + # typeset -g POWERLEVEL9K_DIR_WORK_ANCHOR_FOREGROUND=255 + # + # # Styling for WORK_NOT_WRITABLE. + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_BACKGROUND=4 + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND=254 + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_SHORTENED_FOREGROUND=250 + # typeset -g POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_ANCHOR_FOREGROUND=255 + # + # # Styling for WORK_NON_EXISTENT. + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_BACKGROUND=4 + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_FOREGROUND=254 + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_SHORTENED_FOREGROUND=250 + # typeset -g POWERLEVEL9K_DIR_WORK_NON_EXISTENT_ANCHOR_FOREGROUND=255 + # + # If a styling parameter isn't explicitly defined for some class, it falls back to the classless + # parameter. For example, if POWERLEVEL9K_DIR_WORK_NOT_WRITABLE_FOREGROUND is not set, it falls + # back to POWERLEVEL9K_DIR_FOREGROUND. + # + # typeset -g POWERLEVEL9K_DIR_CLASSES=() + + # Custom prefix. + # typeset -g POWERLEVEL9K_DIR_PREFIX='in ' + + #####################################[ vcs: git status ]###################################### + # Version control background colors. + typeset -g POWERLEVEL9K_VCS_CLEAN_BACKGROUND=2 + typeset -g POWERLEVEL9K_VCS_MODIFIED_BACKGROUND=3 + typeset -g POWERLEVEL9K_VCS_UNTRACKED_BACKGROUND=2 + typeset -g POWERLEVEL9K_VCS_CONFLICTED_BACKGROUND=3 + typeset -g POWERLEVEL9K_VCS_LOADING_BACKGROUND=8 + + # Branch icon. Set this parameter to '\UE0A0 ' for the popular Powerline branch icon. + typeset -g POWERLEVEL9K_VCS_BRANCH_ICON= + + # Untracked files icon. It's really a question mark, your font isn't broken. + # Change the value of this parameter to show a different icon. + typeset -g POWERLEVEL9K_VCS_UNTRACKED_ICON='?' + + # Formatter for Git status. + # + # Example output: master wip ⇣42⇡42 *42 merge ~42 +42 !42 ?42. + # + # You can edit the function to customize how Git status looks. + # + # VCS_STATUS_* parameters are set by gitstatus plugin. See reference: + # https://github.com/romkatv/gitstatus/blob/master/gitstatus.plugin.zsh. + function my_git_formatter() { + emulate -L zsh + + if [[ -n $P9K_CONTENT ]]; then + # If P9K_CONTENT is not empty, use it. It's either "loading" or from vcs_info (not from + # gitstatus plugin). VCS_STATUS_* parameters are not available in this case. + typeset -g my_git_format=$P9K_CONTENT + return + fi + + # Styling for different parts of Git status. + local meta='%7F' # white foreground + local clean='%0F' # black foreground + local modified='%0F' # black foreground + local untracked='%0F' # black foreground + local conflicted='%1F' # red foreground + + local res + + if [[ -n $VCS_STATUS_LOCAL_BRANCH ]]; then + local branch=${(V)VCS_STATUS_LOCAL_BRANCH} + # If local branch name is at most 32 characters long, show it in full. + # Otherwise show the first 12 … the last 12. + # Tip: To always show local branch name in full without truncation, delete the next line. + (( $#branch > 32 )) && branch[13,-13]="…" # <-- this line + res+="${clean}${(g::)POWERLEVEL9K_VCS_BRANCH_ICON}${branch//\%/%%}" + fi + + if [[ -n $VCS_STATUS_TAG + # Show tag only if not on a branch. + # Tip: To always show tag, delete the next line. + && -z $VCS_STATUS_LOCAL_BRANCH # <-- this line + ]]; then + local tag=${(V)VCS_STATUS_TAG} + # If tag name is at most 32 characters long, show it in full. + # Otherwise show the first 12 … the last 12. + # Tip: To always show tag name in full without truncation, delete the next line. + (( $#tag > 32 )) && tag[13,-13]="…" # <-- this line + res+="${meta}#${clean}${tag//\%/%%}" + fi + + # Display the current Git commit if there is no branch and no tag. + # Tip: To always display the current Git commit, delete the next line. + [[ -z $VCS_STATUS_LOCAL_BRANCH && -z $VCS_STATUS_TAG ]] && # <-- this line + res+="${meta}@${clean}${VCS_STATUS_COMMIT[1,8]}" + + # Show tracking branch name if it differs from local branch. + if [[ -n ${VCS_STATUS_REMOTE_BRANCH:#$VCS_STATUS_LOCAL_BRANCH} ]]; then + res+="${meta}:${clean}${(V)VCS_STATUS_REMOTE_BRANCH//\%/%%}" + fi + + # Display "wip" if the latest commit's summary contains "wip" or "WIP". + if [[ $VCS_STATUS_COMMIT_SUMMARY == (|*[^[:alnum:]])(wip|WIP)(|[^[:alnum:]]*) ]]; then + res+=" ${modified}wip" + fi + + if (( VCS_STATUS_COMMITS_AHEAD || VCS_STATUS_COMMITS_BEHIND )); then + # ⇣42 if behind the remote. + (( VCS_STATUS_COMMITS_BEHIND )) && res+=" ${clean}⇣${VCS_STATUS_COMMITS_BEHIND}" + # ⇡42 if ahead of the remote; no leading space if also behind the remote: ⇣42⇡42. + (( VCS_STATUS_COMMITS_AHEAD && !VCS_STATUS_COMMITS_BEHIND )) && res+=" " + (( VCS_STATUS_COMMITS_AHEAD )) && res+="${clean}⇡${VCS_STATUS_COMMITS_AHEAD}" + elif [[ -n $VCS_STATUS_REMOTE_BRANCH ]]; then + # Tip: Uncomment the next line to display '=' if up to date with the remote. + # res+=" ${clean}=" + fi + + # ⇠42 if behind the push remote. + (( VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=" ${clean}⇠${VCS_STATUS_PUSH_COMMITS_BEHIND}" + (( VCS_STATUS_PUSH_COMMITS_AHEAD && !VCS_STATUS_PUSH_COMMITS_BEHIND )) && res+=" " + # ⇢42 if ahead of the push remote; no leading space if also behind: ⇠42⇢42. + (( VCS_STATUS_PUSH_COMMITS_AHEAD )) && res+="${clean}⇢${VCS_STATUS_PUSH_COMMITS_AHEAD}" + # *42 if have stashes. + (( VCS_STATUS_STASHES )) && res+=" ${clean}*${VCS_STATUS_STASHES}" + # 'merge' if the repo is in an unusual state. + [[ -n $VCS_STATUS_ACTION ]] && res+=" ${conflicted}${VCS_STATUS_ACTION}" + # ~42 if have merge conflicts. + (( VCS_STATUS_NUM_CONFLICTED )) && res+=" ${conflicted}~${VCS_STATUS_NUM_CONFLICTED}" + # +42 if have staged changes. + (( VCS_STATUS_NUM_STAGED )) && res+=" ${modified}+${VCS_STATUS_NUM_STAGED}" + # !42 if have unstaged changes. + (( VCS_STATUS_NUM_UNSTAGED )) && res+=" ${modified}!${VCS_STATUS_NUM_UNSTAGED}" + # ?42 if have untracked files. It's really a question mark, your font isn't broken. + # See POWERLEVEL9K_VCS_UNTRACKED_ICON above if you want to use a different icon. + # Remove the next line if you don't want to see untracked files at all. + (( VCS_STATUS_NUM_UNTRACKED )) && res+=" ${untracked}${(g::)POWERLEVEL9K_VCS_UNTRACKED_ICON}${VCS_STATUS_NUM_UNTRACKED}" + # "─" if the number of unstaged files is unknown. This can happen due to + # POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY (see below) being set to a non-negative number lower + # than the number of files in the Git index, or due to bash.showDirtyState being set to false + # in the repository config. The number of staged and untracked files may also be unknown + # in this case. + (( VCS_STATUS_HAS_UNSTAGED == -1 )) && res+=" ${modified}─" + + typeset -g my_git_format=$res + } + functions -M my_git_formatter 2>/dev/null + + # Don't count the number of unstaged, untracked and conflicted files in Git repositories with + # more than this many files in the index. Negative value means infinity. + # + # If you are working in Git repositories with tens of millions of files and seeing performance + # sagging, try setting POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY to a number lower than the output + # of `git ls-files | wc -l`. Alternatively, add `bash.showDirtyState = false` to the repository's + # config: `git config bash.showDirtyState false`. + typeset -g POWERLEVEL9K_VCS_MAX_INDEX_SIZE_DIRTY=-1 + + # Don't show Git status in prompt for repositories whose workdir matches this pattern. + # For example, if set to '~', the Git repository at $HOME/.git will be ignored. + # Multiple patterns can be combined with '|': '~(|/foo)|/bar/baz/*'. + typeset -g POWERLEVEL9K_VCS_DISABLED_WORKDIR_PATTERN='~' + + # Disable the default Git status formatting. + typeset -g POWERLEVEL9K_VCS_DISABLE_GITSTATUS_FORMATTING=true + # Install our own Git status formatter. + typeset -g POWERLEVEL9K_VCS_CONTENT_EXPANSION='${$((my_git_formatter()))+${my_git_format}}' + # Enable counters for staged, unstaged, etc. + typeset -g POWERLEVEL9K_VCS_{STAGED,UNSTAGED,UNTRACKED,CONFLICTED,COMMITS_AHEAD,COMMITS_BEHIND}_MAX_NUM=-1 + + # Custom icon. + # typeset -g POWERLEVEL9K_VCS_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_VCS_PREFIX='on ' + + # Show status of repositories of these types. You can add svn and/or hg if you are + # using them. If you do, your prompt may become slow even when your current directory + # isn't in an svn or hg repository. + typeset -g POWERLEVEL9K_VCS_BACKENDS=(git) + + ##########################[ status: exit code of the last command ]########################### + # Enable OK_PIPE, ERROR_PIPE and ERROR_SIGNAL status states to allow us to enable, disable and + # style them independently from the regular OK and ERROR state. + typeset -g POWERLEVEL9K_STATUS_EXTENDED_STATES=true + + # Status on success. No content, just an icon. No need to show it if prompt_char is enabled as + # it will signify success by turning green. + typeset -g POWERLEVEL9K_STATUS_OK=true + typeset -g POWERLEVEL9K_STATUS_OK_VISUAL_IDENTIFIER_EXPANSION='✔' + typeset -g POWERLEVEL9K_STATUS_OK_FOREGROUND=2 + typeset -g POWERLEVEL9K_STATUS_OK_BACKGROUND=0 + + # Status when some part of a pipe command fails but the overall exit status is zero. It may look + # like this: 1|0. + typeset -g POWERLEVEL9K_STATUS_OK_PIPE=true + typeset -g POWERLEVEL9K_STATUS_OK_PIPE_VISUAL_IDENTIFIER_EXPANSION='✔' + typeset -g POWERLEVEL9K_STATUS_OK_PIPE_FOREGROUND=2 + typeset -g POWERLEVEL9K_STATUS_OK_PIPE_BACKGROUND=0 + + # Status when it's just an error code (e.g., '1'). No need to show it if prompt_char is enabled as + # it will signify error by turning red. + typeset -g POWERLEVEL9K_STATUS_ERROR=true + typeset -g POWERLEVEL9K_STATUS_ERROR_VISUAL_IDENTIFIER_EXPANSION='✘' + typeset -g POWERLEVEL9K_STATUS_ERROR_FOREGROUND=3 + typeset -g POWERLEVEL9K_STATUS_ERROR_BACKGROUND=1 + + # Status when the last command was terminated by a signal. + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL=true + # Use terse signal names: "INT" instead of "SIGINT(2)". + typeset -g POWERLEVEL9K_STATUS_VERBOSE_SIGNAME=false + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_VISUAL_IDENTIFIER_EXPANSION='✘' + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_FOREGROUND=3 + typeset -g POWERLEVEL9K_STATUS_ERROR_SIGNAL_BACKGROUND=1 + + # Status when some part of a pipe command fails and the overall exit status is also non-zero. + # It may look like this: 1|0. + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE=true + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_VISUAL_IDENTIFIER_EXPANSION='✘' + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_FOREGROUND=3 + typeset -g POWERLEVEL9K_STATUS_ERROR_PIPE_BACKGROUND=1 + + ###################[ command_execution_time: duration of the last command ]################### + # Execution time color. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FOREGROUND=0 + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_BACKGROUND=3 + # Show duration of the last command if takes at least this many seconds. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_THRESHOLD=3 + # Show this many fractional digits. Zero means round to seconds. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PRECISION=0 + # Duration format: 1d 2h 3m 4s. + typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_FORMAT='d h m s' + # Custom icon. + # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_COMMAND_EXECUTION_TIME_PREFIX='took ' + + #######################[ background_jobs: presence of background jobs ]####################### + # Background jobs color. + typeset -g POWERLEVEL9K_BACKGROUND_JOBS_FOREGROUND=6 + typeset -g POWERLEVEL9K_BACKGROUND_JOBS_BACKGROUND=0 + # Don't show the number of background jobs. + typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VERBOSE=false + # Custom icon. + # typeset -g POWERLEVEL9K_BACKGROUND_JOBS_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######################[ direnv: direnv status (https://direnv.net/) ]######################## + # Direnv color. + typeset -g POWERLEVEL9K_DIRENV_FOREGROUND=3 + typeset -g POWERLEVEL9K_DIRENV_BACKGROUND=0 + # Custom icon. + # typeset -g POWERLEVEL9K_DIRENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###############[ asdf: asdf version manager (https://github.com/asdf-vm/asdf) ]############### + # Default asdf color. Only used to display tools for which there is no color override (see below). + # Tip: Override these parameters for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_FOREGROUND and + # POWERLEVEL9K_ASDF_${TOOL}_BACKGROUND. + typeset -g POWERLEVEL9K_ASDF_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_BACKGROUND=7 + + # There are four parameters that can be used to hide asdf tools. Each parameter describes + # conditions under which a tool gets hidden. Parameters can hide tools but not unhide them. If at + # least one parameter decides to hide a tool, that tool gets hidden. If no parameter decides to + # hide a tool, it gets shown. + # + # Special note on the difference between POWERLEVEL9K_ASDF_SOURCES and + # POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW. Consider the effect of the following commands: + # + # asdf local python 3.8.1 + # asdf global python 3.8.1 + # + # After running both commands the current python version is 3.8.1 and its source is "local" as + # it takes precedence over "global". If POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW is set to false, + # it'll hide python version in this case because 3.8.1 is the same as the global version. + # POWERLEVEL9K_ASDF_SOURCES will hide python version only if the value of this parameter doesn't + # contain "local". + + # Hide tool versions that don't come from one of these sources. + # + # Available sources: + # + # - shell `asdf current` says "set by ASDF_${TOOL}_VERSION environment variable" + # - local `asdf current` says "set by /some/not/home/directory/file" + # - global `asdf current` says "set by /home/username/file" + # + # Note: If this parameter is set to (shell local global), it won't hide tools. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SOURCES. + typeset -g POWERLEVEL9K_ASDF_SOURCES=(shell local global) + + # If set to false, hide tool versions that are the same as global. + # + # Note: The name of this parameter doesn't reflect its meaning at all. + # Note: If this parameter is set to true, it won't hide tools. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_PROMPT_ALWAYS_SHOW. + typeset -g POWERLEVEL9K_ASDF_PROMPT_ALWAYS_SHOW=false + + # If set to false, hide tool versions that are equal to "system". + # + # Note: If this parameter is set to true, it won't hide tools. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_SYSTEM. + typeset -g POWERLEVEL9K_ASDF_SHOW_SYSTEM=true + + # If set to non-empty value, hide tools unless there is a file matching the specified file pattern + # in the current directory, or its parent directory, or its grandparent directory, and so on. + # + # Note: If this parameter is set to empty value, it won't hide tools. + # Note: SHOW_ON_UPGLOB isn't specific to asdf. It works with all prompt segments. + # Tip: Override this parameter for ${TOOL} with POWERLEVEL9K_ASDF_${TOOL}_SHOW_ON_UPGLOB. + # + # Example: Hide nodejs version when there is no package.json and no *.js files in the current + # directory, in `..`, in `../..` and so on. + # + # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.js|package.json' + typeset -g POWERLEVEL9K_ASDF_SHOW_ON_UPGLOB= + + # Ruby version from asdf. + typeset -g POWERLEVEL9K_ASDF_RUBY_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_RUBY_BACKGROUND=1 + # typeset -g POWERLEVEL9K_ASDF_RUBY_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_RUBY_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Python version from asdf. + typeset -g POWERLEVEL9K_ASDF_PYTHON_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_PYTHON_BACKGROUND=4 + # typeset -g POWERLEVEL9K_ASDF_PYTHON_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_PYTHON_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Go version from asdf. + typeset -g POWERLEVEL9K_ASDF_GOLANG_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_GOLANG_BACKGROUND=4 + # typeset -g POWERLEVEL9K_ASDF_GOLANG_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_GOLANG_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Node.js version from asdf. + typeset -g POWERLEVEL9K_ASDF_NODEJS_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_NODEJS_BACKGROUND=2 + # typeset -g POWERLEVEL9K_ASDF_NODEJS_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_NODEJS_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Rust version from asdf. + typeset -g POWERLEVEL9K_ASDF_RUST_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_RUST_BACKGROUND=208 + # typeset -g POWERLEVEL9K_ASDF_RUST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_RUST_SHOW_ON_UPGLOB='*.foo|*.bar' + + # .NET Core version from asdf. + typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_BACKGROUND=5 + # typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_DOTNET_CORE_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Flutter version from asdf. + typeset -g POWERLEVEL9K_ASDF_FLUTTER_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_FLUTTER_BACKGROUND=4 + # typeset -g POWERLEVEL9K_ASDF_FLUTTER_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_FLUTTER_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Lua version from asdf. + typeset -g POWERLEVEL9K_ASDF_LUA_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_LUA_BACKGROUND=4 + # typeset -g POWERLEVEL9K_ASDF_LUA_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_LUA_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Java version from asdf. + typeset -g POWERLEVEL9K_ASDF_JAVA_FOREGROUND=1 + typeset -g POWERLEVEL9K_ASDF_JAVA_BACKGROUND=7 + # typeset -g POWERLEVEL9K_ASDF_JAVA_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_JAVA_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Perl version from asdf. + typeset -g POWERLEVEL9K_ASDF_PERL_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_PERL_BACKGROUND=4 + # typeset -g POWERLEVEL9K_ASDF_PERL_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_PERL_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Erlang version from asdf. + typeset -g POWERLEVEL9K_ASDF_ERLANG_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_ERLANG_BACKGROUND=1 + # typeset -g POWERLEVEL9K_ASDF_ERLANG_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_ERLANG_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Elixir version from asdf. + typeset -g POWERLEVEL9K_ASDF_ELIXIR_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_ELIXIR_BACKGROUND=5 + # typeset -g POWERLEVEL9K_ASDF_ELIXIR_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_ELIXIR_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Postgres version from asdf. + typeset -g POWERLEVEL9K_ASDF_POSTGRES_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_POSTGRES_BACKGROUND=6 + # typeset -g POWERLEVEL9K_ASDF_POSTGRES_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_POSTGRES_SHOW_ON_UPGLOB='*.foo|*.bar' + + # PHP version from asdf. + typeset -g POWERLEVEL9K_ASDF_PHP_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_PHP_BACKGROUND=5 + # typeset -g POWERLEVEL9K_ASDF_PHP_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_PHP_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Haskell version from asdf. + typeset -g POWERLEVEL9K_ASDF_HASKELL_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_HASKELL_BACKGROUND=3 + # typeset -g POWERLEVEL9K_ASDF_HASKELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_HASKELL_SHOW_ON_UPGLOB='*.foo|*.bar' + + # Julia version from asdf. + typeset -g POWERLEVEL9K_ASDF_JULIA_FOREGROUND=0 + typeset -g POWERLEVEL9K_ASDF_JULIA_BACKGROUND=2 + # typeset -g POWERLEVEL9K_ASDF_JULIA_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_ASDF_JULIA_SHOW_ON_UPGLOB='*.foo|*.bar' + + ##########[ nordvpn: nordvpn connection status, linux only (https://nordvpn.com/) ]########### + # NordVPN connection indicator color. + typeset -g POWERLEVEL9K_NORDVPN_FOREGROUND=7 + typeset -g POWERLEVEL9K_NORDVPN_BACKGROUND=4 + # Hide NordVPN connection indicator when not connected. + typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_CONTENT_EXPANSION= + typeset -g POWERLEVEL9K_NORDVPN_{DISCONNECTED,CONNECTING,DISCONNECTING}_VISUAL_IDENTIFIER_EXPANSION= + # Custom icon. + # typeset -g POWERLEVEL9K_NORDVPN_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #################[ ranger: ranger shell (https://github.com/ranger/ranger) ]################## + # Ranger shell color. + typeset -g POWERLEVEL9K_RANGER_FOREGROUND=3 + typeset -g POWERLEVEL9K_RANGER_BACKGROUND=0 + # Custom icon. + # typeset -g POWERLEVEL9K_RANGER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################[ nnn: nnn shell (https://github.com/jarun/nnn) ]####################### + # Nnn shell color. + typeset -g POWERLEVEL9K_NNN_FOREGROUND=0 + typeset -g POWERLEVEL9K_NNN_BACKGROUND=6 + # Custom icon. + # typeset -g POWERLEVEL9K_NNN_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################[ lf: lf shell (https://github.com/gokcehan/lf) ]####################### + # lf shell color. + typeset -g POWERLEVEL9K_LF_FOREGROUND=0 + typeset -g POWERLEVEL9K_LF_BACKGROUND=6 + # Custom icon. + # typeset -g POWERLEVEL9K_LF_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################[ xplr: xplr shell (https://github.com/sayanarijit/xplr) ]################## + # xplr shell color. + typeset -g POWERLEVEL9K_XPLR_FOREGROUND=0 + typeset -g POWERLEVEL9K_XPLR_BACKGROUND=6 + # Custom icon. + # typeset -g POWERLEVEL9K_XPLR_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########################[ vim_shell: vim shell indicator (:sh) ]########################### + # Vim shell indicator color. + typeset -g POWERLEVEL9K_VIM_SHELL_FOREGROUND=0 + typeset -g POWERLEVEL9K_VIM_SHELL_BACKGROUND=2 + # Custom icon. + # typeset -g POWERLEVEL9K_VIM_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######[ midnight_commander: midnight commander shell (https://midnight-commander.org/) ]###### + # Midnight Commander shell color. + typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_FOREGROUND=3 + typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_BACKGROUND=0 + # Custom icon. + # typeset -g POWERLEVEL9K_MIDNIGHT_COMMANDER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #[ nix_shell: nix shell (https://nixos.org/nixos/nix-pills/developing-with-nix-shell.html) ]## + # Nix shell color. + typeset -g POWERLEVEL9K_NIX_SHELL_FOREGROUND=0 + typeset -g POWERLEVEL9K_NIX_SHELL_BACKGROUND=4 + + # Display the icon of nix_shell if PATH contains a subdirectory of /nix/store. + # typeset -g POWERLEVEL9K_NIX_SHELL_INFER_FROM_PATH=false + + # Tip: If you want to see just the icon without "pure" and "impure", uncomment the next line. + # typeset -g POWERLEVEL9K_NIX_SHELL_CONTENT_EXPANSION= + + # Custom icon. + # typeset -g POWERLEVEL9K_NIX_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################[ chezmoi_shell: chezmoi shell (https://www.chezmoi.io/) ]################## + # chezmoi shell color. + typeset -g POWERLEVEL9K_CHEZMOI_SHELL_FOREGROUND=0 + typeset -g POWERLEVEL9K_CHEZMOI_SHELL_BACKGROUND=4 + # Custom icon. + # typeset -g POWERLEVEL9K_CHEZMOI_SHELL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################################[ disk_usage: disk usage ]################################## + # Colors for different levels of disk usage. + typeset -g POWERLEVEL9K_DISK_USAGE_NORMAL_FOREGROUND=3 + typeset -g POWERLEVEL9K_DISK_USAGE_NORMAL_BACKGROUND=0 + typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_FOREGROUND=0 + typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_BACKGROUND=3 + typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_FOREGROUND=7 + typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_BACKGROUND=1 + # Thresholds for different levels of disk usage (percentage points). + typeset -g POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL=90 + typeset -g POWERLEVEL9K_DISK_USAGE_CRITICAL_LEVEL=95 + # If set to true, hide disk usage when below $POWERLEVEL9K_DISK_USAGE_WARNING_LEVEL percent. + typeset -g POWERLEVEL9K_DISK_USAGE_ONLY_WARNING=false + # Custom icon. + # typeset -g POWERLEVEL9K_DISK_USAGE_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ vi_mode: vi mode (you don't need this if you've enabled prompt_char) ]########### + # Foreground color. + typeset -g POWERLEVEL9K_VI_MODE_FOREGROUND=0 + # Text and color for normal (a.k.a. command) vi mode. + typeset -g POWERLEVEL9K_VI_COMMAND_MODE_STRING=NORMAL + typeset -g POWERLEVEL9K_VI_MODE_NORMAL_BACKGROUND=2 + # Text and color for visual vi mode. + typeset -g POWERLEVEL9K_VI_VISUAL_MODE_STRING=VISUAL + typeset -g POWERLEVEL9K_VI_MODE_VISUAL_BACKGROUND=4 + # Text and color for overtype (a.k.a. overwrite and replace) vi mode. + typeset -g POWERLEVEL9K_VI_OVERWRITE_MODE_STRING=OVERTYPE + typeset -g POWERLEVEL9K_VI_MODE_OVERWRITE_BACKGROUND=3 + # Text and color for insert vi mode. + typeset -g POWERLEVEL9K_VI_INSERT_MODE_STRING= + typeset -g POWERLEVEL9K_VI_MODE_INSERT_FOREGROUND=8 + + ######################################[ ram: free RAM ]####################################### + # RAM color. + typeset -g POWERLEVEL9K_RAM_FOREGROUND=0 + typeset -g POWERLEVEL9K_RAM_BACKGROUND=3 + # Custom icon. + # typeset -g POWERLEVEL9K_RAM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #####################################[ swap: used swap ]###################################### + # Swap color. + typeset -g POWERLEVEL9K_SWAP_FOREGROUND=0 + typeset -g POWERLEVEL9K_SWAP_BACKGROUND=3 + # Custom icon. + # typeset -g POWERLEVEL9K_SWAP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######################################[ load: CPU load ]###################################### + # Show average CPU load over this many last minutes. Valid values are 1, 5 and 15. + typeset -g POWERLEVEL9K_LOAD_WHICH=5 + # Load color when load is under 50%. + typeset -g POWERLEVEL9K_LOAD_NORMAL_FOREGROUND=0 + typeset -g POWERLEVEL9K_LOAD_NORMAL_BACKGROUND=2 + # Load color when load is between 50% and 70%. + typeset -g POWERLEVEL9K_LOAD_WARNING_FOREGROUND=0 + typeset -g POWERLEVEL9K_LOAD_WARNING_BACKGROUND=3 + # Load color when load is over 70%. + typeset -g POWERLEVEL9K_LOAD_CRITICAL_FOREGROUND=0 + typeset -g POWERLEVEL9K_LOAD_CRITICAL_BACKGROUND=1 + # Custom icon. + # typeset -g POWERLEVEL9K_LOAD_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ todo: todo items (https://github.com/todotxt/todo.txt-cli) ]################ + # Todo color. + typeset -g POWERLEVEL9K_TODO_FOREGROUND=0 + typeset -g POWERLEVEL9K_TODO_BACKGROUND=8 + # Hide todo when the total number of tasks is zero. + typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_TOTAL=true + # Hide todo when the number of tasks after filtering is zero. + typeset -g POWERLEVEL9K_TODO_HIDE_ZERO_FILTERED=false + + # Todo format. The following parameters are available within the expansion. + # + # - P9K_TODO_TOTAL_TASK_COUNT The total number of tasks. + # - P9K_TODO_FILTERED_TASK_COUNT The number of tasks after filtering. + # + # These variables correspond to the last line of the output of `todo.sh -p ls`: + # + # TODO: 24 of 42 tasks shown + # + # Here 24 is P9K_TODO_FILTERED_TASK_COUNT and 42 is P9K_TODO_TOTAL_TASK_COUNT. + # + # typeset -g POWERLEVEL9K_TODO_CONTENT_EXPANSION='$P9K_TODO_FILTERED_TASK_COUNT' + + # Custom icon. + # typeset -g POWERLEVEL9K_TODO_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ timewarrior: timewarrior tracking status (https://timewarrior.net/) ]############ + # Timewarrior color. + typeset -g POWERLEVEL9K_TIMEWARRIOR_FOREGROUND=255 + typeset -g POWERLEVEL9K_TIMEWARRIOR_BACKGROUND=8 + + # If the tracked task is longer than 24 characters, truncate and append "…". + # Tip: To always display tasks without truncation, delete the following parameter. + # Tip: To hide task names and display just the icon when time tracking is enabled, set the + # value of the following parameter to "". + typeset -g POWERLEVEL9K_TIMEWARRIOR_CONTENT_EXPANSION='${P9K_CONTENT:0:24}${${P9K_CONTENT:24}:+…}' + + # Custom icon. + # typeset -g POWERLEVEL9K_TIMEWARRIOR_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##############[ taskwarrior: taskwarrior task count (https://taskwarrior.org/) ]############## + # Taskwarrior color. + typeset -g POWERLEVEL9K_TASKWARRIOR_FOREGROUND=0 + typeset -g POWERLEVEL9K_TASKWARRIOR_BACKGROUND=6 + + # Taskwarrior segment format. The following parameters are available within the expansion. + # + # - P9K_TASKWARRIOR_PENDING_COUNT The number of pending tasks: `task +PENDING count`. + # - P9K_TASKWARRIOR_OVERDUE_COUNT The number of overdue tasks: `task +OVERDUE count`. + # + # Zero values are represented as empty parameters. + # + # The default format: + # + # '${P9K_TASKWARRIOR_OVERDUE_COUNT:+"!$P9K_TASKWARRIOR_OVERDUE_COUNT/"}$P9K_TASKWARRIOR_PENDING_COUNT' + # + # typeset -g POWERLEVEL9K_TASKWARRIOR_CONTENT_EXPANSION='$P9K_TASKWARRIOR_PENDING_COUNT' + + # Custom icon. + # typeset -g POWERLEVEL9K_TASKWARRIOR_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ######[ per_directory_history: Oh My Zsh per-directory-history local/global indicator ]####### + # Color when using local/global history. + typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_FOREGROUND=0 + typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_BACKGROUND=5 + typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_FOREGROUND=0 + typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_BACKGROUND=3 + + # Tip: Uncomment the next two lines to hide "local"/"global" text and leave just the icon. + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_CONTENT_EXPANSION='' + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_CONTENT_EXPANSION='' + + # Custom icon. + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_LOCAL_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_PER_DIRECTORY_HISTORY_GLOBAL_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################################[ cpu_arch: CPU architecture ]################################ + # CPU architecture color. + typeset -g POWERLEVEL9K_CPU_ARCH_FOREGROUND=0 + typeset -g POWERLEVEL9K_CPU_ARCH_BACKGROUND=3 + + # Hide the segment when on a specific CPU architecture. + # typeset -g POWERLEVEL9K_CPU_ARCH_X86_64_CONTENT_EXPANSION= + # typeset -g POWERLEVEL9K_CPU_ARCH_X86_64_VISUAL_IDENTIFIER_EXPANSION= + + # Custom icon. + # typeset -g POWERLEVEL9K_CPU_ARCH_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##################################[ context: user@hostname ]################################## + # Context color when running with privileges. + typeset -g POWERLEVEL9K_CONTEXT_ROOT_FOREGROUND=1 + typeset -g POWERLEVEL9K_CONTEXT_ROOT_BACKGROUND=0 + # Context color in SSH without privileges. + typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_FOREGROUND=3 + typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_BACKGROUND=0 + # Default context color (no privileges, no SSH). + typeset -g POWERLEVEL9K_CONTEXT_FOREGROUND=3 + typeset -g POWERLEVEL9K_CONTEXT_BACKGROUND=0 + + # Context format when running with privileges: user@hostname. + typeset -g POWERLEVEL9K_CONTEXT_ROOT_TEMPLATE='%n@%m' + # Context format when in SSH without privileges: user@hostname. + typeset -g POWERLEVEL9K_CONTEXT_{REMOTE,REMOTE_SUDO}_TEMPLATE='%n@%m' + # Default context format (no privileges, no SSH): user@hostname. + typeset -g POWERLEVEL9K_CONTEXT_TEMPLATE='%n@%m' + + # Don't show context unless running with privileges or in SSH. + # Tip: Remove the next line to always show context. + typeset -g POWERLEVEL9K_CONTEXT_{DEFAULT,SUDO}_{CONTENT,VISUAL_IDENTIFIER}_EXPANSION= + + # Custom icon. + # typeset -g POWERLEVEL9K_CONTEXT_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_CONTEXT_PREFIX='with ' + + ###[ virtualenv: python virtual environment (https://docs.python.org/3/library/venv.html) ]### + # Python virtual environment color. + typeset -g POWERLEVEL9K_VIRTUALENV_FOREGROUND=0 + typeset -g POWERLEVEL9K_VIRTUALENV_BACKGROUND=4 + # Don't show Python version next to the virtual environment name. + typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_PYTHON_VERSION=false + # If set to "false", won't show virtualenv if pyenv is already shown. + # If set to "if-different", won't show virtualenv if it's the same as pyenv. + typeset -g POWERLEVEL9K_VIRTUALENV_SHOW_WITH_PYENV=false + # Separate environment name from Python version only with a space. + typeset -g POWERLEVEL9K_VIRTUALENV_{LEFT,RIGHT}_DELIMITER= + # Custom icon. + # typeset -g POWERLEVEL9K_VIRTUALENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #####################[ anaconda: conda environment (https://conda.io/) ]###################### + # Anaconda environment color. + typeset -g POWERLEVEL9K_ANACONDA_FOREGROUND=0 + typeset -g POWERLEVEL9K_ANACONDA_BACKGROUND=4 + + # Anaconda segment format. The following parameters are available within the expansion. + # + # - CONDA_PREFIX Absolute path to the active Anaconda/Miniconda environment. + # - CONDA_DEFAULT_ENV Name of the active Anaconda/Miniconda environment. + # - CONDA_PROMPT_MODIFIER Configurable prompt modifier (see below). + # - P9K_ANACONDA_PYTHON_VERSION Current python version (python --version). + # + # CONDA_PROMPT_MODIFIER can be configured with the following command: + # + # conda config --set env_prompt '({default_env}) ' + # + # The last argument is a Python format string that can use the following variables: + # + # - prefix The same as CONDA_PREFIX. + # - default_env The same as CONDA_DEFAULT_ENV. + # - name The last segment of CONDA_PREFIX. + # - stacked_env Comma-separated list of names in the environment stack. The first element is + # always the same as default_env. + # + # Note: '({default_env}) ' is the default value of env_prompt. + # + # The default value of POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION expands to $CONDA_PROMPT_MODIFIER + # without the surrounding parentheses, or to the last path component of CONDA_PREFIX if the former + # is empty. + typeset -g POWERLEVEL9K_ANACONDA_CONTENT_EXPANSION='${${${${CONDA_PROMPT_MODIFIER#\(}% }%\)}:-${CONDA_PREFIX:t}}' + + # Custom icon. + # typeset -g POWERLEVEL9K_ANACONDA_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ pyenv: python environment (https://github.com/pyenv/pyenv) ]################ + # Pyenv color. + typeset -g POWERLEVEL9K_PYENV_FOREGROUND=0 + typeset -g POWERLEVEL9K_PYENV_BACKGROUND=4 + # Hide python version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_PYENV_SOURCES=(shell local global) + # If set to false, hide python version if it's the same as global: + # $(pyenv version-name) == $(pyenv global). + typeset -g POWERLEVEL9K_PYENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide python version if it's equal to "system". + typeset -g POWERLEVEL9K_PYENV_SHOW_SYSTEM=true + + # Pyenv segment format. The following parameters are available within the expansion. + # + # - P9K_CONTENT Current pyenv environment (pyenv version-name). + # - P9K_PYENV_PYTHON_VERSION Current python version (python --version). + # + # The default format has the following logic: + # + # 1. Display just "$P9K_CONTENT" if it's equal to "$P9K_PYENV_PYTHON_VERSION" or + # starts with "$P9K_PYENV_PYTHON_VERSION/". + # 2. Otherwise display "$P9K_CONTENT $P9K_PYENV_PYTHON_VERSION". + typeset -g POWERLEVEL9K_PYENV_CONTENT_EXPANSION='${P9K_CONTENT}${${P9K_CONTENT:#$P9K_PYENV_PYTHON_VERSION(|/*)}:+ $P9K_PYENV_PYTHON_VERSION}' + + # Custom icon. + # typeset -g POWERLEVEL9K_PYENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ goenv: go environment (https://github.com/syndbg/goenv) ]################ + # Goenv color. + typeset -g POWERLEVEL9K_GOENV_FOREGROUND=0 + typeset -g POWERLEVEL9K_GOENV_BACKGROUND=4 + # Hide go version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_GOENV_SOURCES=(shell local global) + # If set to false, hide go version if it's the same as global: + # $(goenv version-name) == $(goenv global). + typeset -g POWERLEVEL9K_GOENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide go version if it's equal to "system". + typeset -g POWERLEVEL9K_GOENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_GOENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ nodenv: node.js version from nodenv (https://github.com/nodenv/nodenv) ]########## + # Nodenv color. + typeset -g POWERLEVEL9K_NODENV_FOREGROUND=2 + typeset -g POWERLEVEL9K_NODENV_BACKGROUND=0 + # Hide node version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_NODENV_SOURCES=(shell local global) + # If set to false, hide node version if it's the same as global: + # $(nodenv version-name) == $(nodenv global). + typeset -g POWERLEVEL9K_NODENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide node version if it's equal to "system". + typeset -g POWERLEVEL9K_NODENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_NODENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##############[ nvm: node.js version from nvm (https://github.com/nvm-sh/nvm) ]############### + # Nvm color. + typeset -g POWERLEVEL9K_NVM_FOREGROUND=0 + typeset -g POWERLEVEL9K_NVM_BACKGROUND=5 + # If set to false, hide node version if it's the same as default: + # $(nvm version current) == $(nvm version default). + typeset -g POWERLEVEL9K_NVM_PROMPT_ALWAYS_SHOW=false + # If set to false, hide node version if it's equal to "system". + typeset -g POWERLEVEL9K_NVM_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_NVM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ############[ nodeenv: node.js environment (https://github.com/ekalinin/nodeenv) ]############ + # Nodeenv color. + typeset -g POWERLEVEL9K_NODEENV_FOREGROUND=2 + typeset -g POWERLEVEL9K_NODEENV_BACKGROUND=0 + # Don't show Node version next to the environment name. + typeset -g POWERLEVEL9K_NODEENV_SHOW_NODE_VERSION=false + # Separate environment name from Node version only with a space. + typeset -g POWERLEVEL9K_NODEENV_{LEFT,RIGHT}_DELIMITER= + # Custom icon. + # typeset -g POWERLEVEL9K_NODEENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##############################[ node_version: node.js version ]############################### + # Node version color. + typeset -g POWERLEVEL9K_NODE_VERSION_FOREGROUND=7 + typeset -g POWERLEVEL9K_NODE_VERSION_BACKGROUND=2 + # Show node version only when in a directory tree containing package.json. + typeset -g POWERLEVEL9K_NODE_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_NODE_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######################[ go_version: go version (https://golang.org) ]######################## + # Go version color. + typeset -g POWERLEVEL9K_GO_VERSION_FOREGROUND=255 + typeset -g POWERLEVEL9K_GO_VERSION_BACKGROUND=2 + # Show go version only when in a go project subdirectory. + typeset -g POWERLEVEL9K_GO_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_GO_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #################[ rust_version: rustc version (https://www.rust-lang.org) ]################## + # Rust version color. + typeset -g POWERLEVEL9K_RUST_VERSION_FOREGROUND=0 + typeset -g POWERLEVEL9K_RUST_VERSION_BACKGROUND=208 + # Show rust version only when in a rust project subdirectory. + typeset -g POWERLEVEL9K_RUST_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_RUST_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###############[ dotnet_version: .NET version (https://dotnet.microsoft.com) ]################ + # .NET version color. + typeset -g POWERLEVEL9K_DOTNET_VERSION_FOREGROUND=7 + typeset -g POWERLEVEL9K_DOTNET_VERSION_BACKGROUND=5 + # Show .NET version only when in a .NET project subdirectory. + typeset -g POWERLEVEL9K_DOTNET_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_DOTNET_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #####################[ php_version: php version (https://www.php.net/) ]###################### + # PHP version color. + typeset -g POWERLEVEL9K_PHP_VERSION_FOREGROUND=0 + typeset -g POWERLEVEL9K_PHP_VERSION_BACKGROUND=5 + # Show PHP version only when in a PHP project subdirectory. + typeset -g POWERLEVEL9K_PHP_VERSION_PROJECT_ONLY=true + # Custom icon. + # typeset -g POWERLEVEL9K_PHP_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ laravel_version: laravel php framework version (https://laravel.com/) ]########### + # Laravel version color. + typeset -g POWERLEVEL9K_LARAVEL_VERSION_FOREGROUND=1 + typeset -g POWERLEVEL9K_LARAVEL_VERSION_BACKGROUND=7 + # Custom icon. + # typeset -g POWERLEVEL9K_LARAVEL_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #############[ rbenv: ruby version from rbenv (https://github.com/rbenv/rbenv) ]############## + # Rbenv color. + typeset -g POWERLEVEL9K_RBENV_FOREGROUND=0 + typeset -g POWERLEVEL9K_RBENV_BACKGROUND=1 + # Hide ruby version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_RBENV_SOURCES=(shell local global) + # If set to false, hide ruby version if it's the same as global: + # $(rbenv version-name) == $(rbenv global). + typeset -g POWERLEVEL9K_RBENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide ruby version if it's equal to "system". + typeset -g POWERLEVEL9K_RBENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_RBENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ####################[ java_version: java version (https://www.java.com/) ]#################### + # Java version color. + typeset -g POWERLEVEL9K_JAVA_VERSION_FOREGROUND=1 + typeset -g POWERLEVEL9K_JAVA_VERSION_BACKGROUND=7 + # Show java version only when in a java project subdirectory. + typeset -g POWERLEVEL9K_JAVA_VERSION_PROJECT_ONLY=true + # Show brief version. + typeset -g POWERLEVEL9K_JAVA_VERSION_FULL=false + # Custom icon. + # typeset -g POWERLEVEL9K_JAVA_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###[ package: name@version from package.json (https://docs.npmjs.com/files/package.json) ]#### + # Package color. + typeset -g POWERLEVEL9K_PACKAGE_FOREGROUND=0 + typeset -g POWERLEVEL9K_PACKAGE_BACKGROUND=6 + + # Package format. The following parameters are available within the expansion. + # + # - P9K_PACKAGE_NAME The value of `name` field in package.json. + # - P9K_PACKAGE_VERSION The value of `version` field in package.json. + # + # typeset -g POWERLEVEL9K_PACKAGE_CONTENT_EXPANSION='${P9K_PACKAGE_NAME//\%/%%}@${P9K_PACKAGE_VERSION//\%/%%}' + + # Custom icon. + # typeset -g POWERLEVEL9K_PACKAGE_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######################[ rvm: ruby version from rvm (https://rvm.io) ]######################## + # Rvm color. + typeset -g POWERLEVEL9K_RVM_FOREGROUND=0 + typeset -g POWERLEVEL9K_RVM_BACKGROUND=240 + # Don't show @gemset at the end. + typeset -g POWERLEVEL9K_RVM_SHOW_GEMSET=false + # Don't show ruby- at the front. + typeset -g POWERLEVEL9K_RVM_SHOW_PREFIX=false + # Custom icon. + # typeset -g POWERLEVEL9K_RVM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ fvm: flutter version management (https://github.com/leoafarias/fvm) ]############ + # Fvm color. + typeset -g POWERLEVEL9K_FVM_FOREGROUND=0 + typeset -g POWERLEVEL9K_FVM_BACKGROUND=4 + # Custom icon. + # typeset -g POWERLEVEL9K_FVM_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ luaenv: lua version from luaenv (https://github.com/cehoffman/luaenv) ]########### + # Lua color. + typeset -g POWERLEVEL9K_LUAENV_FOREGROUND=0 + typeset -g POWERLEVEL9K_LUAENV_BACKGROUND=4 + # Hide lua version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_LUAENV_SOURCES=(shell local global) + # If set to false, hide lua version if it's the same as global: + # $(luaenv version-name) == $(luaenv global). + typeset -g POWERLEVEL9K_LUAENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide lua version if it's equal to "system". + typeset -g POWERLEVEL9K_LUAENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_LUAENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###############[ jenv: java version from jenv (https://github.com/jenv/jenv) ]################ + # Java color. + typeset -g POWERLEVEL9K_JENV_FOREGROUND=1 + typeset -g POWERLEVEL9K_JENV_BACKGROUND=7 + # Hide java version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_JENV_SOURCES=(shell local global) + # If set to false, hide java version if it's the same as global: + # $(jenv version-name) == $(jenv global). + typeset -g POWERLEVEL9K_JENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide java version if it's equal to "system". + typeset -g POWERLEVEL9K_JENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_JENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ plenv: perl version from plenv (https://github.com/tokuhirom/plenv) ]############ + # Perl color. + typeset -g POWERLEVEL9K_PLENV_FOREGROUND=0 + typeset -g POWERLEVEL9K_PLENV_BACKGROUND=4 + # Hide perl version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_PLENV_SOURCES=(shell local global) + # If set to false, hide perl version if it's the same as global: + # $(plenv version-name) == $(plenv global). + typeset -g POWERLEVEL9K_PLENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide perl version if it's equal to "system". + typeset -g POWERLEVEL9K_PLENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_PLENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ perlbrew: perl version from perlbrew (https://github.com/gugod/App-perlbrew) ]############ + # Perlbrew color. + typeset -g POWERLEVEL9K_PERLBREW_FOREGROUND=67 + # Show perlbrew version only when in a perl project subdirectory. + typeset -g POWERLEVEL9K_PERLBREW_PROJECT_ONLY=true + # Don't show "perl-" at the front. + typeset -g POWERLEVEL9K_PERLBREW_SHOW_PREFIX=false + # Custom icon. + # typeset -g POWERLEVEL9K_PERLBREW_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ############[ phpenv: php version from phpenv (https://github.com/phpenv/phpenv) ]############ + # PHP color. + typeset -g POWERLEVEL9K_PHPENV_FOREGROUND=0 + typeset -g POWERLEVEL9K_PHPENV_BACKGROUND=5 + # Hide php version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_PHPENV_SOURCES=(shell local global) + # If set to false, hide php version if it's the same as global: + # $(phpenv version-name) == $(phpenv global). + typeset -g POWERLEVEL9K_PHPENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide PHP version if it's equal to "system". + typeset -g POWERLEVEL9K_PHPENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_PHPENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #######[ scalaenv: scala version from scalaenv (https://github.com/scalaenv/scalaenv) ]####### + # Scala color. + typeset -g POWERLEVEL9K_SCALAENV_FOREGROUND=0 + typeset -g POWERLEVEL9K_SCALAENV_BACKGROUND=1 + # Hide scala version if it doesn't come from one of these sources. + typeset -g POWERLEVEL9K_SCALAENV_SOURCES=(shell local global) + # If set to false, hide scala version if it's the same as global: + # $(scalaenv version-name) == $(scalaenv global). + typeset -g POWERLEVEL9K_SCALAENV_PROMPT_ALWAYS_SHOW=false + # If set to false, hide scala version if it's equal to "system". + typeset -g POWERLEVEL9K_SCALAENV_SHOW_SYSTEM=true + # Custom icon. + # typeset -g POWERLEVEL9K_SCALAENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ haskell_stack: haskell version from stack (https://haskellstack.org/) ]########### + # Haskell color. + typeset -g POWERLEVEL9K_HASKELL_STACK_FOREGROUND=0 + typeset -g POWERLEVEL9K_HASKELL_STACK_BACKGROUND=3 + + # Hide haskell version if it doesn't come from one of these sources. + # + # shell: version is set by STACK_YAML + # local: version is set by stack.yaml up the directory tree + # global: version is set by the implicit global project (~/.stack/global-project/stack.yaml) + typeset -g POWERLEVEL9K_HASKELL_STACK_SOURCES=(shell local) + # If set to false, hide haskell version if it's the same as in the implicit global project. + typeset -g POWERLEVEL9K_HASKELL_STACK_ALWAYS_SHOW=true + # Custom icon. + # typeset -g POWERLEVEL9K_HASKELL_STACK_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ terraform: terraform workspace (https://www.terraform.io) ]################# + # Don't show terraform workspace if it's literally "default". + typeset -g POWERLEVEL9K_TERRAFORM_SHOW_DEFAULT=false + # POWERLEVEL9K_TERRAFORM_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current terraform workspace gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_TERRAFORM_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_TERRAFORM_CLASSES defines the workspace class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' OTHER) + # + # If your current terraform workspace is "project_test", its class is TEST because "project_test" + # doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_FOREGROUND=2 + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_BACKGROUND=0 + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_TERRAFORM_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_TERRAFORM_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' OTHER) + typeset -g POWERLEVEL9K_TERRAFORM_OTHER_FOREGROUND=4 + typeset -g POWERLEVEL9K_TERRAFORM_OTHER_BACKGROUND=0 + # typeset -g POWERLEVEL9K_TERRAFORM_OTHER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #############[ terraform_version: terraform version (https://www.terraform.io) ]############## + # Terraform version color. + typeset -g POWERLEVEL9K_TERRAFORM_VERSION_FOREGROUND=4 + typeset -g POWERLEVEL9K_TERRAFORM_VERSION_BACKGROUND=0 + # Custom icon. + # typeset -g POWERLEVEL9K_TERRAFORM_VERSION_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################[ terraform_version: It shows active terraform version (https://www.terraform.io) ]################# + typeset -g POWERLEVEL9K_TERRAFORM_VERSION_SHOW_ON_COMMAND='terraform|tf' + + #############[ kubecontext: current kubernetes context (https://kubernetes.io/) ]############# + # Show kubecontext only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show kubecontext. + typeset -g POWERLEVEL9K_KUBECONTEXT_SHOW_ON_COMMAND='kubectl|helm|kubens|kubectx|oc|istioctl|kogito|k9s|helmfile|flux|fluxctl|stern|kubeseal|skaffold|kubent|kubecolor|cmctl|sparkctl' + + # Kubernetes context classes for the purpose of using different colors, icons and expansions with + # different contexts. + # + # POWERLEVEL9K_KUBECONTEXT_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current kubernetes context gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_KUBECONTEXT_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_KUBECONTEXT_CLASSES defines the context class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' DEFAULT) + # + # If your current kubernetes context is "deathray-testing/default", its class is TEST + # because "deathray-testing/default" doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_FOREGROUND=0 + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_BACKGROUND=2 + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_KUBECONTEXT_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_KUBECONTEXT_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' DEFAULT) + typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_FOREGROUND=7 + typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_BACKGROUND=5 + # typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Use POWERLEVEL9K_KUBECONTEXT_CONTENT_EXPANSION to specify the content displayed by kubecontext + # segment. Parameter expansions are very flexible and fast, too. See reference: + # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion. + # + # Within the expansion the following parameters are always available: + # + # - P9K_CONTENT The content that would've been displayed if there was no content + # expansion defined. + # - P9K_KUBECONTEXT_NAME The current context's name. Corresponds to column NAME in the + # output of `kubectl config get-contexts`. + # - P9K_KUBECONTEXT_CLUSTER The current context's cluster. Corresponds to column CLUSTER in the + # output of `kubectl config get-contexts`. + # - P9K_KUBECONTEXT_NAMESPACE The current context's namespace. Corresponds to column NAMESPACE + # in the output of `kubectl config get-contexts`. If there is no + # namespace, the parameter is set to "default". + # - P9K_KUBECONTEXT_USER The current context's user. Corresponds to column AUTHINFO in the + # output of `kubectl config get-contexts`. + # + # If the context points to Google Kubernetes Engine (GKE) or Elastic Kubernetes Service (EKS), + # the following extra parameters are available: + # + # - P9K_KUBECONTEXT_CLOUD_NAME Either "gke" or "eks". + # - P9K_KUBECONTEXT_CLOUD_ACCOUNT Account/project ID. + # - P9K_KUBECONTEXT_CLOUD_ZONE Availability zone. + # - P9K_KUBECONTEXT_CLOUD_CLUSTER Cluster. + # + # P9K_KUBECONTEXT_CLOUD_* parameters are derived from P9K_KUBECONTEXT_CLUSTER. For example, + # if P9K_KUBECONTEXT_CLUSTER is "gke_my-account_us-east1-a_my-cluster-01": + # + # - P9K_KUBECONTEXT_CLOUD_NAME=gke + # - P9K_KUBECONTEXT_CLOUD_ACCOUNT=my-account + # - P9K_KUBECONTEXT_CLOUD_ZONE=us-east1-a + # - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01 + # + # If P9K_KUBECONTEXT_CLUSTER is "arn:aws:eks:us-east-1:123456789012:cluster/my-cluster-01": + # + # - P9K_KUBECONTEXT_CLOUD_NAME=eks + # - P9K_KUBECONTEXT_CLOUD_ACCOUNT=123456789012 + # - P9K_KUBECONTEXT_CLOUD_ZONE=us-east-1 + # - P9K_KUBECONTEXT_CLOUD_CLUSTER=my-cluster-01 + typeset -g POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION= + # Show P9K_KUBECONTEXT_CLOUD_CLUSTER if it's not empty and fall back to P9K_KUBECONTEXT_NAME. + POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${P9K_KUBECONTEXT_CLOUD_CLUSTER:-${P9K_KUBECONTEXT_NAME}}' + # Append the current context's namespace if it's not "default". + POWERLEVEL9K_KUBECONTEXT_DEFAULT_CONTENT_EXPANSION+='${${:-/$P9K_KUBECONTEXT_NAMESPACE}:#/default}' + + # Custom prefix. + # typeset -g POWERLEVEL9K_KUBECONTEXT_PREFIX='at ' + + #[ aws: aws profile (https://docs.aws.amazon.com/cli/latest/userguide/cli-configure-profiles.html) ]# + # Show aws only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show aws. + typeset -g POWERLEVEL9K_AWS_SHOW_ON_COMMAND='aws|awless|terraform|pulumi|terragrunt' + + # POWERLEVEL9K_AWS_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current AWS profile gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_AWS_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_AWS_CLASSES defines the profile class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_AWS_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' DEFAULT) + # + # If your current AWS profile is "company_test", its class is TEST + # because "company_test" doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_AWS_TEST_FOREGROUND=28 + # typeset -g POWERLEVEL9K_AWS_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_AWS_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_AWS_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' DEFAULT) + typeset -g POWERLEVEL9K_AWS_DEFAULT_FOREGROUND=7 + typeset -g POWERLEVEL9K_AWS_DEFAULT_BACKGROUND=1 + # typeset -g POWERLEVEL9K_AWS_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # AWS segment format. The following parameters are available within the expansion. + # + # - P9K_AWS_PROFILE The name of the current AWS profile. + # - P9K_AWS_REGION The region associated with the current AWS profile. + typeset -g POWERLEVEL9K_AWS_CONTENT_EXPANSION='${P9K_AWS_PROFILE//\%/%%}${P9K_AWS_REGION:+ ${P9K_AWS_REGION//\%/%%}}' + + #[ aws_eb_env: aws elastic beanstalk environment (https://aws.amazon.com/elasticbeanstalk/) ]# + # AWS Elastic Beanstalk environment color. + typeset -g POWERLEVEL9K_AWS_EB_ENV_FOREGROUND=2 + typeset -g POWERLEVEL9K_AWS_EB_ENV_BACKGROUND=0 + # Custom icon. + # typeset -g POWERLEVEL9K_AWS_EB_ENV_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ azure: azure account name (https://docs.microsoft.com/en-us/cli/azure) ]########## + # Show azure only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show azure. + typeset -g POWERLEVEL9K_AZURE_SHOW_ON_COMMAND='az|terraform|pulumi|terragrunt' + + # POWERLEVEL9K_AZURE_CLASSES is an array with even number of elements. The first element + # in each pair defines a pattern against which the current azure account name gets matched. + # More specifically, it's P9K_CONTENT prior to the application of context expansion (see below) + # that gets matched. If you unset all POWERLEVEL9K_AZURE_*CONTENT_EXPANSION parameters, + # you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_AZURE_CLASSES defines the account class. Patterns are tried in order. The + # first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_AZURE_CLASSES=( + # '*prod*' PROD + # '*test*' TEST + # '*' OTHER) + # + # If your current azure account is "company_test", its class is TEST because "company_test" + # doesn't match the pattern '*prod*' but does match '*test*'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_AZURE_TEST_FOREGROUND=2 + # typeset -g POWERLEVEL9K_AZURE_TEST_BACKGROUND=0 + # typeset -g POWERLEVEL9K_AZURE_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_AZURE_TEST_CONTENT_EXPANSION='> ${P9K_CONTENT} <' + typeset -g POWERLEVEL9K_AZURE_CLASSES=( + # '*prod*' PROD # These values are examples that are unlikely + # '*test*' TEST # to match your needs. Customize them as needed. + '*' OTHER) + + # Azure account name color. + typeset -g POWERLEVEL9K_AZURE_OTHER_FOREGROUND=7 + typeset -g POWERLEVEL9K_AZURE_OTHER_BACKGROUND=4 + # Custom icon. + # typeset -g POWERLEVEL9K_AZURE_OTHER_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ##########[ gcloud: google cloud account and project (https://cloud.google.com/) ]########### + # Show gcloud only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show gcloud. + typeset -g POWERLEVEL9K_GCLOUD_SHOW_ON_COMMAND='gcloud|gcs|gsutil' + # Google cloud color. + typeset -g POWERLEVEL9K_GCLOUD_FOREGROUND=7 + typeset -g POWERLEVEL9K_GCLOUD_BACKGROUND=4 + + # Google cloud format. Change the value of POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION and/or + # POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION if the default is too verbose or not informative + # enough. You can use the following parameters in the expansions. Each of them corresponds to the + # output of `gcloud` tool. + # + # Parameter | Source + # -------------------------|-------------------------------------------------------------------- + # P9K_GCLOUD_CONFIGURATION | gcloud config configurations list --format='value(name)' + # P9K_GCLOUD_ACCOUNT | gcloud config get-value account + # P9K_GCLOUD_PROJECT_ID | gcloud config get-value project + # P9K_GCLOUD_PROJECT_NAME | gcloud projects describe $P9K_GCLOUD_PROJECT_ID --format='value(name)' + # + # Note: ${VARIABLE//\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced with '%%'. + # + # Obtaining project name requires sending a request to Google servers. This can take a long time + # and even fail. When project name is unknown, P9K_GCLOUD_PROJECT_NAME is not set and gcloud + # prompt segment is in state PARTIAL. When project name gets known, P9K_GCLOUD_PROJECT_NAME gets + # set and gcloud prompt segment transitions to state COMPLETE. + # + # You can customize the format, icon and colors of gcloud segment separately for states PARTIAL + # and COMPLETE. You can also hide gcloud in state PARTIAL by setting + # POWERLEVEL9K_GCLOUD_PARTIAL_VISUAL_IDENTIFIER_EXPANSION and + # POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION to empty. + typeset -g POWERLEVEL9K_GCLOUD_PARTIAL_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_ID//\%/%%}' + typeset -g POWERLEVEL9K_GCLOUD_COMPLETE_CONTENT_EXPANSION='${P9K_GCLOUD_PROJECT_NAME//\%/%%}' + + # Send a request to Google (by means of `gcloud projects describe ...`) to obtain project name + # this often. Negative value disables periodic polling. In this mode project name is retrieved + # only when the current configuration, account or project id changes. + typeset -g POWERLEVEL9K_GCLOUD_REFRESH_PROJECT_NAME_SECONDS=60 + + # Custom icon. + # typeset -g POWERLEVEL9K_GCLOUD_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #[ google_app_cred: google application credentials (https://cloud.google.com/docs/authentication/production) ]# + # Show google_app_cred only when the command you are typing invokes one of these tools. + # Tip: Remove the next line to always show google_app_cred. + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_SHOW_ON_COMMAND='terraform|pulumi|terragrunt' + + # Google application credentials classes for the purpose of using different colors, icons and + # expansions with different credentials. + # + # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES is an array with even number of elements. The first + # element in each pair defines a pattern against which the current kubernetes context gets + # matched. More specifically, it's P9K_CONTENT prior to the application of context expansion + # (see below) that gets matched. If you unset all POWERLEVEL9K_GOOGLE_APP_CRED_*CONTENT_EXPANSION + # parameters, you'll see this value in your prompt. The second element of each pair in + # POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES defines the context class. Patterns are tried in order. + # The first match wins. + # + # For example, given these settings: + # + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=( + # '*:*prod*:*' PROD + # '*:*test*:*' TEST + # '*' DEFAULT) + # + # If your current Google application credentials is "service_account deathray-testing x@y.com", + # its class is TEST because it doesn't match the pattern '* *prod* *' but does match '* *test* *'. + # + # You can define different colors, icons and content expansions for different classes: + # + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_FOREGROUND=28 + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_VISUAL_IDENTIFIER_EXPANSION='⭐' + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_TEST_CONTENT_EXPANSION='$P9K_GOOGLE_APP_CRED_PROJECT_ID' + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_CLASSES=( + # '*:*prod*:*' PROD # These values are examples that are unlikely + # '*:*test*:*' TEST # to match your needs. Customize them as needed. + '*' DEFAULT) + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_FOREGROUND=7 + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_BACKGROUND=4 + # typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Use POWERLEVEL9K_GOOGLE_APP_CRED_CONTENT_EXPANSION to specify the content displayed by + # google_app_cred segment. Parameter expansions are very flexible and fast, too. See reference: + # http://zsh.sourceforge.net/Doc/Release/Expansion.html#Parameter-Expansion. + # + # You can use the following parameters in the expansion. Each of them corresponds to one of the + # fields in the JSON file pointed to by GOOGLE_APPLICATION_CREDENTIALS. + # + # Parameter | JSON key file field + # ---------------------------------+--------------- + # P9K_GOOGLE_APP_CRED_TYPE | type + # P9K_GOOGLE_APP_CRED_PROJECT_ID | project_id + # P9K_GOOGLE_APP_CRED_CLIENT_EMAIL | client_email + # + # Note: ${VARIABLE//\%/%%} expands to ${VARIABLE} with all occurrences of '%' replaced by '%%'. + typeset -g POWERLEVEL9K_GOOGLE_APP_CRED_DEFAULT_CONTENT_EXPANSION='${P9K_GOOGLE_APP_CRED_PROJECT_ID//\%/%%}' + + ##############[ toolbox: toolbox name (https://github.com/containers/toolbox) ]############### + # Toolbox color. + typeset -g POWERLEVEL9K_TOOLBOX_FOREGROUND=0 + typeset -g POWERLEVEL9K_TOOLBOX_BACKGROUND=3 + # Don't display the name of the toolbox if it matches fedora-toolbox-*. + typeset -g POWERLEVEL9K_TOOLBOX_CONTENT_EXPANSION='${P9K_TOOLBOX_NAME:#fedora-toolbox-*}' + # Custom icon. + # typeset -g POWERLEVEL9K_TOOLBOX_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_TOOLBOX_PREFIX='in ' + + ###############################[ public_ip: public IP address ]############################### + # Public IP color. + typeset -g POWERLEVEL9K_PUBLIC_IP_FOREGROUND=7 + typeset -g POWERLEVEL9K_PUBLIC_IP_BACKGROUND=0 + # Custom icon. + # typeset -g POWERLEVEL9K_PUBLIC_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ########################[ vpn_ip: virtual private network indicator ]######################### + # VPN IP color. + typeset -g POWERLEVEL9K_VPN_IP_FOREGROUND=0 + typeset -g POWERLEVEL9K_VPN_IP_BACKGROUND=6 + # When on VPN, show just an icon without the IP address. + # Tip: To display the private IP address when on VPN, remove the next line. + typeset -g POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION= + # Regular expression for the VPN network interface. Run `ifconfig` or `ip -4 a show` while on VPN + # to see the name of the interface. + typeset -g POWERLEVEL9K_VPN_IP_INTERFACE='(gpd|wg|(.*tun)|tailscale)[0-9]*|(zt.*)' + # If set to true, show one segment per matching network interface. If set to false, show only + # one segment corresponding to the first matching network interface. + # Tip: If you set it to true, you'll probably want to unset POWERLEVEL9K_VPN_IP_CONTENT_EXPANSION. + typeset -g POWERLEVEL9K_VPN_IP_SHOW_ALL=false + # Custom icon. + # typeset -g POWERLEVEL9K_VPN_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ###########[ ip: ip address and bandwidth usage for a specified network interface ]########### + # IP color. + typeset -g POWERLEVEL9K_IP_BACKGROUND=4 + typeset -g POWERLEVEL9K_IP_FOREGROUND=0 + # The following parameters are accessible within the expansion: + # + # Parameter | Meaning + # ----------------------+------------------------------------------- + # P9K_IP_IP | IP address + # P9K_IP_INTERFACE | network interface + # P9K_IP_RX_BYTES | total number of bytes received + # P9K_IP_TX_BYTES | total number of bytes sent + # P9K_IP_RX_BYTES_DELTA | number of bytes received since last prompt + # P9K_IP_TX_BYTES_DELTA | number of bytes sent since last prompt + # P9K_IP_RX_RATE | receive rate (since last prompt) + # P9K_IP_TX_RATE | send rate (since last prompt) + typeset -g POWERLEVEL9K_IP_CONTENT_EXPANSION='${P9K_IP_RX_RATE:+⇣$P9K_IP_RX_RATE }${P9K_IP_TX_RATE:+⇡$P9K_IP_TX_RATE }$P9K_IP_IP' + # Show information for the first network interface whose name matches this regular expression. + # Run `ifconfig` or `ip -4 a show` to see the names of all network interfaces. + typeset -g POWERLEVEL9K_IP_INTERFACE='[ew].*' + # Custom icon. + # typeset -g POWERLEVEL9K_IP_VISUAL_IDENTIFIER_EXPANSION='⭐' + + #########################[ proxy: system-wide http/https/ftp proxy ]########################## + # Proxy color. + typeset -g POWERLEVEL9K_PROXY_FOREGROUND=4 + typeset -g POWERLEVEL9K_PROXY_BACKGROUND=0 + # Custom icon. + # typeset -g POWERLEVEL9K_PROXY_VISUAL_IDENTIFIER_EXPANSION='⭐' + + ################################[ battery: internal battery ]################################# + # Show battery in red when it's below this level and not connected to power supply. + typeset -g POWERLEVEL9K_BATTERY_LOW_THRESHOLD=20 + typeset -g POWERLEVEL9K_BATTERY_LOW_FOREGROUND=1 + # Show battery in green when it's charging or fully charged. + typeset -g POWERLEVEL9K_BATTERY_{CHARGING,CHARGED}_FOREGROUND=2 + # Show battery in yellow when it's discharging. + typeset -g POWERLEVEL9K_BATTERY_DISCONNECTED_FOREGROUND=3 + # Battery pictograms going from low to high level of charge. + typeset -g POWERLEVEL9K_BATTERY_STAGES=('%K{232}▁' '%K{232}▂' '%K{232}▃' '%K{232}▄' '%K{232}▅' '%K{232}▆' '%K{232}▇' '%K{232}█') + # Don't show the remaining time to charge/discharge. + typeset -g POWERLEVEL9K_BATTERY_VERBOSE=false + typeset -g POWERLEVEL9K_BATTERY_BACKGROUND=0 + + #####################################[ wifi: wifi speed ]##################################### + # WiFi color. + typeset -g POWERLEVEL9K_WIFI_FOREGROUND=0 + typeset -g POWERLEVEL9K_WIFI_BACKGROUND=4 + # Custom icon. + # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Use different colors and icons depending on signal strength ($P9K_WIFI_BARS). + # + # # Wifi colors and icons for different signal strength levels (low to high). + # typeset -g my_wifi_fg=(0 0 0 0 0) # <-- change these values + # typeset -g my_wifi_icon=('WiFi' 'WiFi' 'WiFi' 'WiFi' 'WiFi') # <-- change these values + # + # typeset -g POWERLEVEL9K_WIFI_CONTENT_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}$P9K_WIFI_LAST_TX_RATE Mbps' + # typeset -g POWERLEVEL9K_WIFI_VISUAL_IDENTIFIER_EXPANSION='%F{${my_wifi_fg[P9K_WIFI_BARS+1]}}${my_wifi_icon[P9K_WIFI_BARS+1]}' + # + # The following parameters are accessible within the expansions: + # + # Parameter | Meaning + # ----------------------+--------------- + # P9K_WIFI_SSID | service set identifier, a.k.a. network name + # P9K_WIFI_LINK_AUTH | authentication protocol such as "wpa2-psk" or "none"; empty if unknown + # P9K_WIFI_LAST_TX_RATE | wireless transmit rate in megabits per second + # P9K_WIFI_RSSI | signal strength in dBm, from -120 to 0 + # P9K_WIFI_NOISE | noise in dBm, from -120 to 0 + # P9K_WIFI_BARS | signal strength in bars, from 0 to 4 (derived from P9K_WIFI_RSSI and P9K_WIFI_NOISE) + + ####################################[ time: current time ]#################################### + # Current time color. + typeset -g POWERLEVEL9K_TIME_FOREGROUND=0 + typeset -g POWERLEVEL9K_TIME_BACKGROUND=7 + # Format for the current time: 09:51:02. See `man 3 strftime`. + typeset -g POWERLEVEL9K_TIME_FORMAT='%D{%H:%M:%S}' + # If set to true, time will update when you hit enter. This way prompts for the past + # commands will contain the start times of their commands as opposed to the default + # behavior where they contain the end times of their preceding commands. + typeset -g POWERLEVEL9K_TIME_UPDATE_ON_COMMAND=false + # Custom icon. + # typeset -g POWERLEVEL9K_TIME_VISUAL_IDENTIFIER_EXPANSION='⭐' + # Custom prefix. + # typeset -g POWERLEVEL9K_TIME_PREFIX='at ' + + # Example of a user-defined prompt segment. Function prompt_example will be called on every + # prompt if `example` prompt segment is added to POWERLEVEL9K_LEFT_PROMPT_ELEMENTS or + # POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS. It displays an icon and yellow text on red background + # greeting the user. + # + # Type `p10k help segment` for documentation and a more sophisticated example. + function prompt_example() { + p10k segment -b 1 -f 3 -i '⭐' -t 'hello, %n' + } + + # User-defined prompt segments may optionally provide an instant_prompt_* function. Its job + # is to generate the prompt segment for display in instant prompt. See + # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. + # + # Powerlevel10k will call instant_prompt_* at the same time as the regular prompt_* function + # and will record all `p10k segment` calls it makes. When displaying instant prompt, Powerlevel10k + # will replay these calls without actually calling instant_prompt_*. It is imperative that + # instant_prompt_* always makes the same `p10k segment` calls regardless of environment. If this + # rule is not observed, the content of instant prompt will be incorrect. + # + # Usually, you should either not define instant_prompt_* or simply call prompt_* from it. If + # instant_prompt_* is not defined for a segment, the segment won't be shown in instant prompt. + function instant_prompt_example() { + # Since prompt_example always makes the same `p10k segment` calls, we can call it from + # instant_prompt_example. This will give us the same `example` prompt segment in the instant + # and regular prompts. + prompt_example + } + + # User-defined prompt segments can be customized the same way as built-in segments. + typeset -g POWERLEVEL9K_EXAMPLE_FOREGROUND=3 + typeset -g POWERLEVEL9K_EXAMPLE_BACKGROUND=1 + # typeset -g POWERLEVEL9K_EXAMPLE_VISUAL_IDENTIFIER_EXPANSION='⭐' + + # Transient prompt works similarly to the builtin transient_rprompt option. It trims down prompt + # when accepting a command line. Supported values: + # + # - off: Don't change prompt when accepting a command line. + # - always: Trim down prompt when accepting a command line. + # - same-dir: Trim down prompt when accepting a command line unless this is the first command + # typed after changing current working directory. + typeset -g POWERLEVEL9K_TRANSIENT_PROMPT=off + + # Instant prompt mode. + # + # - off: Disable instant prompt. Choose this if you've tried instant prompt and found + # it incompatible with your zsh configuration files. + # - quiet: Enable instant prompt and don't print warnings when detecting console output + # during zsh initialization. Choose this if you've read and understood + # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. + # - verbose: Enable instant prompt and print a warning when detecting console output during + # zsh initialization. Choose this if you've never tried instant prompt, haven't + # seen the warning, or if you are unsure what this all means. + typeset -g POWERLEVEL9K_INSTANT_PROMPT=verbose + + # Hot reload allows you to change POWERLEVEL9K options after Powerlevel10k has been initialized. + # For example, you can type POWERLEVEL9K_BACKGROUND=red and see your prompt turn red. Hot reload + # can slow down prompt by 1-2 milliseconds, so it's better to keep it turned off unless you + # really need it. + typeset -g POWERLEVEL9K_DISABLE_HOT_RELOAD=true + + # If p10k is already loaded, reload configuration. + # This works even with POWERLEVEL9K_DISABLE_HOT_RELOAD=true. + (( ! $+functions[p10k] )) || p10k reload +} + +# Tell `p10k configure` which file it should overwrite. +typeset -g POWERLEVEL9K_CONFIG_FILE=${${(%):-%x}:a} + +(( ${#p10k_config_opts} )) && setopt ${p10k_config_opts[@]} +'builtin' 'unset' 'p10k_config_opts' diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-robbyrussell.zsh b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-robbyrussell.zsh new file mode 100644 index 00000000..a59e222b --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/config/p10k-robbyrussell.zsh @@ -0,0 +1,111 @@ +# Config file for Powerlevel10k with the style of robbyrussell theme from Oh My Zsh. +# +# Original: https://github.com/ohmyzsh/ohmyzsh/wiki/Themes#robbyrussell. +# +# Replication of robbyrussell theme is exact. The only observable difference is in +# performance. Powerlevel10k prompt is very fast everywhere, even in large Git repositories. +# +# Usage: Source this file either before or after loading Powerlevel10k. +# +# source ~/powerlevel10k/config/p10k-robbyrussell.zsh +# source ~/powerlevel10k/powerlevel10k.zsh-theme + +# Temporarily change options. +'builtin' 'local' '-a' 'p10k_config_opts' +[[ ! -o 'aliases' ]] || p10k_config_opts+=('aliases') +[[ ! -o 'sh_glob' ]] || p10k_config_opts+=('sh_glob') +[[ ! -o 'no_brace_expand' ]] || p10k_config_opts+=('no_brace_expand') +'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand' + +() { + emulate -L zsh -o extended_glob + + # Unset all configuration options. + unset -m '(POWERLEVEL9K_*|DEFAULT_USER)~POWERLEVEL9K_GITSTATUS_DIR' + + # Zsh >= 5.1 is required. + [[ $ZSH_VERSION == (5.<1->*|<6->.*) ]] || return + + # Left prompt segments. + typeset -g POWERLEVEL9K_LEFT_PROMPT_ELEMENTS=(prompt_char dir vcs) + # Right prompt segments. + typeset -g POWERLEVEL9K_RIGHT_PROMPT_ELEMENTS=() + + # Basic style options that define the overall prompt look. + typeset -g POWERLEVEL9K_BACKGROUND= # transparent background + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_{LEFT,RIGHT}_WHITESPACE= # no surrounding whitespace + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SUBSEGMENT_SEPARATOR=' ' # separate segments with a space + typeset -g POWERLEVEL9K_{LEFT,RIGHT}_SEGMENT_SEPARATOR= # no end-of-line symbol + typeset -g POWERLEVEL9K_VISUAL_IDENTIFIER_EXPANSION= # no segment icons + + # Green prompt symbol if the last command succeeded. + typeset -g POWERLEVEL9K_PROMPT_CHAR_OK_{VIINS,VICMD,VIVIS}_FOREGROUND=green + # Red prompt symbol if the last command failed. + typeset -g POWERLEVEL9K_PROMPT_CHAR_ERROR_{VIINS,VICMD,VIVIS}_FOREGROUND=red + # Prompt symbol: bold arrow. + typeset -g POWERLEVEL9K_PROMPT_CHAR_CONTENT_EXPANSION='%B➜ ' + + # Cyan current directory. + typeset -g POWERLEVEL9K_DIR_FOREGROUND=cyan + # Show only the last segment of the current directory. + typeset -g POWERLEVEL9K_SHORTEN_STRATEGY=truncate_to_last + # Bold directory. + typeset -g POWERLEVEL9K_DIR_CONTENT_EXPANSION='%B$P9K_CONTENT' + + # Git status formatter. + function my_git_formatter() { + emulate -L zsh + if [[ -n $P9K_CONTENT ]]; then + # If P9K_CONTENT is not empty, it's either "loading" or from vcs_info (not from + # gitstatus plugin). VCS_STATUS_* parameters are not available in this case. + typeset -g my_git_format=$P9K_CONTENT + else + # Use VCS_STATUS_* parameters to assemble Git status. See reference: + # https://github.com/romkatv/gitstatus/blob/master/gitstatus.plugin.zsh. + typeset -g my_git_format="${1+%B%4F}git:(${1+%1F}" + my_git_format+=${${VCS_STATUS_LOCAL_BRANCH:-${VCS_STATUS_COMMIT[1,8]}}//\%/%%} + my_git_format+="${1+%4F})" + if (( VCS_STATUS_NUM_CONFLICTED || VCS_STATUS_NUM_STAGED || + VCS_STATUS_NUM_UNSTAGED || VCS_STATUS_NUM_UNTRACKED )); then + my_git_format+=" ${1+%3F}✗" + fi + fi + } + functions -M my_git_formatter 2>/dev/null + + # Disable the default Git status formatting. + typeset -g POWERLEVEL9K_VCS_DISABLE_GITSTATUS_FORMATTING=true + # Install our own Git status formatter. + typeset -g POWERLEVEL9K_VCS_CONTENT_EXPANSION='${$((my_git_formatter(1)))+${my_git_format}}' + typeset -g POWERLEVEL9K_VCS_LOADING_CONTENT_EXPANSION='${$((my_git_formatter()))+${my_git_format}}' + # Grey Git status when loading. + typeset -g POWERLEVEL9K_VCS_LOADING_FOREGROUND=246 + + # Instant prompt mode. + # + # - off: Disable instant prompt. Choose this if you've tried instant prompt and found + # it incompatible with your zsh configuration files. + # - quiet: Enable instant prompt and don't print warnings when detecting console output + # during zsh initialization. Choose this if you've read and understood + # https://github.com/romkatv/powerlevel10k/blob/master/README.md#instant-prompt. + # - verbose: Enable instant prompt and print a warning when detecting console output during + # zsh initialization. Choose this if you've never tried instant prompt, haven't + # seen the warning, or if you are unsure what this all means. + typeset -g POWERLEVEL9K_INSTANT_PROMPT=verbose + + # Hot reload allows you to change POWERLEVEL9K options after Powerlevel10k has been initialized. + # For example, you can type POWERLEVEL9K_BACKGROUND=red and see your prompt turn red. Hot reload + # can slow down prompt by 1-2 milliseconds, so it's better to keep it turned off unless you + # really need it. + typeset -g POWERLEVEL9K_DISABLE_HOT_RELOAD=true + + # If p10k is already loaded, reload configuration. + # This works even with POWERLEVEL9K_DISABLE_HOT_RELOAD=true. + (( ! $+functions[p10k] )) || p10k reload +} + +# Tell `p10k configure` which file it should overwrite. +typeset -g POWERLEVEL9K_CONFIG_FILE=${${(%):-%x}:a} + +(( ${#p10k_config_opts} )) && setopt ${p10k_config_opts[@]} +'builtin' 'unset' 'p10k_config_opts' diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/font.md b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/font.md new file mode 100644 index 00000000..2fb2f8be --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/font.md @@ -0,0 +1,161 @@ +# Recommended font: Meslo Nerd Font patched for Powerlevel10k + +Gorgeous monospace font designed by Jim Lyles for Bitstream, customized by the same for Apple, +further customized by André Berg, and finally patched by yours truly with customized scripts +originally developed by Ryan L McIntyre of Nerd Fonts. Contains all glyphs and symbols that +Powerlevel10k may need. Battle-tested in dozens of different terminals on all major operating +systems. + +*FAQ*: [How was the recommended font created?](README.md#how-was-the-recommended-font-created) + +## Automatic font installation + +If you are using iTerm2 or Termux, `p10k configure` can install the recommended font for you. +Simply answer `Yes` when asked whether to install *Meslo Nerd Font*. + +If you are using a different terminal, proceed with manual font installation. 👇 + +## Manual font installation + +1. Download these four ttf files: + - [MesloLGS NF Regular.ttf]( + https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Regular.ttf) + - [MesloLGS NF Bold.ttf]( + https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Bold.ttf) + - [MesloLGS NF Italic.ttf]( + https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Italic.ttf) + - [MesloLGS NF Bold Italic.ttf]( + https://github.com/romkatv/powerlevel10k-media/raw/master/MesloLGS%20NF%20Bold%20Italic.ttf) +1. Double-click on each file and click "Install". This will make `MesloLGS NF` font available to all + applications on your system. +1. Configure your terminal to use this font: + - **iTerm2**: Type `p10k configure` and answer `Yes` when asked whether to install + *Meslo Nerd Font*. Alternatively, open *iTerm2 → Preferences → Profiles → Text* and set *Font* to + `MesloLGS NF`. + - **Apple Terminal**: Open *Terminal → Preferences → Profiles → Text*, click *Change* under *Font* + and select `MesloLGS NF` family. + - **Hyper**: Open *Hyper → Edit → Preferences* and change the value of `fontFamily` under + `module.exports.config` to `MesloLGS NF`. + - **Visual Studio Code**: Open *File → Preferences → Settings* (PC) or + *Code → Preferences → Settings* (Mac), enter `terminal.integrated.fontFamily` in the search box at + the top of *Settings* tab and set the value below to `MesloLGS NF`. + Consult [this screenshot]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/389133fb8c9a2347929a23702ce3039aacc46c3d/visual-studio-code-font-settings.jpg) + to see how it should look like or see [this issue]( + https://github.com/romkatv/powerlevel10k/issues/671) for extra information. + - **GNOME Terminal** (the default Ubuntu terminal): Open *Terminal → Preferences* and click on the + selected profile under *Profiles*. Check *Custom font* under *Text Appearance* and select + `MesloLGS NF Regular`. + - **Konsole**: Open *Settings → Edit Current Profile → Appearance*, click *Select Font* and select + `MesloLGS NF Regular`. + - **Tilix**: Open *Tilix → Preferences* and click on the selected profile under *Profiles*. Check + *Custom font* under *Text Appearance* and select `MesloLGS NF Regular`. + - **Windows Console Host** (the old thing): Click the icon in the top left corner, then + *Properties → Font* and set *Font* to `MesloLGS NF`. + - **Windows Terminal** by Microsoft (the new thing): Open *Settings* (Ctrl+,), click + either on the selected profile under *Profiles* or on *Defaults*, click *Appearance* and set + *Font face* to `MesloLGS NF`. + - **IntelliJ** (and other IDEs by Jet Brains): Open *IDE → Edit → Preferences → Editor → + Color Scheme → Console Font*. Select *Use console font instead of the default* and set the font + name to `MesloLGS NF`. + - **Termux**: Type `p10k configure` and answer `Yes` when asked whether to install + *Meslo Nerd Font*. + - **Blink**: Type `config`, go to *Appearance*, tap *Add a new font*, tap *Open Gallery*, select + *MesloLGS NF.css*, tap *import* and type `exit` in the home view to reload the font. + - **Tabby** (formerly **Terminus**): Open *Settings → Appearance* and set *Font* to `MesloLGS NF`. + - **Terminator**: Open *Preferences* using the context menu. Under *Profiles* select the *General* + tab (should be selected already), uncheck *Use the system fixed width font* (if not already) + and select `MesloLGS NF Regular`. Exit the Preferences dialog by clicking *Close*. + - **Guake**: Right Click on an open terminal and open *Preferences*. Under *Appearance* + tab, uncheck *Use the system fixed width font* (if not already) and select `MesloLGS NF Regular`. + Exit the Preferences dialog by clicking *Close*. + - **MobaXterm**: Open *Settings* → *Configuration* → *Terminal* → (under *Terminal look and feel*) + and change *Font* to `MesloLGS NF`. + - **Asbrú Connection Manager**: Open *Preferences → Local Shell Options → Look and Feel*, enable + *Use these personal options* and change *Font:* under *Terminal UI* to `MesloLGS NF Regular`. + To change the font for the remote host connections, go to *Preferences → Terminal Options → + Look and Feel* and change *Font:* under *Terminal UI* to `MesloLGS NF Regular`. + - **WSLtty**: Right click on an open terminal and then on *Options*. In the *Text* section, under + *Font*, click *"Select..."* and set Font to `MesloLGS NF Regular`. + - **Yakuake**: Click *≡* → *Manage Profiles* → *New* → *Appearance*. Click *Choose* next to the + *Font* dropdown, select `MesloLGS NF` and click *OK*. Click *OK* to save the profile. Select the + new profile and click *Set as Default*. + - **Alacritty**: Create or open `~/.config/alacritty/alacritty.yml` and add the following section + to it: + ```yaml + font: + normal: + family: "MesloLGS NF" + ``` + - **kitty**: Create or open `~/.config/kitty/kitty.conf` and add the following line to it: + ```text + font_family MesloLGS NF + ``` + Restart kitty by closing all sessions and opening a new session. + - **puTTY**: Set *Window* → *Appearance* → *Font* to `MesloLGS NF`. Requires puTTY + version >= 0.75. + - **WezTerm**: Create or open `$HOME/.config/wezterm/wezterm.lua` and add the following: + ```lua + local wezterm = require 'wezterm'; + return { + font = wezterm.font("MesloLGS NF"), + } + ``` + If the file already exists, only add the line with the font to the existing return. + Also add the first line if it is not already present. + - **urxvt**: Create or open `~/.Xresources` and add the following line to it: + ```text + URxvt.font: xft:MesloLGS NF:size=11 + ``` + You can adjust the font size to your preference. After changing the config run + `xrdb ~/.Xresources` to reload it. The new config is applied to all new terminals. + - **xterm**: Create or open `~/.Xresources` and add the following line to it: + ```text + xterm*faceName: MesloLGS NF + ``` + After changing the config run `xrdb ~/.Xresources` to reload it. The new config is applied to + all new terminals. + - **Zed**: Open `~/.config/zed/settings.json` and set `terminal.font_family` to `"MesloLGS NF"`. + ```jsonc + { + "terminal": { + "font_family": "MesloLGS NF" + }, + // Other settings. + } + ``` + - Crostini (Linux on Chrome OS): Open + chrome-untrusted://terminal/html/nassh_preferences_editor.html, set *Text font family* to + `'MesloLGS NF'` (including the quotes) and *Custom CSS (inline text)* to the following: + ```css + @font-face { + font-family: "MesloLGS NF"; + src: url("https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/MesloLGS%20NF%20Regular.ttf"); + font-weight: normal; + font-style: normal; + } + @font-face { + font-family: "MesloLGS NF"; + src: url("https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/MesloLGS%20NF%20Bold.ttf"); + font-weight: bold; + font-style: normal; + } + @font-face { + font-family: "MesloLGS NF"; + src: url("https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/MesloLGS%20NF%20Italic.ttf"); + font-weight: normal; + font-style: italic; + } + @font-face { + font-family: "MesloLGS NF"; + src: url("https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/MesloLGS%20NF%20Bold%20Italic.ttf"); + font-weight: bold; + font-style: italic; + } + ``` + **_CAVEAT_**: If you open the normal terminal preferences these settings will be overwritten. +1. Run `p10k configure` to generate a new `~/.p10k.zsh`. The old config may work + incorrectly with the new font. + +_Using a different terminal and know how to set the font for it? Share your knowledge by sending a +PR to expand the list!_ diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.clang-format b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.clang-format new file mode 100644 index 00000000..f5e3c53f --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.clang-format @@ -0,0 +1,4 @@ +BasedOnStyle: Google +ColumnLimit: 100 +DerivePointerAlignment: false +PointerAlignment: Left diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.gitattributes b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.gitattributes new file mode 100644 index 00000000..5c1135cb --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.gitattributes @@ -0,0 +1,16 @@ +* text=auto + +*.cc text eol=lf +*.h text eol=lf +*.info text eol=lf +*.json text eol=lf +*.md text eol=lf +*.sh text eol=lf +*.zsh text eol=lf + +/.clang-format text eol=lf +/LICENSE text eol=lf +/Makefile text eol=lf +/build text eol=lf +/install text eol=lf +/mbuild text eol=lf diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.gitignore b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.gitignore new file mode 100644 index 00000000..4915fe60 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.gitignore @@ -0,0 +1,8 @@ +*.zwc +/core +/deps/libgit2-*.tar.gz +/locks +/logs +/obj +/usrbin/gitstatusd* +/.vscode/ipch diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.vscode/c_cpp_properties.json b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.vscode/c_cpp_properties.json new file mode 100644 index 00000000..323a6cde --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.vscode/c_cpp_properties.json @@ -0,0 +1,17 @@ +{ + "configurations": [ + { + "name": "Linux", + "includePath": [ + "${workspaceFolder}/src" + ], + "defines": [ + ], + "compilerPath": "/usr/bin/g++", + "cStandard": "c11", + "cppStandard": "c++17", + "intelliSenseMode": "gcc-x64" + } + ], + "version": 4 +} diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.vscode/settings.json b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.vscode/settings.json new file mode 100644 index 00000000..bec79f94 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/.vscode/settings.json @@ -0,0 +1,72 @@ +{ + "files.exclude": { + "*.zwc": true, + "core": true, + "locks/": true, + "logs/": true, + "obj/": true, + "usrbin/": true, + }, + "files.associations": { + "array": "cpp", + "atomic": "cpp", + "*.tcc": "cpp", + "cctype": "cpp", + "chrono": "cpp", + "clocale": "cpp", + "cmath": "cpp", + "complex": "cpp", + "condition_variable": "cpp", + "cstddef": "cpp", + "cstdint": "cpp", + "cstdio": "cpp", + "cstdlib": "cpp", + "cstring": "cpp", + "ctime": "cpp", + "cwchar": "cpp", + "cwctype": "cpp", + "deque": "cpp", + "unordered_map": "cpp", + "unordered_set": "cpp", + "vector": "cpp", + "exception": "cpp", + "fstream": "cpp", + "functional": "cpp", + "future": "cpp", + "initializer_list": "cpp", + "iomanip": "cpp", + "iosfwd": "cpp", + "iostream": "cpp", + "istream": "cpp", + "limits": "cpp", + "memory": "cpp", + "mutex": "cpp", + "new": "cpp", + "numeric": "cpp", + "optional": "cpp", + "ostream": "cpp", + "ratio": "cpp", + "sstream": "cpp", + "stdexcept": "cpp", + "streambuf": "cpp", + "string_view": "cpp", + "system_error": "cpp", + "thread": "cpp", + "type_traits": "cpp", + "tuple": "cpp", + "typeinfo": "cpp", + "utility": "cpp", + "variant": "cpp", + "cstdarg": "cpp", + "charconv": "cpp", + "algorithm": "cpp", + "cinttypes": "cpp", + "iterator": "cpp", + "map": "cpp", + "memory_resource": "cpp", + "random": "cpp", + "string": "cpp", + "bit": "cpp", + "netfwd": "cpp" + } +} diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/LICENSE b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/LICENSE new file mode 100644 index 00000000..f288702d --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/LICENSE @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + + Copyright (C) + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see . + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + Copyright (C) + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +. diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/Makefile b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/Makefile new file mode 100644 index 00000000..fede08af --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/Makefile @@ -0,0 +1,57 @@ +APPNAME ?= gitstatusd +OBJDIR ?= obj + +CXX ?= g++ +ZSH := $(shell command -v zsh 2> /dev/null) + +VERSION ?= $(shell . ./build.info && printf "%s" "$$gitstatus_version") + +# Note: -fsized-deallocation is not used to avoid binary compatibility issues on macOS. +# +# Sized delete is implemented as __ZdlPvm in /usr/lib/libc++.1.dylib but this symbol is +# missing in macOS prior to 10.13. +CXXFLAGS += -std=c++14 -funsigned-char -O3 -DNDEBUG -DGITSTATUS_VERSION=$(VERSION) -Wall -Werror # -g -fsanitize=thread +LDFLAGS += -pthread # -fsanitize=thread +LDLIBS += -lgit2 # -lprofiler -lunwind + +SRCS := $(shell find src -name "*.cc") +OBJS := $(patsubst src/%.cc, $(OBJDIR)/%.o, $(SRCS)) + +all: $(APPNAME) + +$(APPNAME): usrbin/$(APPNAME) + +usrbin/$(APPNAME): $(OBJS) + $(CXX) $(OBJS) $(LDFLAGS) $(LDLIBS) -o $@ + +$(OBJDIR): + mkdir -p -- $(OBJDIR) + +$(OBJDIR)/%.o: src/%.cc Makefile build.info | $(OBJDIR) + $(CXX) $(CXXFLAGS) -MM -MT $@ src/$*.cc >$(OBJDIR)/$*.dep + $(CXX) $(CXXFLAGS) -Wall -c -o $@ src/$*.cc + +clean: + rm -rf -- $(OBJDIR) + +zwc: + $(or $(ZSH),:) -fc 'for f in *.zsh install; do zcompile -R -- $$f.zwc $$f || exit; done' + +minify: + rm -rf -- .clang-format .git .gitattributes .gitignore .vscode deps docs src usrbin/.gitkeep LICENSE Makefile README.md build mbuild + +pkg: zwc + GITSTATUS_DAEMON= GITSTATUS_CACHE_DIR=$(shell pwd)/usrbin ./install -f + +-include $(OBJS:.o=.dep) + +.PHONY: help + +help: + @echo "Usage: make [TARGET]" + @echo "Available targets:" + @echo " all Build $(APPNAME) (default target)" + @echo " clean Remove generated files and directories" + @echo " zwc Compile Zsh files" + @echo " minify Remove unnecessary files and folders" + @echo " pkg Create a package" diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/README.md b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/README.md new file mode 100644 index 00000000..a6631f63 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/README.md @@ -0,0 +1,530 @@ +# gitstatus + +**gitstatus** is a 10x faster alternative to `git status` and `git describe`. Its primary use +case is to enable fast git prompt in interactive shells. + +Heavy lifting is done by **gitstatusd** -- a custom binary written in C++. It comes with Zsh and +Bash bindings for integration with shell. + +## Table of Contents + +1. [Using from Zsh](#using-from-zsh) +1. [Using from Bash](#using-from-bash) +2. [Using from other shells](#using-from-other-shells) +1. [How it works](#how-it-works) +1. [Benchmarks](#benchmarks) +1. [Why fast](#why-fast) +1. [Requirements](#requirements) +1. [Compiling](#compiling) +1. [License](#license) + +## Using from Zsh + +The easiest way to take advantage of gitstatus from Zsh is to use a theme that's already integrated +with it. For example, [Powerlevel10k](https://github.com/romkatv/powerlevel10k) is a flexible and +fast theme with first-class gitstatus integration. If you install Powerlevel10k, you don't need to +install gitstatus. + +![Powerlevel10k Zsh Theme]( + https://raw.githubusercontent.com/romkatv/powerlevel10k-media/master/prompt-styles-high-contrast.png) + +For those who wish to use gitstatus without a theme, there is +[gitstatus.prompt.zsh](gitstatus.prompt.zsh). Install it as follows: + +```zsh +git clone --depth=1 https://github.com/romkatv/gitstatus.git ~/gitstatus +echo 'source ~/gitstatus/gitstatus.prompt.zsh' >>! ~/.zshrc +``` + +Users in China can use the official mirror on gitee.com for faster download.
+中国大陆用户可以使用 gitee.com 上的官方镜像加速下载. + +```zsh +git clone --depth=1 https://gitee.com/romkatv/gitstatus.git ~/gitstatus +echo 'source ~/gitstatus/gitstatus.prompt.zsh' >>! ~/.zshrc +``` + +Alternatively, if you have Homebrew installed: + +```zsh +brew install romkatv/gitstatus/gitstatus +echo "source $(brew --prefix)/opt/gitstatus/gitstatus.prompt.zsh" >>! ~/.zshrc +``` + +(If you choose this option, replace `~/gitstatus` with `$(brew --prefix)/opt/gitstatus/gitstatus` +in all code snippets below.) + +_Make sure to disable your current theme if you have one._ + +This will give you a basic yet functional prompt with git status in it. It's +[over 10x faster](#benchmarks) than any alternative that can give you comparable prompt. In order +to customize it, set `PROMPT` and/or `RPROMPT` at the end of `~/.zshrc` after sourcing +`gitstatus.prompt.zsh`. Insert `${GITSTATUS_PROMPT}` where you want git status to go. For example: + +```zsh +source ~/gitstatus/gitstatus.prompt.zsh + +PROMPT='%~%# ' # left prompt: directory followed by %/# (normal/root) +RPROMPT='$GITSTATUS_PROMPT' # right prompt: git status +``` + +The expansion of `${GITSTATUS_PROMPT}` can contain the following bits: + +| segment | meaning | +|-------------|-------------------------------------------------------| +| `master` | current branch | +| `#v1` | HEAD is tagged with `v1`; not shown when on a branch | +| `@5fc6fca4` | current commit; not shown when on a branch or tag | +| `⇣1` | local branch is behind the remote by 1 commit | +| `⇡2` | local branch is ahead of the remote by 2 commits | +| `⇠3` | local branch is behind the push remote by 3 commits | +| `⇢4` | local branch is ahead of the push remote by 4 commits | +| `*5` | there are 5 stashes | +| `merge` | merge is in progress (could be some other action) | +| `~6` | there are 6 merge conflicts | +| `+7` | there are 7 staged changes | +| `!8` | there are 8 unstaged changes | +| `?9` | there are 9 untracked files | + +`$GITSTATUS_PROMPT_LEN` tells you how long `$GITSTATUS_PROMPT` is when printed to the console. +[gitstatus.prompt.zsh](gitstatus.prompt.zsh) has an example of using it to truncate the current +directory. + +If you'd like to change the format of git status, or want to have greater control over the +process of assembling `PROMPT`, you can copy and modify parts of +[gitstatus.prompt.zsh](gitstatus.prompt.zsh) instead of sourcing the script. Your `~/.zshrc` +might look something like this: + +```zsh +source ~/gitstatus/gitstatus.plugin.zsh + +function my_set_prompt() { + PROMPT='%~%# ' + RPROMPT='' + + if gitstatus_query MY && [[ $VCS_STATUS_RESULT == ok-sync ]]; then + RPROMPT=${${VCS_STATUS_LOCAL_BRANCH:-@${VCS_STATUS_COMMIT}}//\%/%%} # escape % + (( VCS_STATUS_NUM_STAGED )) && RPROMPT+='+' + (( VCS_STATUS_NUM_UNSTAGED )) && RPROMPT+='!' + (( VCS_STATUS_NUM_UNTRACKED )) && RPROMPT+='?' + fi + + setopt no_prompt_{bang,subst} prompt_percent # enable/disable correct prompt expansions +} + +gitstatus_stop 'MY' && gitstatus_start -s -1 -u -1 -c -1 -d -1 'MY' +autoload -Uz add-zsh-hook +add-zsh-hook precmd my_set_prompt +``` + +This snippet is sourcing `gitstatus.plugin.zsh` rather than `gitstatus.prompt.zsh`. The former +defines low-level bindings that communicate with gitstatusd over pipes. The latter is a simple +script that uses these bindings to assemble git prompt. + +Unlike [Powerlevel10k](https://github.com/romkatv/powerlevel10k), code based on +[gitstatus.prompt.zsh](gitstatus.prompt.zsh) is communicating with gitstatusd synchronously. This +can make your prompt slow when working in a large git repository or on a slow machine. To avoid +this problem, call `gitstatus_query` asynchronously as documented in +[gitstatus.plugin.zsh](gitstatus.plugin.zsh). This can be quite challenging. + +## Using from Bash + +The easiest way to take advantage of gitstatus from Bash is via +[gitstatus.prompt.sh](gitstatus.prompt.sh). Install it as follows: + +```bash +git clone --depth=1 https://github.com/romkatv/gitstatus.git ~/gitstatus +echo 'source ~/gitstatus/gitstatus.prompt.sh' >> ~/.bashrc +``` + +Users in China can use the official mirror on gitee.com for faster download.
+中国大陆用户可以使用 gitee.com 上的官方镜像加速下载. + +```bash +git clone --depth=1 https://gitee.com/romkatv/gitstatus.git ~/gitstatus +echo 'source ~/gitstatus/gitstatus.prompt.sh' >> ~/.bashrc +``` + +Alternatively, if you have Homebrew installed: + +```zsh +brew install romkatv/gitstatus/gitstatus +echo "source $(brew --prefix)/opt/gitstatus/gitstatus.prompt.sh" >> ~/.bashrc +``` + +(If you choose this option, replace `~/gitstatus` with `$(brew --prefix)/opt/gitstatus/gitstatus` +in all code snippets below.) + +This will give you a basic yet functional prompt with git status in it. It's +[over 10x faster](#benchmarks) than any alternative that can give you comparable prompt. + +![Bash Prompt with GitStatus]( + https://raw.githubusercontent.com/romkatv/gitstatus/1ac366952366d89980b3f3484f270b4fa5ae4293/bash-prompt.png) + +In order to customize your prompt, set `PS1` at the end of `~/.bashrc` after sourcing +`gitstatus.prompt.sh`. Insert `${GITSTATUS_PROMPT}` where you want git status to go. For example: + +```bash +source ~/gitstatus/gitstatus.prompt.sh + +PS1='\w ${GITSTATUS_PROMPT}\n\$ ' # directory followed by git status and $/# (normal/root) +``` + +The expansion of `${GITSTATUS_PROMPT}` can contain the following bits: + +| segment | meaning | +|-------------|-------------------------------------------------------| +| `master` | current branch | +| `#v1` | HEAD is tagged with `v1`; not shown when on a branch | +| `@5fc6fca4` | current commit; not shown when on a branch or tag | +| `⇣1` | local branch is behind the remote by 1 commit | +| `⇡2` | local branch is ahead of the remote by 2 commits | +| `⇠3` | local branch is behind the push remote by 3 commits | +| `⇢4` | local branch is ahead of the push remote by 4 commits | +| `*5` | there are 5 stashes | +| `merge` | merge is in progress (could be some other action) | +| `~6` | there are 6 merge conflicts | +| `+7` | there are 7 staged changes | +| `!8` | there are 8 unstaged changes | +| `?9` | there are 9 untracked files | + +If you'd like to change the format of git status, or want to have greater control over the +process of assembling `PS1`, you can copy and modify parts of +[gitstatus.prompt.sh](gitstatus.prompt.sh) instead of sourcing the script. Your `~/.bashrc` might +look something like this: + +```bash +source ~/gitstatus/gitstatus.plugin.sh + +function my_set_prompt() { + PS1='\w' + + if gitstatus_query && [[ "$VCS_STATUS_RESULT" == ok-sync ]]; then + if [[ -n "$VCS_STATUS_LOCAL_BRANCH" ]]; then + PS1+=" ${VCS_STATUS_LOCAL_BRANCH//\\/\\\\}" # escape backslash + else + PS1+=" @${VCS_STATUS_COMMIT//\\/\\\\}" # escape backslash + fi + (( VCS_STATUS_HAS_STAGED" )) && PS1+='+' + (( VCS_STATUS_HAS_UNSTAGED" )) && PS1+='!' + (( VCS_STATUS_HAS_UNTRACKED" )) && PS1+='?' + fi + + PS1+='\n\$ ' + + shopt -u promptvars # disable expansion of '$(...)' and the like +} + +gitstatus_stop && gitstatus_start +PROMPT_COMMAND=my_set_prompt +``` + +This snippet is sourcing `gitstatus.plugin.sh` rather than `gitstatus.prompt.sh`. The former +defines low-level bindings that communicate with gitstatusd over pipes. The latter is a simple +script that uses these bindings to assemble git prompt. + +Note: Bash bindings, unlike Zsh bindings, don't support asynchronous calls. + +## Using from other shells + +If there are no gitstatusd bindings for your shell, you'll need to get your hands dirty. +Use the existing bindings for inspiration; run `gitstatusd --help` or read the same thing in +[options.cc](src/options.cc). + +## How it works + +gitstatusd reads requests from stdin and prints responses to stdout. Requests contain an ID and +a directory. Responses contain the same ID and machine-readable git status for the directory. +gitstatusd keeps some state in memory for the directories it has seen in order to serve future +requests faster. + +[Zsh bindings](gitstatus.plugin.zsh) and [Bash bindings](gitstatus.plugin.sh) start gitstatusd in +the background and communicate with it via pipes. Themes such as +[Powerlevel10k](https://github.com/romkatv/powerlevel10k) use these bindings to put git status in +`PROMPT`. + +Note that gitstatus cannot be used as a drop-in replacement for `git status` command as it doesn't +produce output in the same format. It does perform the same computation though. + +## Benchmarks + +The following benchmark results were obtained on Intel i9-7900X running Ubuntu 18.04 in +a clean [chromium](https://github.com/chromium/chromium) repository synced to `9394e49a`. The +repository was checked out to an ext4 filesystem on M.2 SSD. + +Three functionally equivalent tools for computing git status were benchmarked: + +* `gitstatusd` +* `git` with `core.untrackedcache` enabled and `core.fsmonitor` disabled +* `lg2` -- a demo/example executable from [libgit2](https://github.com/romkatv/libgit2) that + implements a subset of `git` functionality on top of libgit2 API; for the purposes of this + benchmark the subset is sufficient to generate the same data as the other tools + +Every tool was benchmark in cold and hot conditions. For `git` the first run in a repository was +considered cold, with the following runs considered hot. `lg2` was patched to compute results twice +in a single invocation without freeing the repository in between; the second run was considered hot. +The same patching was not done for `git` because `git` cannot be easily modified to refresh inmemory +index state between invocations; in fact, this limitation is one of the primary reasons developers +use libgit2. `gitstatusd` was benchmarked similarly to `lg2` with two result computations in the +same invocation. + +Two commands were benchmarked: `status` and `describe`. + +### Status + +In this benchmark all tools were computing the equivalent of `git status`. Lower numbers are better. + +| Tool | Cold | Hot | +|---------------|-----------:|------------:| +| **gitstatus** | **291 ms** | **30.9 ms** | +| git | 876 ms | 295 ms | +| lg2 | 1730 ms | 1310 ms | + +gitstatusd is substantially faster than the alternatives, especially on hot runs. Note that hot runs +are of primary importance to the main use case of gitstatus in interactive shells. + +The performance of `git status` fluctuated wildly in this benchmarks for reasons unknown to the +author. Moreover, performance is sticky -- once `git status` settles around a number, it stays +there for a long time. Numbers as diverse as 295, 352, 663 and 730 had been observed on hot runs on +the same repository. The number in the table is the lowest (fastest or best) that `git status` had +shown. + +### Describe + +In this benchmark all tools were computing the equivalent of `git describe --tags --exact-match` +to find tags that resolve to the same commit as `HEAD`. Lower numbers are better. + +| Tool | Cold | Hot | +|---------------|------------:|--------------:| +| **gitstatus** | **4.04 ms** | **0.0345 ms** | +| git | 18.0 ms | 14.5 ms | +| lg2 | 185 ms | 45.2 ms | + +gitstatusd is once again faster than the alternatives, more so on hot runs. + +## Why fast + +Since gitstatusd doesn't have to print all staged/unstaged/untracked files but only report +whether there are any, it can terminate repository scan early. It can also remember which files +were dirty on the previous run and check them first on the next run to avoid the scan entirely if +the files are still dirty. However, the benchmarks above were performed in a clean repository where +these shortcuts do not trigger. All benchmarked tools had to do the same work -- check the status +of every file in the index to see if it has changed, check every directory for newly created files, +etc. And yet, gitstatusd came ahead by a large margin. This section describes what it does that +makes it so fast. + +Most of the following comparisons are done against libgit2 rather than git because of the author's +familiarity with the former but not the with latter. libgit2 has clean, well-documented APIs and an +elegant implementation, which makes it so much easier to work with and to analyze performance +bottlenecks. + +### Summary for the impatient + +Under the benchmark conditions described above, the equivalent of libgit2's +`git_diff_index_to_workdir` (the most expensive part of `status` command) is 46.3 times faster in +gitstatusd. The speedup comes from the following sources. + +* gitstatusd uses more efficient data structures and algorithms and employs performance-conscious +coding style throughout the codebase. This reduces CPU time in userspace by 32x compared to libgit2. +* gitstatusd uses less expensive system calls and makes fewer of them. This reduces CPU time spent +in kernel by 1.9x. +* gitstatusd can utilize multiple cores to scan index and workdir in parallel with almost perfect +scaling. This reduces total run time by 12.4x while having virtually no effect on total CPU time. + +### Problem statement + +The most resource-intensive part of the `status` command is finding the difference between _index_ +and _workdir_ (`git_diff_index_to_workdir` in libgit2). Index is a list of all files in the git +repository with their last modification times. This is an obvious simplification but it suffices for +this exposition. On disk, index is stored sorted by file path. Here's an example of git index: + +| File | Last modification time | +|-------------|-----------------------:| +| Makefile | 2019-04-01T14:12:32Z | +| src/hello.c | 2019-04-01T14:12:00Z | +| src/hello.h | 2019-04-01T14:12:32Z | + +This list needs to be compared to the list of files in the working directory. If any of the files +listed in the index are missing from the workdir or have different last modification time, they are +"unstaged" in gitstatusd parlance. If you run `git status`, they'll be shown as "changes not staged +for commit". Thus, any implementation of `status` command has to call `stat()` or one of its +variants on every file in the index. + +In addition, all files in the working directory for which there is no entry in the index at all are +"untracked". `git status` will show them as "untracked files". Finding untracked files requires some +form of work directory traversal. + +### Single-threaded scan + +Let's see how `git_diff_index_to_workdir` from libgit2 accomplishes these tasks. Here's its CPU +profile from 200 hot runs over chromium repository. + +![libgit2 CPU profile (hot)]( + https://raw.githubusercontent.com/romkatv/gitstatus/1ac366952366d89980b3f3484f270b4fa5ae4293/cpu-profile-libgit2.png) + +(The CPU profile was created with [gperftools](https://github.com/gperftools/gperftools) and +rendered with [pprof](https://github.com/google/pprof)). + +We can see `__GI__lxstat` taking a lot of time. This is the `stat()` call for every file in the +index. We can also identify `__opendir`, `__readdir` and `__GI___close_nocancel` -- glibc wrappers +for reading the contents of a directory. This is for finding untracked files. Out of the total 232 +seconds, 111 seconds -- or 47.7% -- was spent on these calls. The rest is computation -- comparing +strings, sorting arrays, etc. + +Now let's take a look at the CPU profile of gitstatusd on the same task. + +![gitstatusd CPU profile (hot)]( + https://raw.githubusercontent.com/romkatv/gitstatus/1ac366952366d89980b3f3484f270b4fa5ae4293/cpu-profile-gitstatusd-hot.png) + +The first impression is that this profile looks pruned. This isn't an artifact. The profile was +generated with the same tools and the same flags as the profile of libgit2. + +Since both profiles were generated from the same workload, absolute numbers can be compared. We can +see that gitstatusd took 62 seconds in total compared to libgit2's 232 seconds. System calls at the +core of the algorithm are clearly visible. `__GI___fxstatat` is a flavor of `stat()`, and the other +three calls -- `__libc_openat64`, `__libc_close` and `__GI___fxstat` are responsible for opening +directories and finding untracked files. Notice that there is almost nothing else in the profile +apart from these calls. The rest of the code accounts for 3.77 seconds of CPU time -- 32 times less +than in libgit2. + +So, one reason gitstatusd is fast is that it has efficient diffing code -- very little time is spent +outside of kernel. However, if we look closely, we can notice that system calls in gitstatusd are +_also_ faster than in libgit2. For example, libgit2 spent 72.07 seconds in `__GI__lxstat` while +gitstatusd spent only 48.82 seconds in `__GI___fxstatat`. There are two reasons for this difference. +First, libgit2 makes more `stat()` calls than is strictly required. It's not necessary to stat +directories because index only has files. There are 25k directories in chromium repository (and 300k +files) -- that's 25k `stat()` calls that could be avoided. The second reason is that libgit2 and +gitstatusd use different flavors of `stat()`. libgit2 uses `lstat()`, which takes a path to the file +as input. Its performance is linear in the number of subdirectories in the path because it needs to +perform a lookup for every one of them and to check permissions. gitstatusd uses `fstatat()`, which +takes a file descriptor to the parent directory and a name of the file. Just a single lookup, less +CPU time. + +Similarly to `lstat()` vs `fstatat()`, it's faster to open files and directories with `openat()` +from the parent directory file descriptor than with regular `open()` that accepts full file path. +gitstatusd takes advantage of `openat()` to open directories as fast as possible. It opens about 90% +of the directories (this depends on the actual directory structure of the repository) from the +immediate parent -- the most efficient way -- and the remaining 10% it opens from the repository's +root directory. The reason it's done this way is to keep the maximum number of simultaneously open +file descriptors bounded. libgit2 can have O(repository depth) simultaneously open file descriptors, +which may be OK for a single-threaded application but can balloon to a large number when scans are +done by many threads simultaneously, like in gitstatusd. + +There is no equivalent to `__opendir` or `__readdir` in the gitstatusd profile because it uses the +equivalent of [untracked cache](https://git-scm.com/docs/git-update-index#_untracked_cache) from +git. On the first scan of the workdir gitstatusd lists all files just like libgit2. But, unlike +libgit2, it remembers the last modification time of every directory along with the list of +untracked files under it. On the next scan, gitstatusd can skip listing files in directories whose +last modification time hasn't changed. + +To summarize, here's what gitstatusd was doing when the CPU profile was captured: + +1. `__libc_openat64`: Open every directory for which there are files in the index. +2. `__GI___fxstat`: Check last modification time of the directory. Since it's the same as on the + last scan, this directory has the same list of untracked files as before, which is empty (the + repository is clean). +3. `__GI___fxstatat`: Check last modification time for every file in the index that belongs to this + directory. +4. `__libc_close`: Close the file descriptor to the directory. + +Here's how the very first scan of a repository looks like in gitstatusd: + +![gitstatusd CPU profile (cold)]( + https://raw.githubusercontent.com/romkatv/gitstatus/1ac366952366d89980b3f3484f270b4fa5ae4293/cpu-profile-gitstatusd-cold.png) + +(Some glibc functions are mislabel on this profile. `explicit_bzero` and `__nss_passwd_lookup` are +in reality `strcmp` and `memcmp`.) + +This is a superset of the previous -- hot -- profile, with an extra `syscall` and string sorting for +directory listing. gitstatusd uses `getdents64` Linux system call directly, bypassing the glibc +wrapper that libgit2 uses. This is 23% faster. The details of this optimization can be found in a +[separate document](docs/listdir.md). + +### Multithreading + +The diffing algorithm in gitstatusd was designed from the ground up with the intention of using it +concurrently from multiple threads. With a fast SSD, `status` is CPU bound, so taking advantage of +all available CPU cores is an obvious way to yield results faster. + +gitstatusd exhibits almost perfect scaling from multithreading. Engaging all cores allows it to +produce results 12.4 times faster than in single-threaded execution. This is on Intel i9-7900X with +10 cores (20 with hyperthreading) with single-core frequency of 4.3GHz and all-core frequency of +4.0GHz. + +Note: `git status` also uses all available cores in some parts of its algorithm while `lg2` does +everything in a single thread. + +### Postprocessing + +Once the difference between the index and the workdir is found, we have a list of _candidates_ -- +files that may be unstaged or untracked. To make the final judgement, these files need to be checked +against `.gitignore` rules and a few other things. + +gitstatusd uses [patched libgit2](https://github.com/romkatv/libgit2) for this step. This fork +adds several optimizations that make libgit2 faster. The patched libgit2 performs more than twice +as fast in the benchmark as the original even without changes in the user code (that is, in the +code that uses the libgit2 APIs). The fork also adds several API extensions, most notable of which +is the support for multi-threaded scans. If `lg2 status` is modified to take advantage of these +extensions, it outperforms the original libgit2 by a factor of 18. Lastly, the fork fixes a score of +bugs, most of which become apparent only when using libgit2 from multiple threads. + +_WARNING: Changes to libgit2 are extensive but the testing they underwent isn't. It is +**not recommended** to use the patched libgit2 in production._ + +## Requirements + +* To compile: binutils, cmake, gcc, g++, git and GNU make. +* To run: Linux, macOS, FreeBSD, Android, WSL, Cygwin or MSYS2. + +## Compiling + +There are prebuilt `gitstatusd` binaries in [releases]( + https://github.com/romkatv/gitstatus/releases). When using the official shell bindings +provided by gitstatus, the right binary for your architecture gets downloaded automatically. + +If prebuilt binaries don't work for you, you'll need to get your hands dirty. + +### Compiling for personal use + +```zsh +git clone --depth=1 https://github.com/romkatv/gitstatus.git +cd gitstatus +./build -w -s -d docker +``` + +Users in China can use the official mirror on gitee.com for faster download.
+中国大陆用户可以使用 gitee.com 上的官方镜像加速下载. + +```zsh +git clone --depth=1 https://gitee.com/romkatv/gitstatus.git +cd gitstatus +./build -w -s -d docker +``` + +- If it says that `-d docker` is not supported on your OS, remove this flag. +- If it says that `-s` is not supported on your OS, remove this flag. +- If it tell you to install docker but you cannot or don't want to, remove `-d docker`. +- If it says that some command is missing, install it. + +If everything goes well, the newly built binary will appear in `./usrbin`. It'll be picked up +by shell bindings automatically. + +When you update shell bindings, they may refuse to work with the binary you've built earlier. In +this case you'll need to rebuild. + +If you are using gitstatus through [Powerlevel10k](https://github.com/romkatv/powerlevel10k), the +instructions are the same except that you don't need to clone gitstatus. Instead, change your +current directory to `/path/to/powerlevel10k/gitstatus` (`/path/to/powerlevel10k` is the directory +where you've installed Powerlevel10k) and run `./build -w -s -d docker` from there as described +above. + +### Compiling for distribution + +It's currently neither easy nor recommended to package and distribute gitstatus. There are no +instructions you can follow that would allow you to easily update your package when new versions of +gitstatus are released. This may change in the future but not soon. + +## License + +GNU General Public License v3.0. See [LICENSE](LICENSE). Contributions are covered by the same +license. diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/build b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/build new file mode 100755 index 00000000..e116abb2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/build @@ -0,0 +1,656 @@ +#!/bin/sh +# +# Type `build -h` for help and see https://github.com/romkatv/gitstatus +# for full documentation. + +set -ue + +if [ -n "${ZSH_VERSION:-}" ]; then + emulate sh -o err_exit -o no_unset +fi + +export LC_ALL=C + +if [ -z "${ZSH_VERSION-}" ] && command -v zsh >/dev/null 2>&1; then + # Avoid bash 3.*. + case "${BASH_VERSION-}" in + [0-3].*) exec zsh "$0" "$@";; + esac +fi + +# Avoid ksh: https://github.com/romkatv/gitstatus/issues/282. +if [ -n "${KSH_VERSION-}" ]; then + if [ -z "${ZSH_VERSION-}" ] && command -v zsh >/dev/null 2>&1; then + exec zsh "$0" "$@" + elif [ -z "${BASH_VERSION-}" ] && command -v bash >/dev/null 2>&1 && + bash_version="$(bash --version 2>&1)"; then + case "$bash_version" in + *version\ [4-9]*|*version\ [1-9][0-9]*) exec bash "$0" "$@";; + esac + fi +fi + +usage="$(command cat <<\END +Usage: build [-m ARCH] [-c CPU] [-d CMD] [-i IMAGE] [-s] [-w] + +Options: + + -m ARCH `uname -m` from the target machine; defaults to `uname -m` + from the local machine + -c CPU generate machine instructions for CPU of this type; this + value gets passed as `-march` (or `-mcpu` for ppc64le) to gcc; + inferred from ARCH if not set explicitly + -d CMD build in a Docker container and use CMD as the `docker` + command; e.g., `-d docker` or `-d podman` + -i IMAGE build in this Docker image; inferred from ARCH if not set + explicitly + -s install whatever software is necessary for build to + succeed; on some operating systems this option is not + supported; on others it can have partial effect + -w automatically download tarballs for dependencies if they + do not already exist in ./deps; dependencies are described + in ./build.info +END +)" + +build="$(command cat <<\END +outdir="$(command pwd)" + +if command -v mktemp >/dev/null 2>&1; then + workdir="$(command mktemp -d "${TMPDIR:-/tmp}"/gitstatus-build.XXXXXXXXXX)" +else + workdir="${TMPDIR:-/tmp}/gitstatus-build.tmp.$$" + command mkdir -- "$workdir" +fi + +cd -- "$workdir" +workdir="$(command pwd)" + +narg() { echo $#; } + +if [ "$(narg $workdir)" != 1 -o -z "${workdir##*:*}" -o -z "${workdir##*=*}" ]; then + >&2 echo "[error] cannot build in this directory: $workdir" + exit 1 +fi + +appname=gitstatusd +libgit2_tmp="$outdir"/deps/"$appname".libgit2.tmp + +cleanup() { + trap - INT QUIT TERM ILL PIPE + cd / + if ! command rm -rf -- "$workdir" "$outdir"/usrbin/"$appname".tmp "$libgit2_tmp"; then + command sleep 5 + command rm -rf -- "$workdir" "$outdir"/usrbin/"$appname".tmp "$libgit2_tmp" + fi +} +trap cleanup INT QUIT TERM ILL PIPE + +if [ -n "$gitstatus_install_tools" ]; then + case "$gitstatus_kernel" in + linux) + if command -v apk >/dev/null 2>&1; then + command apk update + command apk add binutils cmake gcc g++ git make musl-dev perl-utils + elif command -v apt-get >/dev/null 2>&1; then + apt-get update + apt-get install -y binutils cmake gcc g++ make wget + else + >&2 echo "[error] -s is not supported on this system" + exit 1 + fi + ;; + freebsd|dragonfly) + command pkg install -y cmake gmake binutils git perl5 wget + ;; + openbsd) + command pkg_add cmake gmake gcc g++ git wget + ;; + netbsd) + command pkgin -y install cmake gmake binutils git + ;; + darwin) + if ! command -v make >/dev/null 2>&1 || ! command -v gcc >/dev/null 2>&1; then + >&2 echo "[error] please run 'xcode-select --install' and retry" + exit 1 + fi + if command -v port >/dev/null 2>&1; then + sudo port -N install libiconv cmake wget + elif command -v brew >/dev/null 2>&1; then + for formula in libiconv cmake git wget; do + if command brew ls --version "$formula" &>/dev/null; then + command brew upgrade "$formula" + else + command brew install "$formula" + fi + done + else + >&2 echo "[error] please install MacPorts or Homebrew and retry" + exit 1 + fi + ;; + msys*|mingw*) + command pacman -Syu --noconfirm + command pacman -S --needed --noconfirm binutils cmake gcc git make perl + ;; + *) + >&2 echo "[internal error] unhandled kernel: $gitstatus_kernel" + exit 1 + ;; + esac +fi + +cpus="$(command getconf _NPROCESSORS_ONLN 2>/dev/null)" || + cpus="$(command sysctl -n hw.ncpu 2>/dev/null)" || + cpus=8 + +case "$gitstatus_cpu" in + powerpc64|powerpc64le) + archflag="-mcpu" + ;; + *) + archflag="-march" + ;; +esac + +cflags="$archflag=$gitstatus_cpu -fno-plt -D_FORTIFY_SOURCE=2 -Wformat -Werror=format-security -fpie" +ldflags= +static_pie= + +if [ -z "${CC-}" ]; then + case "$gitstatus_kernel" in + freebsd) export CC=clang;; + *) export CC=cc;; + esac +fi + +printf 'int main() {}\n' >"$workdir"/cc-test.c +if 2>/dev/null "$CC" \ + -ffile-prefix-map=x=y \ + -Werror \ + -c "$workdir"/cc-test.c \ + -o "$workdir"/cc-test.o; then + cflags="$cflags -ffile-prefix-map=$workdir/=" +fi + +command rm -f -- "$workdir"/cc-test "$workdir"/cc-test.o +if 2>/dev/null "$CC" \ + -fstack-clash-protection \ + -Werror \ + -c "$workdir"/cc-test.c \ + -o "$workdir"/cc-test.o; then + cflags="$cflags -fstack-clash-protection" +fi + +command rm -f -- "$workdir"/cc-test "$workdir"/cc-test.o +if 2>/dev/null "$CC" \ + -fcf-protection \ + -Werror \ + -c "$workdir"/cc-test.c \ + -o "$workdir"/cc-test.o; then + cflags="$cflags -fcf-protection" +fi + +command rm -f -- "$workdir"/cc-test "$workdir"/cc-test.o +if 2>/dev/null "$CC" \ + -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now \ + -Werror \ + "$workdir"/cc-test.c \ + -o "$workdir"/cc-test; then + ldflags="$ldflags -Wl,-O1,--sort-common,--as-needed,-z,relro,-z,now" +fi + +command rm -f -- "$workdir"/cc-test "$workdir"/cc-test.o +if 2>/dev/null "$CC" \ + -fpie -static-pie \ + -Werror \ + "$workdir"/cc-test.c \ + -o "$workdir"/cc-test; then + static_pie='-static-pie' +fi + +if [ "$gitstatus_cpu" = x86-64 ]; then + cflags="$cflags -mtune=generic" +fi + +libgit2_cmake_flags= +libgit2_cflags="${CFLAGS-} $cflags -O3 -DNDEBUG" + +gitstatus_cxx=g++ +gitstatus_cxxflags="${CXXFLAGS-} $cflags -I${workdir}/libgit2/include -DGITSTATUS_ZERO_NSEC -D_GNU_SOURCE -D_GLIBCXX_ASSERTIONS" +gitstatus_ldflags="${LDFLAGS-} $ldflags -L${workdir}/libgit2/build" +gitstatus_ldlibs= +gitstatus_make=make + +case "$gitstatus_kernel" in + linux) + gitstatus_ldflags="$gitstatus_ldflags ${static_pie:--static}" + libgit2_cmake_flags="$libgit2_cmake_flags -DENABLE_REPRODUCIBLE_BUILDS=ON" + ;; + freebsd) + gitstatus_cxx=clang++ + gitstatus_make=gmake + gitstatus_ldflags="$gitstatus_ldflags ${static_pie:--static}" + libgit2_cmake_flags="$libgit2_cmake_flags -DENABLE_REPRODUCIBLE_BUILDS=ON" + ;; + dragonfly) + gitstatus_cxx=clang++12 + gitstatus_make=gmake + gitstatus_ldflags="$gitstatus_ldflags ${static_pie:--static}" + libgit2_cmake_flags="$libgit2_cmake_flags -DENABLE_REPRODUCIBLE_BUILDS=ON" + ;; + openbsd) + gitstatus_cxx=eg++ + gitstatus_make=gmake + gitstatus_ldflags="$gitstatus_ldflags ${static_pie:--static}" + libgit2_cmake_flags="$libgit2_cmake_flags -DENABLE_REPRODUCIBLE_BUILDS=ON" + ;; + netbsd) + gitstatus_make=gmake + gitstatus_ldflags="$gitstatus_ldflags ${static_pie:--static}" + libgit2_cmake_flags="$libgit2_cmake_flags -DENABLE_REPRODUCIBLE_BUILDS=ON" + ;; + darwin) + command mkdir -- "$workdir"/lib + if [ -e /opt/local/lib/libiconv.a ]; then + command ln -s -- /opt/local/lib/libiconv.a "$workdir"/lib + libgit2_cflags="$libgit2_cflags -I/opt/local/include" + gitstatus_cxxflags="$gitstatus_cxxflags -I/opt/local/include" + else + brew_prefix="$(command brew --prefix)" + command ln -s -- "$brew_prefix"/opt/libiconv/lib/libiconv.a "$workdir"/lib + libgit2_cflags="$libgit2_cflags -I"$brew_prefix"/opt/libiconv/include" + gitstatus_cxxflags="$gitstatus_cxxflags -I"$brew_prefix"/opt/libiconv/include" + fi + libgit2_cmake_flags="$libgit2_cmake_flags -DUSE_ICONV=ON" + gitstatus_ldlibs="$gitstatus_ldlibs -liconv" + gitstatus_ldflags="$gitstatus_ldflags -L${workdir}/lib" + libgit2_cmake_flags="$libgit2_cmake_flags -DENABLE_REPRODUCIBLE_BUILDS=OFF" + ;; + msys*|mingw*) + gitstatus_ldflags="$gitstatus_ldflags ${static_pie:--static}" + libgit2_cmake_flags="$libgit2_cmake_flags -DENABLE_REPRODUCIBLE_BUILDS=ON" + ;; + cygwin*) + gitstatus_ldflags="$gitstatus_ldflags ${static_pie:--static}" + libgit2_cmake_flags="$libgit2_cmake_flags -DENABLE_REPRODUCIBLE_BUILDS=ON" + ;; + *) + >&2 echo "[internal error] unhandled kernel: $gitstatus_kernel" + exit 1 + ;; +esac + +for cmd in cat cmake git ld ln mkdir rm strip tar "$gitstatus_make"; do + if ! command -v "$cmd" >/dev/null 2>&1; then + if [ -n "$gitstatus_install_tools" ]; then + >&2 echo "[internal error] $cmd not found" + exit 1 + else + >&2 echo "[error] command not found: $cmd" + exit 1 + fi + fi +done + +. "$outdir"/build.info +if [ -z "${libgit2_version:-}" ]; then + >&2 echo "[internal error] libgit2_version not set" + exit 1 +fi +if [ -z "${libgit2_sha256:-}" ]; then + >&2 echo "[internal error] libgit2_sha256 not set" + exit 1 +fi +libgit2_tarball="$outdir"/deps/libgit2-"$libgit2_version".tar.gz +if [ ! -e "$libgit2_tarball" ]; then + if [ -n "$gitstatus_download_deps" ]; then + if ! command -v wget >/dev/null 2>&1; then + if [ -n "$gitstatus_install_tools" ]; then + >&2 echo "[internal error] wget not found" + exit 1 + else + >&2 echo "[error] command not found: wget" + exit 1 + fi + fi + libgit2_url=https://github.com/romkatv/libgit2/archive/"$libgit2_version".tar.gz + if ! >"$libgit2_tmp" command wget --no-config -qO- -- "$libgit2_url" && + ! >"$libgit2_tmp" command wget -qO- -- "$libgit2_url"; then + set -x + >&2 command which wget + >&2 command ls -lAd -- "$(command which wget)" + >&2 command ls -lAd -- "$outdir" + >&2 command ls -lA -- "$outdir" + >&2 command ls -lAd -- "$outdir"/deps + >&2 command ls -lA -- "$outdir"/deps + set +x + exit 1 + fi + command mv -f -- "$libgit2_tmp" "$libgit2_tarball" + else + >&2 echo "[error] file not found: deps/libgit2-"$libgit2_version".tar.gz" + exit 1 + fi +fi + +libgit2_actual_sha256= +if command -v shasum >/dev/null 2>/dev/null; then + libgit2_actual_sha256="$(command shasum -b -a 256 -- "$libgit2_tarball")" + libgit2_actual_sha256="${libgit2_actual_sha256%% *}" +elif command -v sha256sum >/dev/null 2>/dev/null; then + libgit2_actual_sha256="$(command sha256sum -b -- "$libgit2_tarball")" + libgit2_actual_sha256="${libgit2_actual_sha256%% *}" +elif command -v sha256 >/dev/null 2>/dev/null; then + libgit2_actual_sha256="$(command sha256 -- "$libgit2_tarball" &2 echo "[error] command not found: shasum or sha256sum" + exit 1 +fi + +if [ "$libgit2_actual_sha256" != "$libgit2_sha256" ]; then + >&2 echo "[error] sha256 mismatch" + >&2 echo "" + >&2 echo " file : deps/libgit2-$libgit2_version.tar.gz" + >&2 echo " expected: $libgit2_sha256" + >&2 echo " actual : $libgit2_actual_sha256" + exit 1 +fi + +cd -- "$workdir" +command tar -xzf "$libgit2_tarball" +command mv -- libgit2-"$libgit2_version" libgit2 +command mkdir libgit2/build +cd libgit2/build + +CFLAGS="$libgit2_cflags" command cmake \ + -DCMAKE_BUILD_TYPE=None \ + -DZERO_NSEC=ON \ + -DTHREADSAFE=ON \ + -DUSE_BUNDLED_ZLIB=ON \ + -DREGEX_BACKEND=builtin \ + -DUSE_HTTP_PARSER=builtin \ + -DUSE_SSH=OFF \ + -DUSE_HTTPS=OFF \ + -DBUILD_CLAR=OFF \ + -DUSE_GSSAPI=OFF \ + -DUSE_NTLMCLIENT=OFF \ + -DBUILD_SHARED_LIBS=OFF \ + $libgit2_cmake_flags \ + .. +command make -j "$cpus" VERBOSE=1 + +APPNAME="$appname".tmp \ + OBJDIR="$workdir"/gitstatus \ + CXX="${CXX:-$gitstatus_cxx}" \ + CXXFLAGS="$gitstatus_cxxflags" \ + LDFLAGS="$gitstatus_ldflags" \ + LDLIBS="$gitstatus_ldlibs" \ + command "$gitstatus_make" -C "$outdir" -j "$cpus" + +app="$outdir"/usrbin/"$appname" + +command strip "$app".tmp + +command mkdir -- "$workdir"/repo +printf '[init]\n defaultBranch = master\n' >"$workdir"/.gitconfig +( + cd -- "$workdir"/repo + GIT_CONFIG_NOSYSTEM=1 HOME="$workdir" command git init + GIT_CONFIG_NOSYSTEM=1 HOME="$workdir" command git config user.name "Your Name" + GIT_CONFIG_NOSYSTEM=1 HOME="$workdir" command git config user.email "you@example.com" + GIT_CONFIG_NOSYSTEM=1 HOME="$workdir" command git commit \ + --allow-empty --allow-empty-message --no-gpg-sign -m '' +) + +resp="$(printf "hello\037$workdir/repo\036" | "$app".tmp)" +case "$resp" in + hello*1*/repo*master*);; + *) + >&2 echo 'error: invalid gitstatusd response for a git repo' + exit 1 + ;; +esac + +resp="$(printf 'hello\037\036' | "$app".tmp)" +case "$resp" in + hello*0*);; + *) + >&2 echo 'error: invalid gitstatusd response for a non-repo' + exit 1 + ;; +esac + +command mv -f -- "$app".tmp "$app" + +cleanup + +command cat >&2 <<-END + ------------------------------------------------- + SUCCESS: created usrbin/$appname + END +END +)" + +docker_image= +docker_cmd= + +gitstatus_arch= +gitstatus_cpu= +gitstatus_install_tools= +gitstatus_download_deps= + +while getopts ':m:c:i:d:swh' opt "$@"; do + case "$opt" in + h) + printf '%s\n' "$usage" + exit + ;; + m) + if [ -n "$gitstatus_arch" ]; then + >&2 echo "[error] duplicate option: -$opt" + exit 1 + fi + if [ -z "$OPTARG" ]; then + >&2 echo "[error] incorrect value of -$opt: $OPTARG" + exit 1 + fi + gitstatus_arch="$OPTARG" + ;; + c) + if [ -n "$gitstatus_cpu" ]; then + >&2 echo "[error] duplicate option: -$opt" + exit 1 + fi + if [ -z "$OPTARG" ]; then + >&2 echo "[error] incorrect value of -$opt: $OPTARG" + exit 1 + fi + gitstatus_cpu="$OPTARG" + ;; + i) + if [ -n "$docker_image" ]; then + >&2 echo "[error] duplicate option: -$opt" + exit 1 + fi + if [ -z "$OPTARG" ]; then + >&2 echo "[error] incorrect value of -$opt: $OPTARG" + exit 1 + fi + docker_image="$OPTARG" + ;; + d) + if [ -n "$docker_cmd" ]; then + >&2 echo "[error] duplicate option: -$opt" + exit 1 + fi + if [ -z "$OPTARG" ]; then + >&2 echo "[error] incorrect value of -$opt: $OPTARG" + exit 1 + fi + docker_cmd="$OPTARG" + ;; + s) + if [ -n "$gitstatus_install_tools" ]; then + >&2 echo "[error] duplicate option: -$opt" + exit 1 + fi + gitstatus_install_tools=1 + ;; + w) + if [ -n "$gitstatus_download_deps" ]; then + >&2 echo "[error] duplicate option: -$opt" + exit 1 + fi + gitstatus_download_deps=1 + ;; + \?) >&2 echo "[error] invalid option: -$OPTARG" ; exit 1;; + :) >&2 echo "[error] missing required argument: -$OPTARG"; exit 1;; + *) >&2 echo "[internal error] unhandled option: -$opt" ; exit 1;; + esac +done + +if [ "$OPTIND" -le $# ]; then + >&2 echo "[error] unexpected positional argument" + exit 1 +fi + +if [ -n "$docker_image" -a -z "$docker_cmd" ]; then + >&2 echo "[error] cannot use -i without -d" + exit 1 +fi + +if [ -z "$gitstatus_arch" ]; then + gitstatus_arch="$(uname -m)" + gitstatus_arch="$(printf '%s' "$gitstatus_arch" | tr '[A-Z]' '[a-z]')" +fi + +if [ -z "$gitstatus_cpu" ]; then + case "$gitstatus_arch" in + armel) gitstatus_cpu=armv5;; + armv6l|armhf) gitstatus_cpu=armv6;; + armv7l) gitstatus_cpu=armv7;; + arm64|aarch64) gitstatus_cpu=armv8-a;; + ppc64|ppc64le) gitstatus_cpu=powerpc64le;; + riscv64) gitstatus_cpu=rv64imafdc;; + loongarch64) gitstatus_cpu=loongarch64;; + x86_64|amd64) gitstatus_cpu=x86-64;; + x86) gitstatus_cpu=i586;; + s390x) gitstatus_cpu=z900;; + i386|i586|i686) gitstatus_cpu="$gitstatus_arch";; + *) + >&2 echo '[error] unable to infer target CPU architecture' + >&2 echo 'Please specify explicitly with `-c CPU`.' + exit 1 + ;; + esac +fi + +gitstatus_kernel="$(uname -s)" +gitstatus_kernel="$(printf '%s' "$gitstatus_kernel" | tr '[A-Z]' '[a-z]')" + +case "$gitstatus_kernel" in + linux) + if [ -n "$docker_cmd" ]; then + if [ -z "${docker_cmd##*/*}" ]; then + if [ ! -x "$docker_cmd" ]; then + >&2 echo "[error] not an executable file: $docker_cmd" + exit 1 + fi + else + if ! command -v "$docker_cmd" >/dev/null 2>&1; then + >&2 echo "[error] command not found: $docker_cmd" + exit 1 + fi + fi + if [ -z "$docker_image" ]; then + case "$gitstatus_arch" in + x86_64) docker_image=alpine:3.11.6;; + x86|i386|i586|i686) docker_image=i386/alpine:3.11.6;; + armv6l|armhf) docker_image=arm32v6/alpine:3.11.6;; + armv7l) docker_image=arm32v7/alpine:3.11.6;; + aarch64) docker_image=arm64v8/alpine:3.11.6;; + ppc64|ppc64le) docker_image=ppc64le/alpine:3.11.6;; + s390x) docker_image=s390x/alpine:3.11.6;; + *) + >&2 echo '[error] unable to infer docker image' + >&2 echo 'Please specify explicitly with `-i IMAGE`.' + exit 1 + ;; + esac + fi + fi + ;; + freebsd|openbsd|netbsd|darwin|dragonfly) + if [ -n "$docker_cmd" ]; then + >&2 echo "[error] docker (-d) is not supported on $gitstatus_kernel" + exit 1 + fi + ;; + msys_nt-*|mingw32_nt-*|mingw64_nt-*|cygwin_nt-*) + if ! printf '%s' "$gitstatus_kernel" | grep -Eqx '[^-]+-[0-9]+\.[0-9]+(-.*)?'; then + >&2 echo '[error] unsupported kernel, sorry!' + exit 1 + fi + gitstatus_kernel="$(printf '%s' "$gitstatus_kernel" | sed 's/^\([^-]*-[0-9]*\.[0-9]*\).*/\1/')" + if [ -n "$docker_cmd" ]; then + >&2 echo '[error] docker (-d) is not supported on windows' + exit 1 + fi + if [ -n "$gitstatus_install_tools" -a -z "${gitstatus_kernel##cygwin_nt-*}" ]; then + >&2 echo '[error] -s is not supported on cygwin' + exit 1 + fi + ;; + *) + >&2 echo '[error] unsupported kernel, sorry!' + exit 1 + ;; +esac + +dir="$(dirname -- "$0")" +cd -- "$dir" +dir="$(pwd)" + +>&2 echo "Building gitstatusd..." +>&2 echo "" +>&2 echo " kernel := $gitstatus_kernel" +>&2 echo " arch := $gitstatus_arch" +>&2 echo " cpu := $gitstatus_cpu" +[ -z "$docker_cmd" ] || >&2 echo " docker command := $docker_cmd" +[ -z "$docker_image" ] || >&2 echo " docker image := $docker_image" +if [ -n "$gitstatus_install_tools" ]; then + >&2 echo " install tools := yes" +else + >&2 echo " install tools := no" +fi +if [ -n "$gitstatus_download_deps" ]; then + >&2 echo " download deps := yes" +else + >&2 echo " download deps := no" +fi + +if [ -n "$docker_cmd" ]; then + "$docker_cmd" run \ + -e docker_cmd="$docker_cmd" \ + -e docker_image="$docker_image" \ + -e gitstatus_kernel="$gitstatus_kernel" \ + -e gitstatus_arch="$gitstatus_arch" \ + -e gitstatus_cpu="$gitstatus_cpu" \ + -e gitstatus_install_tools="$gitstatus_install_tools" \ + -e gitstatus_download_deps="$gitstatus_download_deps" \ + -v "$dir":/out \ + -w /out \ + --rm \ + -- "$docker_image" /bin/sh -uexc "$build" +else + eval "$build" +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/build.info b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/build.info new file mode 100644 index 00000000..baa30b07 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/build.info @@ -0,0 +1,22 @@ +# This value gets embedded in gitstatusd at build time. It is +# read by ./Makefile. `gitstatusd --version` reports it back. +# +# This value is also read by shell bindings (indirectly, through +# ./install) when using GITSTATUS_DAEMON or usrbin/gitstatusd. +gitstatus_version="v1.5.4" + +# libgit2 is a build time dependency of gitstatusd. The values of +# libgit2_version and libgit2_sha256 are read by ./build. +# +# If ./deps/libgit2-${libgit2_version}.tar.gz doesn't exist, build +# downloads it from the following location: +# +# https://github.com/romkatv/libgit2/archive/${libgit2_version}.tar.gz +# +# Once downloaded, the tarball is stored at the path indicated +# above so that repeated builds don't consume network bandwidth. +# +# If sha256 of ./deps/libgit2-${libgit2_version}.tar.gz doesn't match, +# build gets aborted. +libgit2_version="tag-0ad3d776aa86dd607dc86dcd7f77ad3ed7ebec61" +libgit2_sha256="c5d0117ae74d3ef244c26f10cce022019077dbc4563e6251fa9f56d36868ce74" diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/deps/.gitkeep b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/deps/.gitkeep new file mode 100644 index 00000000..e69de29b diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/docs/listdir.md b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/docs/listdir.md new file mode 100644 index 00000000..0939cc18 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/docs/listdir.md @@ -0,0 +1,330 @@ +# Fast directory listing + +In order to find untracked files in a git repository, [gitstatusd](../README.md) needs to list the +contents of every directory. gitstatusd does it 27% faster than a reasonable implementation that a +seasoned C/C++ practitioner might write. This document explains the optimizations that went into it. +As directory listing is a common operation, many other projects can benefit from applying these +optimizations. + +## v1 + +Given a path to a directory, `ListDir()` must produce the list of files in that directory. Moreover, +the list must be sorted lexicographically to enable fast comparison with Git index. + +The following C++ implementation gets the job done. For simplicity, it returns an empty list on +error. + +```c++ +vector ListDir(const char* dirname) { + vector entries; + if (DIR* dir = opendir(dirname)) { + while (struct dirent* ent = (errno = 0, readdir(dir))) { + if (!Dots(ent->d_name)) entries.push_back(ent->d_name); + } + if (errno) entries.clear(); + sort(entries.begin(), entries.end()); + closedir(dir); + } + return entries; +} +``` + +Every directory has entries `"."` and `".."`, which we aren't interested in. We filter them out with +a helper function `Dots()`. + +```c++ +bool Dots(const char* s) { return s[0] == '.' && (!s[1] || (s[1] == '.' && !s[2])); } +``` + +To check how fast `ListDir()` performs, we can run it many times on a typical directory. One million +runs on a directory with 32 files with 16-character names takes 12.7 seconds. + +## v2 + +Experienced C++ practitioners will scoff at our implementation of `ListDir()`. If it's meant to be +efficient, returning `vector` is an unaffordable convenience. To avoid heap allocations we +can use a simple arena that will allow us to reuse memory between different `ListDir()` calls. + +(Changed and added lines are marked with comments.) + +```c++ +void ListDir(const char* dirname, string& arena, vector& entries) { // + + entries.clear(); // + + if (DIR* dir = opendir(dirname)) { + arena.clear(); // + + while (struct dirent* ent = (errno = 0, readdir(dir))) { + if (!Dots(ent->d_name)) { + entries.push_back(reinterpret_cast(arena.size())); // + + arena.append(ent->d_name, strlen(ent->d_name) + 1); // + + } + } + if (errno) entries.clear(); + for (char*& p : entries) p = &arena[reinterpret_cast(p)]; // + + sort(entries.begin(), entries.end(), // + + [](const char* a, const char* b) { return strcmp(a, b) < 0; }); // + + closedir(dir); + } +} +``` + +To make performance comparison easier, we can normalize them relative to the baseline. v1 will get +performance score of 100. A twice-as-fast alternative will be 200. + +| version | optimization | score | +|---------|----------------------------|----------:| +| v1 | baseline | 100.0 | +| **v2** | **avoid heap allocations** | **112.7** | + +Avoiding heap allocations makes `ListDir()` 12.7% faster. Not bad. As an added bonus, those casts +will fend off the occasional frontend developer who accidentally wanders into the codebase. + +## v3 + +`opendir()` is an expensive call whose performance is linear in the number of subdirectories in the +path because it needs to perform a lookup for every one of them. We can replace it with `openat()`, +which takes a file descriptor to the parent directory and a name of the subdirectory. Just a single +lookup, less CPU time. This optimization assumes that callers already have a descriptor to the +parent directory, which is indeed the case for gitstatusd, and is often the case in other +applications that traverse filesystem. + +```c++ +void ListDir(int parent_fd, const char* dirname, string& arena, vector& entries) { // + + entries.clear(); + int dir_fd = openat(parent_fd, dirname, O_NOATIME | O_RDONLY | O_DIRECTORY | O_CLOEXEC); // + + if (dir_fd < 0) return; // + + if (DIR* dir = fdopendir(dir_fd)) { + arena.clear(); + while (struct dirent* ent = (errno = 0, readdir(dir))) { + if (!Dots(ent->d_name)) { + entries.push_back(reinterpret_cast(arena.size())); + arena.append(ent->d_name, strlen(ent->d_name) + 1); + } + } + if (errno) entries.clear(); + for (char*& p : entries) p = &arena[reinterpret_cast(p)]; + sort(entries.begin(), entries.end(), + [](const char* a, const char* b) { return strcmp(a, b) < 0; }); + closedir(dir); + } else { // + + close(dir_fd); // + + } // + +} +``` + +This is worth about 3.5% in speed. + +| version | optimization | score | +|---------|--------------------------------------|----------:| +| v1 | baseline | 100.0 | +| v2 | avoid heap allocations | 112.7 | +| **v3** | **open directories with `openat()`** | **116.2** | + +## v4 + +Copying file names to the arena isn't free but it doesn't seem like we can avoid it. Poking around +we can see that the POSIX API we are using is implemented on Linux on top of `getdents64` system +call. Its documentation isn't very encouraging: + +```text +These are not the interfaces you are interested in. Look at +readdir(3) for the POSIX-conforming C library interface. This page +documents the bare kernel system call interfaces. + +Note: There are no glibc wrappers for these system calls. +``` + +Hmm... The API looks like something we can take advantage of, so let's try it anyway. + +First, we'll need a simple `Arena` class that can allocate 8KB blocks of memory. + +```c++ +class Arena { + public: + enum { kBlockSize = 8 << 10 }; + + char* Alloc() { + if (cur_ == blocks_.size()) blocks_.emplace_back(kBlockSize, 0); + return blocks_[cur_++].data(); + } + + void Clear() { cur_ = 0; } + + private: + size_t cur_ = 0; + vector blocks_; +}; +``` + +Next, we need to define `struct dirent64_t` ourselves because there is no wrapper for the system +call we are about to use. + +```c++ +struct dirent64_t { + ino64_t d_ino; + off64_t d_off; + unsigned short d_reclen; + unsigned char d_type; + char d_name[]; +}; +``` + +Finally we can get to the implementation of `ListDir()`. + +```c++ +void ListDir(int parent_fd, Arena& arena, vector& entries) { // + + entries.clear(); + int dir_fd = openat(parent_fd, dirname, O_NOATIME | O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir_fd < 0) return; + arena.Clear(); // + + while (true) { // + + char* buf = arena.Alloc(); // + + int n = syscall(SYS_getdents64, dir_fd, buf, Arena::kBlockSize); // + + if (n <= 0) { // + + if (n) entries.clear(); // + + break; // + + } // + + for (int pos = 0; pos < n;) { // + + auto* ent = reinterpret_cast(buf + pos); // + + if (!Dots(ent->d_name)) entries.push_back(ent->d_name); // + + pos += ent->d_reclen; // + + } // + + } // + + sort(entries.begin(), entries.end(), + [](const char* a, const char* b) { return strcmp(a, b) < 0; }); + close(dir_fd); +} +``` + +How are we doing with this one? + +| version | optimization | score | +|---------|----------------------------------|----------:| +| v1 | baseline | 100.0 | +| v2 | avoid heap allocations | 112.7 | +| v3 | open directories with `openat()` | 116.2 | +| **v4** | **call `getdents64()` directly** | **137.8** | + +Solid 20% speedup. Worth the trouble. Unfortunately, we now have just one `reinterpret_cast` instead +of two, and it's not nearly as scary-looking. Hopefully with the next iteration we can get back some +of that evil vibe of low-level code. + +As a bonus, every element in `entries` has `d_type` at offset -1. This can be useful to the callers +that need to distinguish between regular files and directories (gitstatusd, in fact, needs this). +Note how `ListDir()` implements this feature at zero cost, as a lucky accident of `dirent64_t` +memory layout. + +## v5 + +The CPU profile of `ListDir()` reveals that almost all userspace CPU time is spent in `strcmp()`. +Digging into the source code of `std::sort()` we can see that it uses Insertion Sort for short +collections. Our 32-element vector falls under the threshold. Insertion Sort makes `O(N^2)` +comparisons, hence a lot of CPU time in `strcmp()`. Switching to `qsort()` or +[Timsort](https://en.wikipedia.org/wiki/Timsort) is of no use as all good sorting algorithms fall +back to Insertion Sort. + +If we cannot make fewer comparisons, perhaps we can make each of them faster? `strcmp()` compares +characters one at a time. It cannot read ahead as it can be illegal to touch memory past the first +null byte. But _we_ know that it's safe to read a few extra bytes past the end of `d_name` for every +entry except the last in the buffer. And since we own the buffer, we can overallocate it so that +reading past the end of the last entry is also safe. + +Combining these ideas with the fact that file names on Linux are at most 255 bytes long, we can +invoke `getdents64()` like this: + +```c++ +int n = syscall(SYS_getdents64, dir_fd, buf, Arena::kBlockSize - 256); +``` + +And then compare entries like this: + +```c++ +[](const char* a, const char* b) { return memcmp(a, b, 255) < 0; } +``` + +This version doesn't give any speedup compared to the previous but it opens an avenue for another +optimization. The pointers we pass to `memcmp()` aren't aligned. To be more specific, their +numerical values are `N * 8 + 3` for some `N`. When given such a pointer, `memcmp()` will check the +first 5 bytes one by one, and only then switch to comparing 8 bytes at a time. If we can handle the +first 5 bytes ourselves, we can pass aligned memory to `memcmp()` and take full advantage of its +vectorized loop. + +Here's the implementation: + +```c++ +uint64_t Read64(const void* p) { // + + uint64_t x; // + + memcpy(&x, p, sizeof(x)); // + + return x; // + +} // + + +void ByteSwap64(void* p) { // + + uint64_t x = __builtin_bswap64(Read64(p)); // + + memcpy(p, &x, sizeof(x)); // + +} // + + +void ListDir(int parent_fd, Arena& arena, vector& entries) { + entries.clear(); + int dir_fd = openat(parent_fd, dirname, O_NOATIME | O_RDONLY | O_DIRECTORY | O_CLOEXEC); + if (dir_fd < 0) return; + arena.Clear(); + while (true) { + char* buf = arena.Alloc(); + int n = syscall(SYS_getdents64, dir_fd, buf, Arena::kBlockSize - 256); // + + if (n <= 0) { + if (n) entries.clear(); + break; + } + for (int pos = 0; pos < n;) { + auto* ent = reinterpret_cast(buf + pos); + if (!Dots(ent->d_name)) { + ByteSwap64(ent->d_name); // + + entries.push_back(ent->d_name); + } + pos += ent->d_reclen; + } + } + sort(entries.begin(), entries.end(), [](const char* a, const char* b) { + uint64_t x = Read64(a); // + + uint64_t y = Read64(b); // + + return x < y || (x == y && a != b && memcmp(a + 5, b + 5, 256) < 0); // + + }); + for (char* p : entries) ByteSwap64(p); // + + close(dir_fd); +} +``` + +This is for Little Endian architecture. Big Endian doesn't need `ByteSwap64()`, so it'll be a bit +faster. + +| version | optimization | score | +|---------|----------------------------------|----------:| +| v1 | baseline | 100.0 | +| v2 | avoid heap allocations | 112.7 | +| v3 | open directories with `openat()` | 116.2 | +| v4 | call `getdents64()` directly | 137.8 | +| **v5** | **hand-optimize `strcmp()`** | **143.3** | + +Fast and respectably arcane. + +## Conclusion + +Through a series of incremental improvements we've sped up directory listing by 43.3% compared to a +naive implementation (v1) and 27.2% compared to a reasonable implementation that a seasoned C/C++ +practitioner might write (v2). + +However, these numbers are based on an artificial benchmark while the real judge is always the real +code. Our goal was to speed up gitstatusd. Benchmark was just a tool. Thankfully, the different +versions of `ListDir()` have the same comparative performance within gitstatusd as in the benchmark. +In truth, the directory chosen for the benchmark wasn't arbitrary. It was picked by sampling +gitstatusd when it runs on [chromium](https://github.com/chromium/chromium) git repository. + +The final version of `ListDir()` spends 97% of its CPU time in the kernel. If we assume that it +makes the minimum possible number of system calls and these calls are optimal (true to the best +of my knowledge), it puts the upper bound on possible future performance improvements at just 3%. +There is almost nothing left in `ListDir()` to optimize. + +![ListDir() CPU profile]( + https://raw.githubusercontent.com/romkatv/gitstatus/1ac366952366d89980b3f3484f270b4fa5ae4293/cpu-profile-listdir.png) + +(The CPU profile was created with [gperftools](https://github.com/gperftools/gperftools) and +rendered with [pprof](https://github.com/google/pprof)). diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/gitstatus.plugin.sh b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/gitstatus.plugin.sh new file mode 100644 index 00000000..bfe16dc2 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/gitstatus.plugin.sh @@ -0,0 +1,474 @@ +# Bash bindings for gitstatus. + +[[ $- == *i* ]] || return # non-interactive shell + +# Starts gitstatusd in the background. Does nothing and succeeds if gitstatusd +# is already running. +# +# Usage: gitstatus_start [OPTION]... +# +# -t FLOAT Fail the self-check on initialization if not getting a response from +# gitstatusd for this this many seconds. Defaults to 5. +# +# -s INT Report at most this many staged changes; negative value means infinity. +# Defaults to 1. +# +# -u INT Report at most this many unstaged changes; negative value means infinity. +# Defaults to 1. +# +# -c INT Report at most this many conflicted changes; negative value means infinity. +# Defaults to 1. +# +# -d INT Report at most this many untracked files; negative value means infinity. +# Defaults to 1. +# +# -m INT Report -1 unstaged, untracked and conflicted if there are more than this many +# files in the index. Negative value means infinity. Defaults to -1. +# +# -e Count files within untracked directories like `git status --untracked-files`. +# +# -U Unless this option is specified, report zero untracked files for repositories +# with status.showUntrackedFiles = false. +# +# -W Unless this option is specified, report zero untracked files for repositories +# with bash.showUntrackedFiles = false. +# +# -D Unless this option is specified, report zero staged, unstaged and conflicted +# changes for repositories with bash.showDirtyState = false. +# +# -r INT Close git repositories that haven't been used for this many seconds. This is +# meant to release resources such as memory and file descriptors. The next request +# for a repo that's been closed is much slower than for a repo that hasn't been. +# Negative value means infinity. The default is 3600 (one hour). +function gitstatus_start() { + if [[ "$BASH_VERSION" < 4 ]]; then + >&2 printf 'gitstatus_start: need bash version >= 4.0, found %s\n' "$BASH_VERSION" + >&2 printf '\n' + >&2 printf 'To see the version of the current shell, type:\n' + >&2 printf '\n' + >&2 printf ' \033[32mecho\033[0m \033[33m"$BASH_VERSION"\033[0m\n' + >&2 printf '\n' + >&2 printf 'The output of `\033[32mbash\033[0m --version` may be different and is not relevant.\n' + return 1 + fi + + unset OPTIND + local opt timeout=5 max_dirty=-1 ttl=3600 extra_flags= + local max_num_staged=1 max_num_unstaged=1 max_num_conflicted=1 max_num_untracked=1 + while getopts "t:s:u:c:d:m:r:eUWD" opt; do + case "$opt" in + t) timeout=$OPTARG;; + s) max_num_staged=$OPTARG;; + u) max_num_unstaged=$OPTARG;; + c) max_num_conflicted=$OPTARG;; + d) max_num_untracked=$OPTARG;; + m) max_dirty=$OPTARG;; + r) ttl=$OPTARG;; + e) extra_flags+='--recurse-untracked-dirs ';; + U) extra_flags+='--ignore-status-show-untracked-files ';; + W) extra_flags+='--ignore-bash-show-untracked-files ';; + D) extra_flags+='--ignore-bash-show-dirty-state ';; + *) return 1;; + esac + done + + (( OPTIND == $# + 1 )) || { echo "usage: gitstatus_start [OPTION]..." >&2; return 1; } + + [[ -z "${GITSTATUS_DAEMON_PID:-}" ]] || return 0 # already started + + if [[ "${BASH_SOURCE[0]}" == */* ]]; then + local gitstatus_plugin_dir="${BASH_SOURCE[0]%/*}" + if [[ "$gitstatus_plugin_dir" != /* ]]; then + gitstatus_plugin_dir="$PWD"/"$gitstatus_plugin_dir" + fi + else + local gitstatus_plugin_dir="$PWD" + fi + + local tmpdir req_fifo resp_fifo culprit + + function gitstatus_start_impl() { + local log_level="${GITSTATUS_LOG_LEVEL:-}" + [[ -n "$log_level" || "${GITSTATUS_ENABLE_LOGGING:-0}" != 1 ]] || log_level=INFO + + local uname_sm + uname_sm="$(command uname -sm)" || return + uname_sm="${uname_sm,,}" + local uname_s="${uname_sm% *}" + local uname_m="${uname_sm#* }" + + if [[ "${GITSTATUS_NUM_THREADS:-0}" -gt 0 ]]; then + local threads="$GITSTATUS_NUM_THREADS" + else + local cpus + if ! command -v sysctl &>/dev/null || [[ "$uname_s" == linux ]] || + ! cpus="$(command sysctl -n hw.ncpu)"; then + if ! command -v getconf &>/dev/null || ! cpus="$(command getconf _NPROCESSORS_ONLN)"; then + cpus=8 + fi + fi + local threads=$((cpus > 16 ? 32 : cpus > 0 ? 2 * cpus : 16)) + fi + + local daemon_args=( + --parent-pid="$$" + --num-threads="$threads" + --max-num-staged="$max_num_staged" + --max-num-unstaged="$max_num_unstaged" + --max-num-conflicted="$max_num_conflicted" + --max-num-untracked="$max_num_untracked" + --dirty-max-index-size="$max_dirty" + --repo-ttl-seconds="$ttl" + $extra_flags) + + if [[ -n "$TMPDIR" && ( ( -d "$TMPDIR" && -w "$TMPDIR" ) || ! ( -d /tmp && -w /tmp ) ) ]]; then + local tmpdir=$TMPDIR + else + local tmpdir=/tmp + fi + tmpdir="$(command mktemp -d "$tmpdir"/gitstatus.bash.$$.XXXXXXXXXX)" || return + + if [[ -n "$log_level" ]]; then + GITSTATUS_DAEMON_LOG="$tmpdir"/daemon.log + [[ "$log_level" == INFO ]] || daemon_args+=(--log-level="$log_level") + else + GITSTATUS_DAEMON_LOG=/dev/null + fi + + req_fifo="$tmpdir"/req.fifo + resp_fifo="$tmpdir"/resp.fifo + command mkfifo -- "$req_fifo" "$resp_fifo" || return + + { + ( + trap '' INT QUIT TSTP + [[ "$GITSTATUS_DAEMON_LOG" == /dev/null ]] || set -x + builtin cd / + + ( + local fd_in fd_out + exec {fd_in}<"$req_fifo" {fd_out}>>"$resp_fifo" || exit + echo "$BASHPID" >&"$fd_out" + + local _gitstatus_bash_daemon _gitstatus_bash_version _gitstatus_bash_downloaded + + function _gitstatus_set_daemon() { + _gitstatus_bash_daemon="$1" + _gitstatus_bash_version="$2" + _gitstatus_bash_downloaded="$3" + } + + set -- -d "$gitstatus_plugin_dir" -s "$uname_s" -m "$uname_m" \ + -p "printf '.\036' >&$fd_out" -e "$fd_out" -- _gitstatus_set_daemon + [[ "${GITSTATUS_AUTO_INSTALL:-1}" -ne 0 ]] || set -- -n "$@" + source "$gitstatus_plugin_dir"/install || return + [[ -n "$_gitstatus_bash_daemon" ]] || return + [[ -n "$_gitstatus_bash_version" ]] || return + [[ "$_gitstatus_bash_downloaded" == [01] ]] || return + + local sig=(TERM ILL PIPE) + + if (( UID == EUID )); then + local home=~ + else + local user + user="$(command id -un)" || return + [[ "$user" =~ ^[a-zA-Z0-9_,.-]+$ ]] || return + eval "local home=~$user" + [[ -n "$home" ]] || return + fi + + if [[ -x "$_gitstatus_bash_daemon" ]]; then + HOME="$home" "$_gitstatus_bash_daemon" \ + -G "$_gitstatus_bash_version" "${daemon_args[@]}" <&"$fd_in" >&"$fd_out" & + local pid=$! + trap "trap - ${sig[*]}; kill $pid &>/dev/null" ${sig[@]} + wait "$pid" + local ret=$? + trap - ${sig[@]} + case "$ret" in + 0|129|130|131|137|141|143|159) + echo -nE $'}bye\x1f0\x1e' >&"$fd_out" + exit "$ret" + ;; + esac + fi + + (( ! _gitstatus_bash_downloaded )) || return + [[ "${GITSTATUS_AUTO_INSTALL:-1}" -ne 0 ]] || return + [[ "$_gitstatus_bash_daemon" == \ + "${GITSTATUS_CACHE_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/gitstatus}"/* ]] || return + + set -- -f "$@" + _gitstatus_bash_daemon= + _gitstatus_bash_version= + _gitstatus_bash_downloaded= + source "$gitstatus_plugin_dir"/install || return + [[ -n "$_gitstatus_bash_daemon" ]] || return + [[ -n "$_gitstatus_bash_version" ]] || return + [[ "$_gitstatus_bash_downloaded" == 1 ]] || return + + HOME="$home" "$_gitstatus_bash_daemon" \ + -G "$_gitstatus_bash_version" "${daemon_args[@]}" <&"$fd_in" >&"$fd_out" & + local pid=$! + trap "trap - ${sig[*]}; kill $pid &>/dev/null" ${sig[@]} + wait "$pid" + trap - ${sig[@]} + echo -nE $'}bye\x1f0\x1e' >&"$fd_out" + ) & disown + ) & disown + } 0"$GITSTATUS_DAEMON_LOG" + + exec {_GITSTATUS_REQ_FD}>>"$req_fifo" {_GITSTATUS_RESP_FD}<"$resp_fifo" || return + command rm -f -- "$req_fifo" "$resp_fifo" || return + [[ "$GITSTATUS_DAEMON_LOG" != /dev/null ]] || command rmdir -- "$tmpdir" 2>/dev/null + + IFS='' read -r -u $_GITSTATUS_RESP_FD GITSTATUS_DAEMON_PID || return + [[ "$GITSTATUS_DAEMON_PID" == [1-9]* ]] || return + + local reply + echo -nE $'}hello\x1f\x1e' >&$_GITSTATUS_REQ_FD || return + local dl= + while true; do + reply= + if ! IFS='' read -rd $'\x1e' -u $_GITSTATUS_RESP_FD -t "$timeout" reply; then + culprit="$reply" + return 1 + fi + [[ "$reply" == $'}hello\x1f0' ]] && break + if [[ -z "$dl" ]]; then + dl=1 + if [[ -t 2 ]]; then + local spinner=('\b\033[33m-\033[0m' '\b\033[33m\\\033[0m' '\b\033[33m|\033[0m' '\b\033[33m/\033[0m') + >&2 printf '[\033[33mgitstatus\033[0m] fetching \033[32mgitstatusd\033[0m .. ' + else + local spinner=('.') + >&2 printf '[gitstatus] fetching gitstatusd ..' + fi + fi + >&2 printf "${spinner[0]}" + spinner=("${spinner[@]:1}" "${spinner[0]}") + done + + if [[ -n "$dl" ]]; then + if [[ -t 2 ]]; then + >&2 printf '\b[\033[32mok\033[0m]\n' + else + >&2 echo ' [ok]' + fi + fi + + _GITSTATUS_DIRTY_MAX_INDEX_SIZE=$max_dirty + _GITSTATUS_CLIENT_PID="$BASHPID" + } + + if ! gitstatus_start_impl; then + >&2 printf '\n' + >&2 printf '[\033[31mERROR\033[0m]: gitstatus failed to initialize.\n' + if [[ -n "${culprit-}" ]]; then + >&2 printf '\n%s\n' "$culprit" + fi + [[ -z "${req_fifo:-}" ]] || command rm -f "$req_fifo" + [[ -z "${resp_fifo:-}" ]] || command rm -f "$resp_fifo" + unset -f gitstatus_start_impl + gitstatus_stop + return 1 + fi + + export _GITSTATUS_CLIENT_PID _GITSTATUS_REQ_FD _GITSTATUS_RESP_FD GITSTATUS_DAEMON_PID + unset -f gitstatus_start_impl +} + +# Stops gitstatusd if it's running. +function gitstatus_stop() { + if [[ "${_GITSTATUS_CLIENT_PID:-$BASHPID}" == "$BASHPID" ]]; then + [[ -z "${_GITSTATUS_REQ_FD:-}" ]] || exec {_GITSTATUS_REQ_FD}>&- || true + [[ -z "${_GITSTATUS_RESP_FD:-}" ]] || exec {_GITSTATUS_RESP_FD}>&- || true + [[ -z "${GITSTATUS_DAEMON_PID:-}" ]] || kill "$GITSTATUS_DAEMON_PID" &>/dev/null || true + fi + unset _GITSTATUS_REQ_FD _GITSTATUS_RESP_FD GITSTATUS_DAEMON_PID + unset _GITSTATUS_DIRTY_MAX_INDEX_SIZE _GITSTATUS_CLIENT_PID +} + +# Retrieves status of a git repository from a directory under its working tree. +# +# Usage: gitstatus_query [OPTION]... +# +# -d STR Directory to query. Defaults to $PWD. Has no effect if GIT_DIR is set. +# -t FLOAT Timeout in seconds. Will block for at most this long. If no results +# are available by then, will return error. +# -p Don't compute anything that requires reading Git index. If this option is used, +# the following parameters will be 0: VCS_STATUS_INDEX_SIZE, +# VCS_STATUS_{NUM,HAS}_{STAGED,UNSTAGED,UNTRACKED,CONFLICTED}. +# +# On success sets VCS_STATUS_RESULT to one of the following values: +# +# norepo-sync The directory doesn't belong to a git repository. +# ok-sync The directory belongs to a git repository. +# +# If VCS_STATUS_RESULT is ok-sync, additional variables are set: +# +# VCS_STATUS_WORKDIR Git repo working directory. Not empty. +# VCS_STATUS_COMMIT Commit hash that HEAD is pointing to. Either 40 hex digits or +# empty if there is no HEAD (empty repo). +# VCS_STATUS_COMMIT_ENCODING Encoding of the HEAD's commit message. Empty value means UTF-8. +# VCS_STATUS_COMMIT_SUMMARY The first paragraph of the HEAD's commit message as one line. +# VCS_STATUS_LOCAL_BRANCH Local branch name or empty if not on a branch. +# VCS_STATUS_REMOTE_NAME The remote name, e.g. "upstream" or "origin". +# VCS_STATUS_REMOTE_BRANCH Upstream branch name. Can be empty. +# VCS_STATUS_REMOTE_URL Remote URL. Can be empty. +# VCS_STATUS_ACTION Repository state, A.K.A. action. Can be empty. +# VCS_STATUS_INDEX_SIZE The number of files in the index. +# VCS_STATUS_NUM_STAGED The number of staged changes. +# VCS_STATUS_NUM_CONFLICTED The number of conflicted changes. +# VCS_STATUS_NUM_UNSTAGED The number of unstaged changes. +# VCS_STATUS_NUM_UNTRACKED The number of untracked files. +# VCS_STATUS_HAS_STAGED 1 if there are staged changes, 0 otherwise. +# VCS_STATUS_HAS_CONFLICTED 1 if there are conflicted changes, 0 otherwise. +# VCS_STATUS_HAS_UNSTAGED 1 if there are unstaged changes, 0 if there aren't, -1 if +# unknown. +# VCS_STATUS_NUM_STAGED_NEW The number of staged new files. Note that renamed files +# are reported as deleted plus new. +# VCS_STATUS_NUM_STAGED_DELETED The number of staged deleted files. Note that renamed files +# are reported as deleted plus new. +# VCS_STATUS_NUM_UNSTAGED_DELETED The number of unstaged deleted files. Note that renamed files +# are reported as deleted plus new. +# VCS_STATUS_HAS_UNTRACKED 1 if there are untracked files, 0 if there aren't, -1 if +# unknown. +# VCS_STATUS_COMMITS_AHEAD Number of commits the current branch is ahead of upstream. +# Non-negative integer. +# VCS_STATUS_COMMITS_BEHIND Number of commits the current branch is behind upstream. +# Non-negative integer. +# VCS_STATUS_STASHES Number of stashes. Non-negative integer. +# VCS_STATUS_TAG The last tag (in lexicographical order) that points to the same +# commit as HEAD. +# VCS_STATUS_PUSH_REMOTE_NAME The push remote name, e.g. "upstream" or "origin". +# VCS_STATUS_PUSH_REMOTE_URL Push remote URL. Can be empty. +# VCS_STATUS_PUSH_COMMITS_AHEAD Number of commits the current branch is ahead of push remote. +# Non-negative integer. +# VCS_STATUS_PUSH_COMMITS_BEHIND Number of commits the current branch is behind push remote. +# Non-negative integer. +# VCS_STATUS_NUM_SKIP_WORKTREE The number of files in the index with skip-worktree bit set. +# Non-negative integer. +# VCS_STATUS_NUM_ASSUME_UNCHANGED The number of files in the index with assume-unchanged bit set. +# Non-negative integer. +# +# The point of reporting -1 via VCS_STATUS_HAS_* is to allow the command to skip scanning files in +# large repos. See -m flag of gitstatus_start. +# +# gitstatus_query returns an error if gitstatus_start hasn't been called in the same +# shell or the call had failed. +function gitstatus_query() { + unset OPTIND + local opt dir= timeout=() no_diff=0 + while getopts "d:c:t:p" opt "$@"; do + case "$opt" in + d) dir=$OPTARG;; + t) timeout=(-t "$OPTARG");; + p) no_diff=1;; + *) return 1;; + esac + done + (( OPTIND == $# + 1 )) || { echo "usage: gitstatus_query [OPTION]..." >&2; return 1; } + + [[ -n "${GITSTATUS_DAEMON_PID-}" ]] || return # not started + + local req_id="$RANDOM.$RANDOM.$RANDOM.$RANDOM" + if [[ -z "${GIT_DIR:-}" ]]; then + [[ "$dir" == /* ]] || dir="$(pwd -P)/$dir" || return + elif [[ "$GIT_DIR" == /* ]]; then + dir=:"$GIT_DIR" + else + dir=:"$(pwd -P)/$GIT_DIR" || return + fi + echo -nE "$req_id"$'\x1f'"$dir"$'\x1f'"$no_diff"$'\x1e' >&$_GITSTATUS_REQ_FD || return + + local -a resp + while true; do + IFS=$'\x1f' read -rd $'\x1e' -a resp -u $_GITSTATUS_RESP_FD "${timeout[@]}" || return + [[ "${resp[0]}" == "$req_id" ]] && break + done + + if [[ "${resp[1]}" == 1 ]]; then + VCS_STATUS_RESULT=ok-sync + VCS_STATUS_WORKDIR="${resp[2]}" + VCS_STATUS_COMMIT="${resp[3]}" + VCS_STATUS_LOCAL_BRANCH="${resp[4]}" + VCS_STATUS_REMOTE_BRANCH="${resp[5]}" + VCS_STATUS_REMOTE_NAME="${resp[6]}" + VCS_STATUS_REMOTE_URL="${resp[7]}" + VCS_STATUS_ACTION="${resp[8]}" + VCS_STATUS_INDEX_SIZE="${resp[9]}" + VCS_STATUS_NUM_STAGED="${resp[10]}" + VCS_STATUS_NUM_UNSTAGED="${resp[11]}" + VCS_STATUS_NUM_CONFLICTED="${resp[12]}" + VCS_STATUS_NUM_UNTRACKED="${resp[13]}" + VCS_STATUS_COMMITS_AHEAD="${resp[14]}" + VCS_STATUS_COMMITS_BEHIND="${resp[15]}" + VCS_STATUS_STASHES="${resp[16]}" + VCS_STATUS_TAG="${resp[17]}" + VCS_STATUS_NUM_UNSTAGED_DELETED="${resp[18]}" + VCS_STATUS_NUM_STAGED_NEW="${resp[19]:-0}" + VCS_STATUS_NUM_STAGED_DELETED="${resp[20]:-0}" + VCS_STATUS_PUSH_REMOTE_NAME="${resp[21]:-}" + VCS_STATUS_PUSH_REMOTE_URL="${resp[22]:-}" + VCS_STATUS_PUSH_COMMITS_AHEAD="${resp[23]:-0}" + VCS_STATUS_PUSH_COMMITS_BEHIND="${resp[24]:-0}" + VCS_STATUS_NUM_SKIP_WORKTREE="${resp[25]:-0}" + VCS_STATUS_NUM_ASSUME_UNCHANGED="${resp[26]:-0}" + VCS_STATUS_COMMIT_ENCODING="${resp[27]-}" + VCS_STATUS_COMMIT_SUMMARY="${resp[28]-}" + VCS_STATUS_HAS_STAGED=$((VCS_STATUS_NUM_STAGED > 0)) + if (( _GITSTATUS_DIRTY_MAX_INDEX_SIZE >= 0 && + VCS_STATUS_INDEX_SIZE > _GITSTATUS_DIRTY_MAX_INDEX_SIZE_ )); then + VCS_STATUS_HAS_UNSTAGED=-1 + VCS_STATUS_HAS_CONFLICTED=-1 + VCS_STATUS_HAS_UNTRACKED=-1 + else + VCS_STATUS_HAS_UNSTAGED=$((VCS_STATUS_NUM_UNSTAGED > 0)) + VCS_STATUS_HAS_CONFLICTED=$((VCS_STATUS_NUM_CONFLICTED > 0)) + VCS_STATUS_HAS_UNTRACKED=$((VCS_STATUS_NUM_UNTRACKED > 0)) + fi + else + VCS_STATUS_RESULT=norepo-sync + unset VCS_STATUS_WORKDIR + unset VCS_STATUS_COMMIT + unset VCS_STATUS_LOCAL_BRANCH + unset VCS_STATUS_REMOTE_BRANCH + unset VCS_STATUS_REMOTE_NAME + unset VCS_STATUS_REMOTE_URL + unset VCS_STATUS_ACTION + unset VCS_STATUS_INDEX_SIZE + unset VCS_STATUS_NUM_STAGED + unset VCS_STATUS_NUM_UNSTAGED + unset VCS_STATUS_NUM_CONFLICTED + unset VCS_STATUS_NUM_UNTRACKED + unset VCS_STATUS_HAS_STAGED + unset VCS_STATUS_HAS_UNSTAGED + unset VCS_STATUS_HAS_CONFLICTED + unset VCS_STATUS_HAS_UNTRACKED + unset VCS_STATUS_COMMITS_AHEAD + unset VCS_STATUS_COMMITS_BEHIND + unset VCS_STATUS_STASHES + unset VCS_STATUS_TAG + unset VCS_STATUS_NUM_UNSTAGED_DELETED + unset VCS_STATUS_NUM_STAGED_NEW + unset VCS_STATUS_NUM_STAGED_DELETED + unset VCS_STATUS_PUSH_REMOTE_NAME + unset VCS_STATUS_PUSH_REMOTE_URL + unset VCS_STATUS_PUSH_COMMITS_AHEAD + unset VCS_STATUS_PUSH_COMMITS_BEHIND + unset VCS_STATUS_NUM_SKIP_WORKTREE + unset VCS_STATUS_NUM_ASSUME_UNCHANGED + unset VCS_STATUS_COMMIT_ENCODING + unset VCS_STATUS_COMMIT_SUMMARY + fi +} + +# Usage: gitstatus_check. +# +# Returns 0 if and only if gitstatus_start has succeeded previously. +# If it returns non-zero, gitstatus_query is guaranteed to return non-zero. +function gitstatus_check() { + [[ -n "$GITSTATUS_DAEMON_PID" ]] +} diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/gitstatus.plugin.zsh b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/gitstatus.plugin.zsh new file mode 100644 index 00000000..b74396d3 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/gitstatus.plugin.zsh @@ -0,0 +1,908 @@ +# Zsh bindings for gitstatus. +# +# ------------------------------------------------------------------ +# +# Example: Start gitstatusd, send it a request, wait for response and print it. +# +# source ~/gitstatus/gitstatus.plugin.zsh +# gitstatus_start MY +# gitstatus_query -d $PWD MY +# typeset -m 'VCS_STATUS_*' +# +# Output: +# +# VCS_STATUS_ACTION='' +# VCS_STATUS_COMMIT=c000eddcff0fb38df2d0137efe24d9d2d900f209 +# VCS_STATUS_COMMITS_AHEAD=0 +# VCS_STATUS_COMMITS_BEHIND=0 +# VCS_STATUS_COMMIT_ENCODING='' +# VCS_STATUS_COMMIT_SUMMARY='pull upstream changes from gitstatus' +# VCS_STATUS_HAS_CONFLICTED=0 +# VCS_STATUS_HAS_STAGED=0 +# VCS_STATUS_HAS_UNSTAGED=1 +# VCS_STATUS_HAS_UNTRACKED=1 +# VCS_STATUS_INDEX_SIZE=33 +# VCS_STATUS_LOCAL_BRANCH=master +# VCS_STATUS_NUM_ASSUME_UNCHANGED=0 +# VCS_STATUS_NUM_CONFLICTED=0 +# VCS_STATUS_NUM_STAGED=0 +# VCS_STATUS_NUM_UNSTAGED=1 +# VCS_STATUS_NUM_SKIP_WORKTREE=0 +# VCS_STATUS_NUM_STAGED_NEW=0 +# VCS_STATUS_NUM_STAGED_DELETED=0 +# VCS_STATUS_NUM_UNSTAGED_DELETED=0 +# VCS_STATUS_NUM_UNTRACKED=1 +# VCS_STATUS_PUSH_COMMITS_AHEAD=0 +# VCS_STATUS_PUSH_COMMITS_BEHIND=0 +# VCS_STATUS_PUSH_REMOTE_NAME='' +# VCS_STATUS_PUSH_REMOTE_URL='' +# VCS_STATUS_REMOTE_BRANCH=master +# VCS_STATUS_REMOTE_NAME=origin +# VCS_STATUS_REMOTE_URL=git@github.com:romkatv/powerlevel10k.git +# VCS_STATUS_RESULT=ok-sync +# VCS_STATUS_STASHES=0 +# VCS_STATUS_TAG='' +# VCS_STATUS_WORKDIR=/home/romka/powerlevel10k + +[[ -o 'interactive' ]] || 'return' + +# Temporarily change options. +'builtin' 'local' '-a' '_gitstatus_opts' +[[ ! -o 'aliases' ]] || _gitstatus_opts+=('aliases') +[[ ! -o 'sh_glob' ]] || _gitstatus_opts+=('sh_glob') +[[ ! -o 'no_brace_expand' ]] || _gitstatus_opts+=('no_brace_expand') +'builtin' 'setopt' 'no_aliases' 'no_sh_glob' 'brace_expand' + +autoload -Uz add-zsh-hook || return +zmodload zsh/datetime zsh/system || return +zmodload -F zsh/files b:zf_rm || return + +typeset -g _gitstatus_plugin_dir"${1:-}"="${${(%):-%x}:A:h}" + +# Retrieves status of a git repo from a directory under its working tree. +# +## Usage: gitstatus_query [OPTION]... NAME +# +# -d STR Directory to query. Defaults to the current directory. Has no effect if GIT_DIR +# is set. +# -c STR Callback function to call once the results are available. Called only after +# gitstatus_query returns 0 with VCS_STATUS_RESULT=tout. +# -t FLOAT Timeout in seconds. Negative value means infinity. Will block for at most this long. +# If no results are available by then: if -c isn't specified, will return 1; otherwise +# will set VCS_STATUS_RESULT=tout and return 0. +# -p Don't compute anything that requires reading Git index. If this option is used, +# the following parameters will be 0: VCS_STATUS_INDEX_SIZE, +# VCS_STATUS_{NUM,HAS}_{STAGED,UNSTAGED,UNTRACKED,CONFLICTED}. +# +# On success sets VCS_STATUS_RESULT to one of the following values: +# +# tout Timed out waiting for data; will call the user-specified callback later. +# norepo-sync The directory isn't a git repo. +# ok-sync The directory is a git repo. +# +# When the callback is called, VCS_STATUS_RESULT is set to one of the following values: +# +# norepo-async The directory isn't a git repo. +# ok-async The directory is a git repo. +# +# If VCS_STATUS_RESULT is ok-sync or ok-async, additional variables are set: +# +# VCS_STATUS_WORKDIR Git repo working directory. Not empty. +# VCS_STATUS_COMMIT Commit hash that HEAD is pointing to. Either 40 hex digits or +# empty if there is no HEAD (empty repo). +# VCS_STATUS_COMMIT_ENCODING Encoding of the HEAD's commit message. Empty value means UTF-8. +# VCS_STATUS_COMMIT_SUMMARY The first paragraph of the HEAD's commit message as one line. +# VCS_STATUS_LOCAL_BRANCH Local branch name or empty if not on a branch. +# VCS_STATUS_REMOTE_NAME The remote name, e.g. "upstream" or "origin". +# VCS_STATUS_REMOTE_BRANCH Upstream branch name. Can be empty. +# VCS_STATUS_REMOTE_URL Remote URL. Can be empty. +# VCS_STATUS_ACTION Repository state, A.K.A. action. Can be empty. +# VCS_STATUS_INDEX_SIZE The number of files in the index. +# VCS_STATUS_NUM_STAGED The number of staged changes. +# VCS_STATUS_NUM_CONFLICTED The number of conflicted changes. +# VCS_STATUS_NUM_UNSTAGED The number of unstaged changes. +# VCS_STATUS_NUM_UNTRACKED The number of untracked files. +# VCS_STATUS_HAS_STAGED 1 if there are staged changes, 0 otherwise. +# VCS_STATUS_HAS_CONFLICTED 1 if there are conflicted changes, 0 otherwise. +# VCS_STATUS_HAS_UNSTAGED 1 if there are unstaged changes, 0 if there aren't, -1 if +# unknown. +# VCS_STATUS_NUM_STAGED_NEW The number of staged new files. Note that renamed files +# are reported as deleted plus new. +# VCS_STATUS_NUM_STAGED_DELETED The number of staged deleted files. Note that renamed files +# are reported as deleted plus new. +# VCS_STATUS_NUM_UNSTAGED_DELETED The number of unstaged deleted files. Note that renamed files +# are reported as deleted plus new. +# VCS_STATUS_HAS_UNTRACKED 1 if there are untracked files, 0 if there aren't, -1 if +# unknown. +# VCS_STATUS_COMMITS_AHEAD Number of commits the current branch is ahead of upstream. +# Non-negative integer. +# VCS_STATUS_COMMITS_BEHIND Number of commits the current branch is behind upstream. +# Non-negative integer. +# VCS_STATUS_STASHES Number of stashes. Non-negative integer. +# VCS_STATUS_TAG The last tag (in lexicographical order) that points to the same +# commit as HEAD. +# VCS_STATUS_PUSH_REMOTE_NAME The push remote name, e.g. "upstream" or "origin". +# VCS_STATUS_PUSH_REMOTE_URL Push remote URL. Can be empty. +# VCS_STATUS_PUSH_COMMITS_AHEAD Number of commits the current branch is ahead of push remote. +# Non-negative integer. +# VCS_STATUS_PUSH_COMMITS_BEHIND Number of commits the current branch is behind push remote. +# Non-negative integer. +# VCS_STATUS_NUM_SKIP_WORKTREE The number of files in the index with skip-worktree bit set. +# Non-negative integer. +# VCS_STATUS_NUM_ASSUME_UNCHANGED The number of files in the index with assume-unchanged bit set. +# Non-negative integer. +# +# The point of reporting -1 via VCS_STATUS_HAS_* is to allow the command to skip scanning files in +# large repos. See -m flag of gitstatus_start. +# +# gitstatus_query returns an error if gitstatus_start hasn't been called in the same shell or +# the call had failed. +# +# !!!!! WARNING: CONCURRENT CALLS WITH THE SAME NAME ARE NOT ALLOWED !!!!! +# +# It's illegal to call gitstatus_query if the last asynchronous call with the same NAME hasn't +# completed yet. If you need to issue concurrent requests, use different NAME arguments. +function gitstatus_query"${1:-}"() { + emulate -L zsh -o no_aliases -o extended_glob -o typeset_silent + + local fsuf=${${(%):-%N}#gitstatus_query} + + unset VCS_STATUS_RESULT + + local opt dir callback OPTARG + local -i no_diff OPTIND + local -F timeout=-1 + while getopts ":d:c:t:p" opt; do + case $opt in + +p) no_diff=0;; + p) no_diff=1;; + d) dir=$OPTARG;; + c) callback=$OPTARG;; + t) + if [[ $OPTARG != (|+|-)<->(|.<->)(|[eE](|-|+)<->) ]]; then + print -ru2 -- "gitstatus_query: invalid -t argument: $OPTARG" + return 1 + fi + timeout=OPTARG + ;; + \?) print -ru2 -- "gitstatus_query: invalid option: $OPTARG" ; return 1;; + :) print -ru2 -- "gitstatus_query: missing required argument: $OPTARG"; return 1;; + *) print -ru2 -- "gitstatus_query: invalid option: $opt" ; return 1;; + esac + done + + if (( OPTIND != ARGC )); then + print -ru2 -- "gitstatus_query: exactly one positional argument is required" + return 1 + fi + + local name=$*[OPTIND] + if [[ $name != [[:IDENT:]]## ]]; then + print -ru2 -- "gitstatus_query: invalid positional argument: $name" + return 1 + fi + + (( _GITSTATUS_STATE_$name == 2 )) || return + + if [[ -z $GIT_DIR ]]; then + if [[ $dir != /* ]]; then + if [[ $PWD == /* && $PWD -ef . ]]; then + dir=$PWD/$dir + else + dir=${dir:a} + fi + fi + else + if [[ $GIT_DIR == /* ]]; then + dir=:$GIT_DIR + elif [[ $PWD == /* && $PWD -ef . ]]; then + dir=:$PWD/$GIT_DIR + else + dir=:${GIT_DIR:a} + fi + fi + + if [[ $dir != (|:)/* ]]; then + typeset -g VCS_STATUS_RESULT=norepo-sync + _gitstatus_clear$fsuf + return 0 + fi + + local -i req_fd=${(P)${:-_GITSTATUS_REQ_FD_$name}} + local req_id=$EPOCHREALTIME + print -rnu $req_fd -- $req_id' '$callback$'\x1f'$dir$'\x1f'$no_diff$'\x1e' || return + + (( ++_GITSTATUS_NUM_INFLIGHT_$name )) + + if (( timeout == 0 )); then + typeset -g VCS_STATUS_RESULT=tout + _gitstatus_clear$fsuf + else + while true; do + _gitstatus_process_response$fsuf $name $timeout $req_id || return + [[ $VCS_STATUS_RESULT == *-async ]] || break + done + fi + + [[ $VCS_STATUS_RESULT != tout || -n $callback ]] +} + +# If the last call to gitstatus_query timed out (VCS_STATUS_RESULT=tout), wait for the callback +# to be called. Otherwise do nothing. +# +# Usage: gitstatus_process_results [OPTION]... NAME +# +# -t FLOAT Timeout in seconds. Negative value means infinity. Will block for at most this long. +# +# Returns an error only when invoked with incorrect arguments and when gitstatusd isn't running or +# broken. +# +# If a callback gets called, VCS_STATUS_* parameters are set as in gitstatus_query. +# VCS_STATUS_RESULT is either norepo-async or ok-async. +function gitstatus_process_results"${1:-}"() { + emulate -L zsh -o no_aliases -o extended_glob -o typeset_silent + + local fsuf=${${(%):-%N}#gitstatus_process_results} + + local opt OPTARG + local -i OPTIND + local -F timeout=-1 + while getopts ":t:" opt; do + case $opt in + t) + if [[ $OPTARG != (|+|-)<->(|.<->)(|[eE](|-|+)<->) ]]; then + print -ru2 -- "gitstatus_process_results: invalid -t argument: $OPTARG" + return 1 + fi + timeout=OPTARG + ;; + \?) print -ru2 -- "gitstatus_process_results: invalid option: $OPTARG" ; return 1;; + :) print -ru2 -- "gitstatus_process_results: missing required argument: $OPTARG"; return 1;; + *) print -ru2 -- "gitstatus_process_results: invalid option: $opt" ; return 1;; + esac + done + + if (( OPTIND != ARGC )); then + print -ru2 -- "gitstatus_process_results: exactly one positional argument is required" + return 1 + fi + + local name=$*[OPTIND] + if [[ $name != [[:IDENT:]]## ]]; then + print -ru2 -- "gitstatus_process_results: invalid positional argument: $name" + return 1 + fi + + (( _GITSTATUS_STATE_$name == 2 )) || return + + while (( _GITSTATUS_NUM_INFLIGHT_$name )); do + _gitstatus_process_response$fsuf $name $timeout '' || return + [[ $VCS_STATUS_RESULT == *-async ]] || break + done + + return 0 +} + +function _gitstatus_clear"${1:-}"() { + unset VCS_STATUS_{WORKDIR,COMMIT,LOCAL_BRANCH,REMOTE_BRANCH,REMOTE_NAME,REMOTE_URL,ACTION,INDEX_SIZE,NUM_STAGED,NUM_UNSTAGED,NUM_CONFLICTED,NUM_UNTRACKED,HAS_STAGED,HAS_UNSTAGED,HAS_CONFLICTED,HAS_UNTRACKED,COMMITS_AHEAD,COMMITS_BEHIND,STASHES,TAG,NUM_UNSTAGED_DELETED,NUM_STAGED_NEW,NUM_STAGED_DELETED,PUSH_REMOTE_NAME,PUSH_REMOTE_URL,PUSH_COMMITS_AHEAD,PUSH_COMMITS_BEHIND,NUM_SKIP_WORKTREE,NUM_ASSUME_UNCHANGED} +} + +function _gitstatus_process_response"${1:-}"() { + local name=$1 timeout req_id=$3 buf + local -i resp_fd=_GITSTATUS_RESP_FD_$name + local -i dirty_max_index_size=_GITSTATUS_DIRTY_MAX_INDEX_SIZE_$name + + (( $2 >= 0 )) && timeout=-t$2 && [[ -t $resp_fd ]] + sysread $timeout -i $resp_fd 'buf[$#buf+1]' || { + if (( $? == 4 )); then + if [[ -n $req_id ]]; then + typeset -g VCS_STATUS_RESULT=tout + _gitstatus_clear$fsuf + fi + return 0 + else + gitstatus_stop$fsuf $name + return 1 + fi + } + while [[ $buf != *$'\x1e' ]]; do + if ! sysread -i $resp_fd 'buf[$#buf+1]'; then + gitstatus_stop$fsuf $name + return 1 + fi + done + + local s + for s in ${(ps:\x1e:)buf}; do + local -a resp=("${(@ps:\x1f:)s}") + if (( resp[2] )); then + if [[ $resp[1] == $req_id' '* ]]; then + typeset -g VCS_STATUS_RESULT=ok-sync + else + typeset -g VCS_STATUS_RESULT=ok-async + fi + for VCS_STATUS_WORKDIR \ + VCS_STATUS_COMMIT \ + VCS_STATUS_LOCAL_BRANCH \ + VCS_STATUS_REMOTE_BRANCH \ + VCS_STATUS_REMOTE_NAME \ + VCS_STATUS_REMOTE_URL \ + VCS_STATUS_ACTION \ + VCS_STATUS_INDEX_SIZE \ + VCS_STATUS_NUM_STAGED \ + VCS_STATUS_NUM_UNSTAGED \ + VCS_STATUS_NUM_CONFLICTED \ + VCS_STATUS_NUM_UNTRACKED \ + VCS_STATUS_COMMITS_AHEAD \ + VCS_STATUS_COMMITS_BEHIND \ + VCS_STATUS_STASHES \ + VCS_STATUS_TAG \ + VCS_STATUS_NUM_UNSTAGED_DELETED \ + VCS_STATUS_NUM_STAGED_NEW \ + VCS_STATUS_NUM_STAGED_DELETED \ + VCS_STATUS_PUSH_REMOTE_NAME \ + VCS_STATUS_PUSH_REMOTE_URL \ + VCS_STATUS_PUSH_COMMITS_AHEAD \ + VCS_STATUS_PUSH_COMMITS_BEHIND \ + VCS_STATUS_NUM_SKIP_WORKTREE \ + VCS_STATUS_NUM_ASSUME_UNCHANGED \ + VCS_STATUS_COMMIT_ENCODING \ + VCS_STATUS_COMMIT_SUMMARY in "${(@)resp[3,29]}"; do + done + typeset -gi VCS_STATUS_{INDEX_SIZE,NUM_STAGED,NUM_UNSTAGED,NUM_CONFLICTED,NUM_UNTRACKED,COMMITS_AHEAD,COMMITS_BEHIND,STASHES,NUM_UNSTAGED_DELETED,NUM_STAGED_NEW,NUM_STAGED_DELETED,PUSH_COMMITS_AHEAD,PUSH_COMMITS_BEHIND,NUM_SKIP_WORKTREE,NUM_ASSUME_UNCHANGED} + typeset -gi VCS_STATUS_HAS_STAGED=$((VCS_STATUS_NUM_STAGED > 0)) + if (( dirty_max_index_size >= 0 && VCS_STATUS_INDEX_SIZE > dirty_max_index_size )); then + typeset -gi \ + VCS_STATUS_HAS_UNSTAGED=-1 \ + VCS_STATUS_HAS_CONFLICTED=-1 \ + VCS_STATUS_HAS_UNTRACKED=-1 + else + typeset -gi \ + VCS_STATUS_HAS_UNSTAGED=$((VCS_STATUS_NUM_UNSTAGED > 0)) \ + VCS_STATUS_HAS_CONFLICTED=$((VCS_STATUS_NUM_CONFLICTED > 0)) \ + VCS_STATUS_HAS_UNTRACKED=$((VCS_STATUS_NUM_UNTRACKED > 0)) + fi + else + if [[ $resp[1] == $req_id' '* ]]; then + typeset -g VCS_STATUS_RESULT=norepo-sync + else + typeset -g VCS_STATUS_RESULT=norepo-async + fi + _gitstatus_clear$fsuf + fi + (( --_GITSTATUS_NUM_INFLIGHT_$name )) + [[ $VCS_STATUS_RESULT == *-async ]] && emulate zsh -c "${resp[1]#* }" + done + + return 0 +} + +function _gitstatus_daemon"${1:-}"() { + local -i pipe_fd + exec 0<&- {pipe_fd}>&1 1>>$daemon_log 2>&1 || return + local pgid=$sysparams[pid] + [[ $pgid == <1-> ]] || return + builtin cd -q / || return + + { + { + trap '' PIPE + + local uname_sm + uname_sm="${${(L)$(command uname -sm)}//ı/i}" || return + [[ $uname_sm == [^' ']##' '[^' ']## ]] || return + local uname_s=${uname_sm% *} + local uname_m=${uname_sm#* } + + if [[ $GITSTATUS_NUM_THREADS == <1-> ]]; then + args+=(-t $GITSTATUS_NUM_THREADS) + else + local cpus + if (( ! $+commands[sysctl] )) || [[ $uname_s == linux ]] || + ! cpus="$(command sysctl -n hw.ncpu)"; then + if (( ! $+commands[getconf] )) || ! cpus="$(command getconf _NPROCESSORS_ONLN)"; then + cpus=8 + fi + fi + args+=(-t $((cpus > 16 ? 32 : cpus > 0 ? 2 * cpus : 16))) + fi + + command mkfifo -- $file_prefix.fifo || return + print -rnu $pipe_fd -- ${(l:20:)pgid} || return + exec <$file_prefix.fifo || return + zf_rm -- $file_prefix.fifo || return + + local _gitstatus_zsh_daemon _gitstatus_zsh_version _gitstatus_zsh_downloaded + + function _gitstatus_set_daemon$fsuf() { + _gitstatus_zsh_daemon="$1" + _gitstatus_zsh_version="$2" + _gitstatus_zsh_downloaded="$3" + } + + local gitstatus_plugin_dir_var=_gitstatus_plugin_dir$fsuf + local gitstatus_plugin_dir=${(P)gitstatus_plugin_dir_var} + builtin set -- -d $gitstatus_plugin_dir -s $uname_s -m $uname_m \ + -p "printf '\\001' >&$pipe_fd" -e $pipe_fd -- _gitstatus_set_daemon$fsuf + [[ ${GITSTATUS_AUTO_INSTALL:-1} == (|-|+)<1-> ]] || builtin set -- -n "$@" + builtin source $gitstatus_plugin_dir/install || return + [[ -n $_gitstatus_zsh_daemon ]] || return + [[ -n $_gitstatus_zsh_version ]] || return + [[ $_gitstatus_zsh_downloaded == [01] ]] || return + + if (( UID == EUID )); then + local home=~ + else + local user + user="$(command id -un)" || return + local home=${userdirs[$user]} + [[ -n $home ]] || return + fi + + if [[ -x $_gitstatus_zsh_daemon ]]; then + HOME=$home $_gitstatus_zsh_daemon -G $_gitstatus_zsh_version "${(@)args}" >&$pipe_fd + local -i ret=$? + [[ $ret == (0|129|130|131|137|141|143|159) ]] && return ret + fi + + (( ! _gitstatus_zsh_downloaded )) || return + [[ ${GITSTATUS_AUTO_INSTALL:-1} == (|-|+)<1-> ]] || return + [[ $_gitstatus_zsh_daemon == \ + ${GITSTATUS_CACHE_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/gitstatus}/* ]] || return + + builtin set -- -f "$@" + _gitstatus_zsh_daemon= + _gitstatus_zsh_version= + _gitstatus_zsh_downloaded= + builtin source $gitstatus_plugin_dir/install || return + [[ -n $_gitstatus_zsh_daemon ]] || return + [[ -n $_gitstatus_zsh_version ]] || return + [[ $_gitstatus_zsh_downloaded == 1 ]] || return + + HOME=$home $_gitstatus_zsh_daemon -G $_gitstatus_zsh_version "${(@)args}" >&$pipe_fd + } always { + local -i ret=$? + zf_rm -f -- $file_prefix.lock $file_prefix.fifo + kill -- -$pgid + } + } &! + + (( lock_fd == -1 )) && return + + { + if zsystem flock -- $file_prefix.lock && command sleep 5 && [[ -e $file_prefix.lock ]]; then + zf_rm -f -- $file_prefix.lock $file_prefix.fifo + kill -- -$pgid + fi + } &! +} + +# Starts gitstatusd in the background. Does nothing and succeeds if gitstatusd is already running. +# +# Usage: gitstatus_start [OPTION]... NAME +# +# -t FLOAT Fail the self-check on initialization if not getting a response from gitstatusd for +# this this many seconds. Defaults to 5. +# +# -s INT Report at most this many staged changes; negative value means infinity. +# Defaults to 1. +# +# -u INT Report at most this many unstaged changes; negative value means infinity. +# Defaults to 1. +# +# -c INT Report at most this many conflicted changes; negative value means infinity. +# Defaults to 1. +# +# -d INT Report at most this many untracked files; negative value means infinity. +# Defaults to 1. +# +# -m INT Report -1 unstaged, untracked and conflicted if there are more than this many +# files in the index. Negative value means infinity. Defaults to -1. +# +# -e Count files within untracked directories like `git status --untracked-files`. +# +# -U Unless this option is specified, report zero untracked files for repositories +# with status.showUntrackedFiles = false. +# +# -W Unless this option is specified, report zero untracked files for repositories +# with bash.showUntrackedFiles = false. +# +# -D Unless this option is specified, report zero staged, unstaged and conflicted +# changes for repositories with bash.showDirtyState = false. +function gitstatus_start"${1:-}"() { + emulate -L zsh -o no_aliases -o no_bg_nice -o extended_glob -o typeset_silent || return + print -rnu2 || return + + local fsuf=${${(%):-%N}#gitstatus_start} + + local opt OPTARG + local -i OPTIND + local -F timeout=5 + local -i async=0 + local -a args=() + local -i dirty_max_index_size=-1 + + while getopts ":t:s:u:c:d:m:eaUWD" opt; do + case $opt in + a) async=1;; + +a) async=0;; + t) + if [[ $OPTARG != (|+)<->(|.<->)(|[eE](|-|+)<->) ]] || (( ${timeout::=OPTARG} <= 0 )); then + print -ru2 -- "gitstatus_start: invalid -t argument: $OPTARG" + return 1 + fi + ;; + s|u|c|d|m) + if [[ $OPTARG != (|-|+)<-> ]]; then + print -ru2 -- "gitstatus_start: invalid -$opt argument: $OPTARG" + return 1 + fi + args+=(-$opt $OPTARG) + [[ $opt == m ]] && dirty_max_index_size=OPTARG + ;; + e|U|W|D) args+=-$opt;; + +(e|U|W|D)) args=(${(@)args:#-$opt});; + \?) print -ru2 -- "gitstatus_start: invalid option: $OPTARG" ; return 1;; + :) print -ru2 -- "gitstatus_start: missing required argument: $OPTARG"; return 1;; + *) print -ru2 -- "gitstatus_start: invalid option: $opt" ; return 1;; + esac + done + + if (( OPTIND != ARGC )); then + print -ru2 -- "gitstatus_start: exactly one positional argument is required" + return 1 + fi + + local name=$*[OPTIND] + if [[ $name != [[:IDENT:]]## ]]; then + print -ru2 -- "gitstatus_start: invalid positional argument: $name" + return 1 + fi + + local -i lock_fd resp_fd stderr_fd + local file_prefix xtrace=/dev/null daemon_log=/dev/null culprit + + { + if (( _GITSTATUS_STATE_$name )); then + (( async )) && return + (( _GITSTATUS_STATE_$name == 2 )) && return + lock_fd=_GITSTATUS_LOCK_FD_$name + resp_fd=_GITSTATUS_RESP_FD_$name + xtrace=${(P)${:-GITSTATUS_XTRACE_$name}} + daemon_log=${(P)${:-GITSTATUS_DAEMON_LOG_$name}} + file_prefix=${(P)${:-_GITSTATUS_FILE_PREFIX_$name}} + else + typeset -gi _GITSTATUS_START_COUNTER + local log_level=$GITSTATUS_LOG_LEVEL + if [[ -n "$TMPDIR" && ( ( -d "$TMPDIR" && -w "$TMPDIR" ) || ! ( -d /tmp && -w /tmp ) ) ]]; then + local tmpdir=$TMPDIR + else + local tmpdir=/tmp + fi + local file_prefix=${tmpdir:A}/gitstatus.$name.$EUID + file_prefix+=.$sysparams[pid].$EPOCHSECONDS.$((++_GITSTATUS_START_COUNTER)) + (( GITSTATUS_ENABLE_LOGGING )) && : ${log_level:=INFO} + if [[ -n $log_level ]]; then + xtrace=$file_prefix.xtrace.log + daemon_log=$file_prefix.daemon.log + fi + args+=(-v ${log_level:-FATAL}) + typeset -g GITSTATUS_XTRACE_$name=$xtrace + typeset -g GITSTATUS_DAEMON_LOG_$name=$daemon_log + typeset -g _GITSTATUS_FILE_PREFIX_$name=$file_prefix + typeset -gi _GITSTATUS_CLIENT_PID_$name="sysparams[pid]" + typeset -gi _GITSTATUS_DIRTY_MAX_INDEX_SIZE_$name=dirty_max_index_size + fi + + () { + if [[ $xtrace != /dev/null && -o no_xtrace ]]; then + exec {stderr_fd}>&2 || return + exec 2>>$xtrace || return + setopt xtrace + fi + + setopt monitor || return + + if (( ! _GITSTATUS_STATE_$name )); then + if [[ -r /proc/version && "$($file_prefix.lock || return + zsystem flock -f lock_fd $file_prefix.lock || return + [[ $lock_fd == <1-> ]] || return + fi + + typeset -gi _GITSTATUS_LOCK_FD_$name=lock_fd + + if [[ $OSTYPE == cygwin* && -d /proc/self/fd ]]; then + # Work around bugs in Cygwin 32-bit. + # + # This hangs: + # + # emulate -L zsh + # () { exec {fd}< $1 } <(:) + # =true # hangs here + # + # This hangs: + # + # sysopen -r -u fd <(:) + local -i fd + exec {fd}< <(_gitstatus_daemon$fsuf) || return + { + [[ -r /proc/self/fd/$fd ]] || return + sysopen -r -o cloexec -u resp_fd /proc/self/fd/$fd || return + } always { + exec {fd} >&- || return + } + else + sysopen -r -o cloexec -u resp_fd <(_gitstatus_daemon$fsuf) || return + fi + + typeset -gi GITSTATUS_DAEMON_PID_$name="${sysparams[procsubstpid]:--1}" + + [[ $resp_fd == <1-> ]] || return + typeset -gi _GITSTATUS_RESP_FD_$name=resp_fd + typeset -gi _GITSTATUS_STATE_$name=1 + fi + + if (( ! async )); then + (( _GITSTATUS_CLIENT_PID_$name == sysparams[pid] )) || return + + local pgid + while (( $#pgid < 20 )); do + [[ -t $resp_fd ]] + sysread -s $((20 - $#pgid)) -t $timeout -i $resp_fd 'pgid[$#pgid+1]' || return + done + [[ $pgid == ' '#<1-> ]] || return + typeset -gi GITSTATUS_DAEMON_PID_$name=pgid + + sysopen -w -o cloexec -u req_fd -- $file_prefix.fifo || return + [[ $req_fd == <1-> ]] || return + typeset -gi _GITSTATUS_REQ_FD_$name=req_fd + + print -nru $req_fd -- $'}hello\x1f\x1e' || return + local expected=$'}hello\x1f0\x1e' actual + if (( $+functions[p10k] )) && [[ ! -t 1 && ! -t 0 ]]; then + local -F deadline='EPOCHREALTIME + 4' + else + local -F deadline='1' + fi + while true; do + [[ -t $resp_fd ]] + sysread -s 1 -t $timeout -i $resp_fd actual || return + [[ $expected == $actual* ]] && break + if [[ $actual != $'\1' ]]; then + [[ -t $resp_fd ]] + while sysread -t $timeout -i $resp_fd 'actual[$#actual+1]'; do + [[ -t $resp_fd ]] + done + culprit=$actual + return 1 + fi + (( EPOCHREALTIME < deadline )) && continue + if (( deadline > 0 )); then + deadline=0 + if (( stderr_fd )); then + unsetopt xtrace + exec 2>&$stderr_fd {stderr_fd}>&- + stderr_fd=0 + fi + if (( $+functions[p10k] )); then + p10k clear-instant-prompt || return + fi + if [[ $name == POWERLEVEL9K ]]; then + local label=powerlevel10k + else + local label=gitstatus + fi + if [[ -t 2 ]]; then + local spinner=($'\b%3F-%f' $'\b%3F\\%f' $'\b%3F|%f' $'\b%3F/%f') + print -Prnu2 -- "[%3F$label%f] fetching %2Fgitstatusd%f .. " + else + local spinner=('.') + print -rnu2 -- "[$label] fetching gitstatusd .." + fi + fi + print -Prnu2 -- $spinner[1] + spinner=($spinner[2,-1] $spinner[1]) + done + + if (( deadline == 0 )); then + if [[ -t 2 ]]; then + print -Pru2 -- $'\b[%2Fok%f]' + else + print -ru2 -- ' [ok]' + fi + if [[ $xtrace != /dev/null && -o no_xtrace ]]; then + exec {stderr_fd}>&2 || return + exec 2>>$xtrace || return + setopt xtrace + fi + fi + + while (( $#actual < $#expected )); do + [[ -t $resp_fd ]] + sysread -s $(($#expected - $#actual)) -t $timeout -i $resp_fd 'actual[$#actual+1]' || return + done + [[ $actual == $expected ]] || return + + function _gitstatus_process_response_$name-$fsuf() { + emulate -L zsh -o no_aliases -o extended_glob -o typeset_silent + local pair=${${(%):-%N}#_gitstatus_process_response_} + local name=${pair%%-*} + local fsuf=${pair#*-} + [[ $name == POWERLEVEL9K && $fsuf == _p9k_ ]] && eval $__p9k_intro_base + if (( ARGC == 1 )); then + _gitstatus_process_response$fsuf $name 0 '' + else + gitstatus_stop$fsuf $name + fi + } + if ! zle -F $resp_fd _gitstatus_process_response_$name-$fsuf; then + unfunction _gitstatus_process_response_$name-$fsuf + return 1 + fi + + function _gitstatus_cleanup_$name-$fsuf() { + emulate -L zsh -o no_aliases -o extended_glob -o typeset_silent + local pair=${${(%):-%N}#_gitstatus_cleanup_} + local name=${pair%%-*} + local fsuf=${pair#*-} + (( _GITSTATUS_CLIENT_PID_$name == sysparams[pid] )) || return + gitstatus_stop$fsuf $name + } + if ! add-zsh-hook zshexit _gitstatus_cleanup_$name-$fsuf; then + unfunction _gitstatus_cleanup_$name-$fsuf + return 1 + fi + + if (( lock_fd != -1 )); then + zf_rm -- $file_prefix.lock || return + zsystem flock -u $lock_fd || return + fi + unset _GITSTATUS_LOCK_FD_$name + + typeset -gi _GITSTATUS_STATE_$name=2 + fi + } + } always { + local -i err=$? + (( stderr_fd )) && exec 2>&$stderr_fd {stderr_fd}>&- + (( err == 0 )) && return + + gitstatus_stop$fsuf $name + + setopt prompt_percent no_prompt_subst no_prompt_bang + (( $+functions[p10k] )) && p10k clear-instant-prompt + print -ru2 -- '' + print -Pru2 -- '[%F{red}ERROR%f]: gitstatus failed to initialize.' + print -ru2 -- '' + if [[ -n $culprit ]]; then + print -ru2 -- $culprit + return err + fi + if [[ -s $xtrace ]]; then + print -ru2 -- '' + print -Pru2 -- " Zsh log (%U${xtrace//\%/%%}%u):" + print -Pru2 -- '%F{yellow}' + print -lru2 -- "${(@)${(@f)$(<$xtrace)}/#/ }" + print -Pnru2 -- '%f' + fi + if [[ -s $daemon_log ]]; then + print -ru2 -- '' + print -Pru2 -- " Daemon log (%U${daemon_log//\%/%%}%u):" + print -Pru2 -- '%F{yellow}' + print -lru2 -- "${(@)${(@f)$(<$daemon_log)}/#/ }" + print -Pnru2 -- '%f' + fi + if [[ $GITSTATUS_LOG_LEVEL == DEBUG ]]; then + print -ru2 -- '' + print -ru2 -- ' System information:' + print -Pru2 -- '%F{yellow}' + print -ru2 -- " zsh: $ZSH_VERSION" + print -ru2 -- " uname -a: $(command uname -a)" + print -Pru2 -- '%f' + print -ru2 -- ' If you need help, open an issue and attach this whole error message to it:' + print -ru2 -- '' + print -Pru2 -- ' %Uhttps://github.com/romkatv/gitstatus/issues/new%u' + else + print -ru2 -- '' + local home=~ + local zshrc=${${${(q)${ZDOTDIR:-~}}/#${(q)home}/'~'}//\%/%%}/.zshrc + print -Pru2 -- " Add the following parameter to %U$zshrc%u for extra diagnostics on error:" + print -ru2 -- '' + print -Pru2 -- ' %BGITSTATUS_LOG_LEVEL=DEBUG%b' + print -ru2 -- '' + print -ru2 -- ' Restart Zsh to retry gitstatus initialization:' + print -ru2 -- '' + print -Pru2 -- ' %F{green}%Uexec%u zsh%f' + fi + } +} + +# Stops gitstatusd if it's running. +# +# Usage: gitstatus_stop NAME. +function gitstatus_stop"${1:-}"() { + emulate -L zsh -o no_aliases -o extended_glob -o typeset_silent + + local fsuf=${${(%):-%N}#gitstatus_stop} + + if (( ARGC != 1 )); then + print -ru2 -- "gitstatus_stop: exactly one positional argument is required" + return 1 + fi + + local name=$1 + if [[ $name != [[:IDENT:]]## ]]; then + print -ru2 -- "gitstatus_stop: invalid positional argument: $name" + return 1 + fi + + local state_var=_GITSTATUS_STATE_$name + local req_fd_var=_GITSTATUS_REQ_FD_$name + local resp_fd_var=_GITSTATUS_RESP_FD_$name + local lock_fd_var=_GITSTATUS_LOCK_FD_$name + local client_pid_var=_GITSTATUS_CLIENT_PID_$name + local daemon_pid_var=GITSTATUS_DAEMON_PID_$name + local inflight_var=_GITSTATUS_NUM_INFLIGHT_$name + local file_prefix_var=_GITSTATUS_FILE_PREFIX_$name + local dirty_max_index_size_var=_GITSTATUS_DIRTY_MAX_INDEX_SIZE_$name + + local req_fd=${(P)req_fd_var} + local resp_fd=${(P)resp_fd_var} + local lock_fd=${(P)lock_fd_var} + local daemon_pid=${(P)daemon_pid_var} + local file_prefix=${(P)file_prefix_var} + + local cleanup=_gitstatus_cleanup_$name-$fsuf + local process=_gitstatus_process_response_$name-$fsuf + + if (( $+functions[$cleanup] )); then + add-zsh-hook -d zshexit $cleanup + unfunction -- $cleanup + fi + + if (( $+functions[$process] )); then + [[ -n $resp_fd ]] && zle -F $resp_fd + unfunction -- $process + fi + + [[ $daemon_pid == <1-> ]] && kill -- -$daemon_pid 2>/dev/null + [[ $file_prefix == /* ]] && zf_rm -f -- $file_prefix.lock $file_prefix.fifo + [[ $lock_fd == <1-> ]] && zsystem flock -u $lock_fd + [[ $req_fd == <1-> ]] && exec {req_fd}>&- + [[ $resp_fd == <1-> ]] && exec {resp_fd}>&- + + unset $state_var $req_fd_var $lock_fd_var $resp_fd_var $client_pid_var $daemon_pid_var + unset $inflight_var $file_prefix_var $dirty_max_index_size_var + + unset VCS_STATUS_RESULT + _gitstatus_clear$fsuf +} + +# Usage: gitstatus_check NAME. +# +# Returns 0 if and only if `gitstatus_start NAME` has succeeded previously. +# If it returns non-zero, gitstatus_query NAME is guaranteed to return non-zero. +function gitstatus_check"${1:-}"() { + emulate -L zsh -o no_aliases -o extended_glob -o typeset_silent + + local fsuf=${${(%):-%N}#gitstatus_check} + + if (( ARGC != 1 )); then + print -ru2 -- "gitstatus_check: exactly one positional argument is required" + return 1 + fi + + local name=$1 + if [[ $name != [[:IDENT:]]## ]]; then + print -ru2 -- "gitstatus_check: invalid positional argument: $name" + return 1 + fi + + (( _GITSTATUS_STATE_$name == 2 )) +} + +(( ${#_gitstatus_opts} )) && setopt ${_gitstatus_opts[@]} +'builtin' 'unset' '_gitstatus_opts' diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/gitstatus.prompt.sh b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/gitstatus.prompt.sh new file mode 100644 index 00000000..f54c11ac --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/gitstatus.prompt.sh @@ -0,0 +1,111 @@ +# Simple Bash prompt with Git status. + +# Source gitstatus.plugin.sh from $GITSTATUS_DIR or from the same directory +# in which the current script resides if the variable isn't set. +if [[ -n "${GITSTATUS_DIR-}" ]]; then + source "$GITSTATUS_DIR" || return +elif [[ "${BASH_SOURCE[0]}" == */* ]]; then + source "${BASH_SOURCE[0]%/*}/gitstatus.plugin.sh" || return +else + source gitstatus.plugin.sh || return +fi + +# Sets GITSTATUS_PROMPT to reflect the state of the current git repository. +# The value is empty if not in a git repository. Forwards all arguments to +# gitstatus_query. +# +# Example value of GITSTATUS_PROMPT: master ⇣42⇡42 ⇠42⇢42 *42 merge ~42 +42 !42 ?42 +# +# master current branch +# ⇣42 local branch is 42 commits behind the remote +# ⇡42 local branch is 42 commits ahead of the remote +# ⇠42 local branch is 42 commits behind the push remote +# ⇢42 local branch is 42 commits ahead of the push remote +# *42 42 stashes +# merge merge in progress +# ~42 42 merge conflicts +# +42 42 staged changes +# !42 42 unstaged changes +# ?42 42 untracked files +function gitstatus_prompt_update() { + GITSTATUS_PROMPT="" + + gitstatus_query "$@" || return 1 # error + [[ "$VCS_STATUS_RESULT" == ok-sync ]] || return 0 # not a git repo + + local reset=$'\001\e[0m\002' # no color + local clean=$'\001\e[38;5;076m\002' # green foreground + local untracked=$'\001\e[38;5;014m\002' # teal foreground + local modified=$'\001\e[38;5;011m\002' # yellow foreground + local conflicted=$'\001\e[38;5;196m\002' # red foreground + + local p + + local where # branch name, tag or commit + if [[ -n "$VCS_STATUS_LOCAL_BRANCH" ]]; then + where="$VCS_STATUS_LOCAL_BRANCH" + elif [[ -n "$VCS_STATUS_TAG" ]]; then + p+="${reset}#" + where="$VCS_STATUS_TAG" + else + p+="${reset}@" + where="${VCS_STATUS_COMMIT:0:8}" + fi + + (( ${#where} > 32 )) && where="${where:0:12}…${where: -12}" # truncate long branch names and tags + p+="${clean}${where}" + + # ⇣42 if behind the remote. + (( VCS_STATUS_COMMITS_BEHIND )) && p+=" ${clean}⇣${VCS_STATUS_COMMITS_BEHIND}" + # ⇡42 if ahead of the remote; no leading space if also behind the remote: ⇣42⇡42. + (( VCS_STATUS_COMMITS_AHEAD && !VCS_STATUS_COMMITS_BEHIND )) && p+=" " + (( VCS_STATUS_COMMITS_AHEAD )) && p+="${clean}⇡${VCS_STATUS_COMMITS_AHEAD}" + # ⇠42 if behind the push remote. + (( VCS_STATUS_PUSH_COMMITS_BEHIND )) && p+=" ${clean}⇠${VCS_STATUS_PUSH_COMMITS_BEHIND}" + (( VCS_STATUS_PUSH_COMMITS_AHEAD && !VCS_STATUS_PUSH_COMMITS_BEHIND )) && p+=" " + # ⇢42 if ahead of the push remote; no leading space if also behind: ⇠42⇢42. + (( VCS_STATUS_PUSH_COMMITS_AHEAD )) && p+="${clean}⇢${VCS_STATUS_PUSH_COMMITS_AHEAD}" + # *42 if have stashes. + (( VCS_STATUS_STASHES )) && p+=" ${clean}*${VCS_STATUS_STASHES}" + # 'merge' if the repo is in an unusual state. + [[ -n "$VCS_STATUS_ACTION" ]] && p+=" ${conflicted}${VCS_STATUS_ACTION}" + # ~42 if have merge conflicts. + (( VCS_STATUS_NUM_CONFLICTED )) && p+=" ${conflicted}~${VCS_STATUS_NUM_CONFLICTED}" + # +42 if have staged changes. + (( VCS_STATUS_NUM_STAGED )) && p+=" ${modified}+${VCS_STATUS_NUM_STAGED}" + # !42 if have unstaged changes. + (( VCS_STATUS_NUM_UNSTAGED )) && p+=" ${modified}!${VCS_STATUS_NUM_UNSTAGED}" + # ?42 if have untracked files. It's really a question mark, your font isn't broken. + (( VCS_STATUS_NUM_UNTRACKED )) && p+=" ${untracked}?${VCS_STATUS_NUM_UNTRACKED}" + + GITSTATUS_PROMPT="${p}${reset}" +} + +# Start gitstatusd in the background. +gitstatus_stop && gitstatus_start -s -1 -u -1 -c -1 -d -1 + +# On every prompt, fetch git status and set GITSTATUS_PROMPT. +if [[ -z "${PROMPT_COMMAND[*]}" ]]; then + PROMPT_COMMAND=gitstatus_prompt_update +elif [[ ! "${PROMPT_COMMAND[*]}" =~ [[:space:]\;]?gitstatus_prompt_update[[:space:]\;]? ]]; then + # Note: If PROMPT_COMMAND is an array, this will modify its first element. + PROMPT_COMMAND=$'gitstatus_prompt_update\n'"$PROMPT_COMMAND" +fi + +# Retain 3 trailing components of the current directory. +PROMPT_DIRTRIM=3 + +# Enable promptvars so that ${GITSTATUS_PROMPT} in PS1 is expanded. +shopt -s promptvars + +# Customize prompt. Put $GITSTATUS_PROMPT in it reflect git status. +# +# Example: +# +# user@host ~/projects/skynet master ⇡42 +# $ █ +PS1='\[\033[01;32m\]\u@\h\[\033[00m\] ' # green user@host +PS1+='\[\033[01;34m\]\w\[\033[00m\]' # blue current working directory +PS1+='${GITSTATUS_PROMPT:+ $GITSTATUS_PROMPT}' # git status (requires promptvars option) +PS1+='\n\[\033[01;$((31+!$?))m\]\$\[\033[00m\] ' # green/red (success/error) $/# (normal/root) +PS1+='\[\e]0;\u@\h: \w\a\]' # terminal title: user@host: dir diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/gitstatus.prompt.zsh b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/gitstatus.prompt.zsh new file mode 100644 index 00000000..6ad64856 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/gitstatus.prompt.zsh @@ -0,0 +1,111 @@ +# Simple Zsh prompt with Git status. + +# Source gitstatus.plugin.zsh from $GITSTATUS_DIR or from the same directory +# in which the current script resides if the variable isn't set. +source "${GITSTATUS_DIR:-${${(%):-%x}:h}}/gitstatus.plugin.zsh" || return + +# Sets GITSTATUS_PROMPT to reflect the state of the current git repository. Empty if not +# in a git repository. In addition, sets GITSTATUS_PROMPT_LEN to the number of columns +# $GITSTATUS_PROMPT will occupy when printed. +# +# Example: +# +# GITSTATUS_PROMPT='master ⇣42⇡42 ⇠42⇢42 *42 merge ~42 +42 !42 ?42' +# GITSTATUS_PROMPT_LEN=39 +# +# master current branch +# ⇣42 local branch is 42 commits behind the remote +# ⇡42 local branch is 42 commits ahead of the remote +# ⇠42 local branch is 42 commits behind the push remote +# ⇢42 local branch is 42 commits ahead of the push remote +# *42 42 stashes +# merge merge in progress +# ~42 42 merge conflicts +# +42 42 staged changes +# !42 42 unstaged changes +# ?42 42 untracked files +function gitstatus_prompt_update() { + emulate -L zsh + typeset -g GITSTATUS_PROMPT='' + typeset -gi GITSTATUS_PROMPT_LEN=0 + + # Call gitstatus_query synchronously. Note that gitstatus_query can also be called + # asynchronously; see documentation in gitstatus.plugin.zsh. + gitstatus_query 'MY' || return 1 # error + [[ $VCS_STATUS_RESULT == 'ok-sync' ]] || return 0 # not a git repo + + local clean='%76F' # green foreground + local modified='%178F' # yellow foreground + local untracked='%39F' # blue foreground + local conflicted='%196F' # red foreground + + local p + + local where # branch name, tag or commit + if [[ -n $VCS_STATUS_LOCAL_BRANCH ]]; then + where=$VCS_STATUS_LOCAL_BRANCH + elif [[ -n $VCS_STATUS_TAG ]]; then + p+='%f#' + where=$VCS_STATUS_TAG + else + p+='%f@' + where=${VCS_STATUS_COMMIT[1,8]} + fi + + (( $#where > 32 )) && where[13,-13]="…" # truncate long branch names and tags + p+="${clean}${where//\%/%%}" # escape % + + # ⇣42 if behind the remote. + (( VCS_STATUS_COMMITS_BEHIND )) && p+=" ${clean}⇣${VCS_STATUS_COMMITS_BEHIND}" + # ⇡42 if ahead of the remote; no leading space if also behind the remote: ⇣42⇡42. + (( VCS_STATUS_COMMITS_AHEAD && !VCS_STATUS_COMMITS_BEHIND )) && p+=" " + (( VCS_STATUS_COMMITS_AHEAD )) && p+="${clean}⇡${VCS_STATUS_COMMITS_AHEAD}" + # ⇠42 if behind the push remote. + (( VCS_STATUS_PUSH_COMMITS_BEHIND )) && p+=" ${clean}⇠${VCS_STATUS_PUSH_COMMITS_BEHIND}" + (( VCS_STATUS_PUSH_COMMITS_AHEAD && !VCS_STATUS_PUSH_COMMITS_BEHIND )) && p+=" " + # ⇢42 if ahead of the push remote; no leading space if also behind: ⇠42⇢42. + (( VCS_STATUS_PUSH_COMMITS_AHEAD )) && p+="${clean}⇢${VCS_STATUS_PUSH_COMMITS_AHEAD}" + # *42 if have stashes. + (( VCS_STATUS_STASHES )) && p+=" ${clean}*${VCS_STATUS_STASHES}" + # 'merge' if the repo is in an unusual state. + [[ -n $VCS_STATUS_ACTION ]] && p+=" ${conflicted}${VCS_STATUS_ACTION}" + # ~42 if have merge conflicts. + (( VCS_STATUS_NUM_CONFLICTED )) && p+=" ${conflicted}~${VCS_STATUS_NUM_CONFLICTED}" + # +42 if have staged changes. + (( VCS_STATUS_NUM_STAGED )) && p+=" ${modified}+${VCS_STATUS_NUM_STAGED}" + # !42 if have unstaged changes. + (( VCS_STATUS_NUM_UNSTAGED )) && p+=" ${modified}!${VCS_STATUS_NUM_UNSTAGED}" + # ?42 if have untracked files. It's really a question mark, your font isn't broken. + (( VCS_STATUS_NUM_UNTRACKED )) && p+=" ${untracked}?${VCS_STATUS_NUM_UNTRACKED}" + + GITSTATUS_PROMPT="${p}%f" + + # The length of GITSTATUS_PROMPT after removing %f and %F. + GITSTATUS_PROMPT_LEN="${(m)#${${GITSTATUS_PROMPT//\%\%/x}//\%(f|<->F)}}" +} + +# Start gitstatusd instance with name "MY". The same name is passed to +# gitstatus_query in gitstatus_prompt_update. The flags with -1 as values +# enable staged, unstaged, conflicted and untracked counters. +gitstatus_stop 'MY' && gitstatus_start -s -1 -u -1 -c -1 -d -1 'MY' + +# On every prompt, fetch git status and set GITSTATUS_PROMPT. +autoload -Uz add-zsh-hook +add-zsh-hook precmd gitstatus_prompt_update + +# Enable/disable the right prompt options. +setopt no_prompt_bang prompt_percent prompt_subst + +# Customize prompt. Put $GITSTATUS_PROMPT in it to reflect git status. +# +# Example: +# +# user@host ~/projects/skynet master ⇡42 +# % █ +# +# The current directory gets truncated from the left if the whole prompt doesn't fit on the line. +PROMPT='%70F%n@%m%f ' # green user@host +PROMPT+='%39F%$((-GITSTATUS_PROMPT_LEN-1))<…<%~%<<%f' # blue current working directory +PROMPT+='${GITSTATUS_PROMPT:+ $GITSTATUS_PROMPT}' # git status +PROMPT+=$'\n' # new line +PROMPT+='%F{%(?.76.196)}%#%f ' # %/# (normal/root); green/red (ok/error) diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/install b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/install new file mode 100755 index 00000000..76f339e0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/install @@ -0,0 +1,476 @@ +#!/bin/sh +# +# This script does not have a stable API. + +_gitstatus_install_daemon_found() { + local installed="$1" + shift + [ $# = 0 ] || "$@" "$daemon" "$version" "$installed" +} + +_gitstatus_install_main() { + if [ -n "${ZSH_VERSION:-}" ]; then + emulate -L sh -o no_unset + else + set -u + fi + + local argv1="$1" + shift + + local no_check= no_install= uname_s= uname_m= gitstatus_dir= dl_status= e= + local opt= OPTARG= OPTIND=1 + + while getopts ':s:m:d:p:e:fnh' opt "$@"; do + case "$opt" in + h) + command cat <<\END +Usage: install [-s KERNEL] [-m ARCH] [-d DIR] [-p CMD] [-e ERRFD] [-f|-n] [-- CMD [ARG]...] + +If positional arguments are specified, call this on success: + + CMD [ARG]... DAEMON VERSION INSTALLED + +DAEMON is path to gitstatusd. VERSION is a glob pattern for the +version this daemon should support; it's supposed to be passed as +-G to gitstatusd. INSTALLED is 1 if gitstatusd has just been +downloaded and 0 otherwise. + +Options: + + -s KERNEL use this instead of lowercase `uname -s` + -m ARCH use this instead of lowercase `uname -m` + -d DIR use this instead of `dirname "$0"` + -p CMD eval this every second while downloading gitstatusd + -e ERRFD write error messages to this file descriptor + -f download gitstatusd even if there is one locally + -n do not download gitstatusd (fail instead) +END + return + ;; + n) + if [ -n "$no_install" ]; then + >&2 echo "[gitstatus] error: duplicate option: -$opt" + return 1 + fi + no_install=1 + ;; + f) + if [ -n "$no_check" ]; then + >&2 echo "[gitstatus] error: duplicate option: -$opt" + return 1 + fi + no_check=1 + ;; + d) + if [ -n "$gitstatus_dir" ]; then + >&2 echo "[gitstatus] error: duplicate option: -$opt" + return 1 + fi + if [ -z "$OPTARG" ]; then + >&2 echo "[error] incorrect value of -$opt: $OPTARG" + return 1 + fi + gitstatus_dir="$OPTARG" + ;; + p) + if [ -n "$dl_status" ]; then + >&2 echo "[gitstatus] error: duplicate option: -$opt" + return 1 + fi + if [ -z "$OPTARG" ]; then + >&2 echo "[error] incorrect value of -$opt: $OPTARG" + return 1 + fi + dl_status="$OPTARG" + ;; + e) + if [ -n "$e" ]; then + >&2 echo "[gitstatus] error: duplicate option: -$opt" + return 1 + fi + if [ -z "$OPTARG" ]; then + >&2 echo "[error] incorrect value of -$opt: $OPTARG" + return 1 + fi + e="$OPTARG" + ;; + m) + if [ -n "$uname_m" ]; then + >&2 echo "[gitstatus] error: duplicate option: -$opt" + return 1 + fi + if [ -z "$OPTARG" ]; then + >&2 echo "[error] incorrect value of -$opt: $OPTARG" + return 1 + fi + uname_m="$OPTARG" + ;; + s) + if [ -n "$uname_s" ]; then + >&2 echo "[gitstatus] error: duplicate option: -$opt" + return 1 + fi + if [ -z "$OPTARG" ]; then + >&2 echo "[error] incorrect value of -$opt: $OPTARG" + return 1 + fi + uname_s="$OPTARG" + ;; + \?) >&2 echo "[gitstatus] error: invalid option: -$OPTARG" ; return 1;; + :) >&2 echo "[gitstatus] error: missing required argument: -$OPTARG"; return 1;; + *) >&2 echo "[gitstatus] internal error: unhandled option: -$opt" ; return 1;; + esac + done + + shift "$((OPTIND - 1))" + + : "${e:=2}" + : "${gitstatus_dir:=$argv1}" + + if [ -n "$no_check" -a -n "$no_install" ]; then + >&2 echo "[gitstatus] error: incompatible options: -f, -n" + return 1 + fi + + if [ -z "$uname_s" ]; then + uname_s="$(command uname -s)" || return + uname_s="$(printf '%s' "$uname_s" | command tr '[A-Z]' '[a-z]')" || return + fi + if [ -z "$uname_m" ]; then + uname_m="$(command uname -m)" || return + uname_m="$(printf '%s' "$uname_m" | command tr '[A-Z]' '[a-z]')" || return + fi + + local daemon="${GITSTATUS_DAEMON:-}" + local cache_dir="${GITSTATUS_CACHE_DIR:-${XDG_CACHE_HOME:-$HOME/.cache}/gitstatus}" + + if [ -z "$no_check" ]; then + if [ -n "${daemon##/*}" ]; then + >&2 echo "[gitstatus] error: GITSTATUS_DAEMON is not absolute path: $daemon" + return 1 + fi + if [ -z "$daemon" -a -e "$gitstatus_dir"/usrbin/gitstatusd ]; then + daemon="$gitstatus_dir"/usrbin/gitstatusd + fi + if [ -n "$daemon" ]; then + local gitstatus_version= libgit2_version= + if ! . "$gitstatus_dir"/build.info; then + >&2 echo "[gitstatus] internal error: failed to source build.info" + return 1 + fi + if [ -z "$gitstatus_version" ]; then + >&2 echo "[gitstatus] internal error: empty gitstatus_version in build.info" + return 1 + fi + local version="$gitstatus_version" + _gitstatus_install_daemon_found 0 "$@" + return + fi + fi + + while IFS= read -r line; do + line="${line###*}" + [ -n "$line" ] || continue + + local uname_s_glob= uname_m_glob= file= version= sha256= + eval "$line" || return + + if [ -z "$uname_s_glob" -o \ + -z "$uname_m_glob" -o \ + -z "$file" -o \ + -z "$version" -o \ + -z "$sha256" ]; then + >&2 echo "[gitstatus] internal error: invalid install.info line: $line" + return 1 + fi + + case "$uname_s" in + $uname_s_glob) ;; + *) continue;; + esac + case "$uname_m" in + $uname_m_glob) ;; + *) continue;; + esac + + # Found a match. The while loop will terminate during this iteration. + + if [ -z "$no_check" ]; then + # Check if a suitable gitstatusd already exists. + local daemon="$gitstatus_dir"/usrbin/"$file" + if [ ! -e "$daemon" ]; then + daemon="$cache_dir"/"$file" + [ -e "$daemon" ] || daemon= + fi + if [ -n "$daemon" ]; then + _gitstatus_install_daemon_found 0 "$@" + return + fi + fi + + # No suitable gitstatusd exists. Need to download. + + if [ -n "$no_install" ]; then + >&2 echo "[gitstatus] error: no gitstatusd found and installation is disabled" + return 1 + fi + + local daemon="$cache_dir"/"$file" + + if [ -n "${cache_dir##/*}" ]; then + >&2 echo "[gitstatus] error: GITSTATUS_CACHE_DIR is not absolute: $cache_dir" + return 1 + fi + if [ ! -d "$cache_dir" ] && ! mkdir -p -- "$cache_dir" || [ ! -w "$cache_dir" ]; then + local dir="$cache_dir" + while true; do + if [ -e "$dir" ]; then + if [ ! -d "$dir" ]; then + >&"$e" printf 'Not a directory: \033[4;31m%s\033[0m\n' "$dir" + >&"$e" printf '\n' + >&"$e" printf 'Delete it, then restart your shell.\n' + elif [ ! -w "$dir" ]; then + >&"$e" printf 'Directory is not writable: \033[4;31m%s\033[0m\n' "$dir" + >&"$e" printf '\n' + >&"$e" printf 'Make it writable, then restart your shell.\n' + fi + break + fi + if [ "$dir" = / ] || [ "$dir" = . ]; then + break + fi + dir="$(dirname -- "$dir")" + done + return 1 + fi + + if [ -n "${TMPDIR-}" -a '(' '(' -d "${TMPDIR-}" -a -w "${TMPDIR-}" ')' -o '!' '(' -d /tmp -a -w /tmp ')' ')' ]; then + local tmp="$TMPDIR" + else + local tmp=/tmp + fi + if ! command -v mktemp >/dev/null 2>&1 || + ! tmpdir="$(command mktemp -d "$tmp"/gitstatus-install.XXXXXXXXXX)"; then + tmpdir="$tmp/gitstatus-install.tmp.$$" + if ! mkdir -p -- "$tmpdir"; then + if [ "$tmp" = /tmp ]; then + local label='directory' + else + local label='directory (\033[1mTMPDIR\033[m)' + fi + if [ ! -e "$tmp" ]; then + >&"$e" printf 'Temporary '"$label"' does not exist: \033[4;31m%s\033[0m\n' "$tmp" + >&"$e" printf '\n' + >&"$e" printf 'Create it, then restart your shell.\n' + elif [ ! -d "$tmp" ]; then + >&"$e" printf 'Not a '"$label"': \033[4;31m%s\033[0m\n' "$tmp" + >&"$e" printf '\n' + >&"$e" printf 'Make it a directory, then restart your shell.\n' + elif [ ! -w "$tmp" ]; then + >&"$e" printf 'Temporary '"$label"' is not writable: \033[4;31m%s\033[0m\n' "$tmp" + >&"$e" printf '\n' + >&"$e" printf 'Make it writable, then restart your shell.\n' + fi + return 1 + fi + fi + + if ! command -v curl >/dev/null 2>&1 && ! command -v wget >/dev/null 2>&1; then + >&"$e" printf 'Please install \033[32mcurl\033[0m or \033[32mwget\033[0m, then restart your shell.\n' + return 1 + fi + + ( + run_cmd() { + command -v "$1" >/dev/null 2>/dev/null || return 127 + local trapped= pid die ret + trap 'trapped=1' $sig + # The only reason for suppressing stderr is that `curl -f` cannot be silenced: + # `-s` doesn't work despite what the docs say. + command "$@" 2>/dev/null & + ret="$?" + if [ "$ret" = 0 ]; then + pid="$!" + die="trap - $sig; kill -- $pid 2>/dev/null; wait -- $pid 2>/dev/null; exit 1" + trap "$die" $sig + [ -z "$trapped" ] || eval "$die" + wait -- "$pid" 2>/dev/null + ret="$?" + fi + trap - $sig + [ -z "$trapped" ] || exit + return "$ret" + } + + check_sha256() { + local data_file="$tmpdir"/"$1".tar.gz + local hash_file="$tmpdir"/"$1".tar.gz.sha256 + local hash= + { + command -v shasum >/dev/null 2>/dev/null && + run_cmd shasum -b -a 256 -- "$data_file" >"$hash_file" /dev/null 2>/dev/null && + run_cmd sha256sum -b -- "$data_file" >"$hash_file" /dev/null 2>/dev/null && + run_cmd sha256 -- "$data_file" >"$hash_file" /dev/null 2>/dev/null; then + if ! run_cmd sleep "$1"; then + echo -n >"$tmpdir"/"$1".status + return 1 + fi + fi + local cmd part url ret + for cmd in 'curl -kfsSL' 'wget -qO-' 'curl -q -kfsSL' 'wget --no-config -qO-'; do + part=0 + while true; do + if [ "$part" = 2 ]; then + ret=1 + break + elif [ "$part" = 0 ]; then + url="$2" + else + url="$2"."$part" + fi + run_cmd $cmd -- "$url" >>"$tmpdir"/"$1".tar.gz + ret="$?" + [ "$ret" = 0 ] || break + check_sha256 "$1" && break + part=$((part+1)) + done + [ "$ret" = 0 ] && break + run_cmd rm -f -- "$tmpdir"/"$1".tar.gz && continue + ret="$?" + break + done + echo -n >"$tmpdir"/"$1".status + return "$ret" + } + + local trapped= + trap 'trapped=1' $sig + fetch 1 "$url1" & + local pid1="$!" + fetch 2 "$url2" & + local pid2="$!" + + local die="trap - $sig; kill -- $pid1 $pid2 2>/dev/null; wait -- $pid1 $pid2 2>/dev/null; exit 1" + trap "$die" $sig + [ -z "$trapped" ] || eval "$die" + + local n= + while true; do + [ -z "$dl_status" ] || eval "$dl_status" || eval "$die" + if command -v sleep >/dev/null 2>/dev/null; then + command sleep 1 + elif command -v true >/dev/null 2>/dev/null; then + command true + fi + if [ -n "$pid1" -a -e "$tmpdir"/1.status ]; then + wait -- "$pid1" 2>/dev/null + local ret="$?" + pid1= + if [ "$ret" = 0 ]; then + if [ -n "$pid2" ]; then + kill -- "$pid2" 2>/dev/null + wait -- "$pid2" 2>/dev/null + fi + n=1 + break + elif [ -z "$pid2" ]; then + break + else + die="trap - $sig; kill -- $pid2 2>/dev/null; wait -- $pid2 2>/dev/null; exit 1" + trap "$die" $sig + fi + elif [ -n "$pid2" -a -e "$tmpdir"/2.status ]; then + wait -- "$pid2" 2>/dev/null + local ret="$?" + pid2= + if [ "$ret" = 0 ]; then + if [ -n "$pid1" ]; then + kill -- "$pid1" 2>/dev/null + wait -- "$pid1" 2>/dev/null + fi + n=2 + break + elif [ -z "$pid1" ]; then + break + else + die="trap - $sig; kill -- $pid1 2>/dev/null; wait -- $pid1 2>/dev/null; exit 1" + trap "$die" $sig + fi + fi + done + + trap - $sig + + if [ -z "$n" ]; then + >&"$e" printf 'Failed to download \033[32m%s\033[0m from any mirror:\n' "$file" + >&"$e" printf '\n' + >&"$e" printf ' 1. \033[4m%s\033[0m\n' "$url1" + >&"$e" printf ' 2. \033[4m%s\033[0m\n' "$url2" + >&"$e" printf '\n' + >&"$e" printf 'Check your internet connection, then restart your shell.\n' + exit 1 + fi + + command tar -C "$tmpdir" -xzf "$tmpdir"/"$n".tar.gz || exit + + local tmpfile + if ! command -v mktemp >/dev/null 2>&1 || + ! tmpfile="$(command mktemp "$cache_dir"/gitstatusd.XXXXXXXXXX)"; then + tmpfile="$cache_dir"/gitstatusd.tmp.$$ + fi + + command mv -f -- "$tmpdir"/"$file" "$tmpfile" || exit + command mv -f -- "$tmpfile" "$cache_dir"/"$file" && exit + command rm -f -- "$cache_dir"/"$file" + command mv -f -- "$tmpfile" "$cache_dir"/"$file" && exit + command rm -f -- "$tmpfile" + exit 1 + ) + + local ret="$?" + command rm -rf -- "$tmpdir" + [ "$ret" = 0 ] || return + + _gitstatus_install_daemon_found 1 "$@" + return + done <"$gitstatus_dir"/install.info + + >&"$e" printf 'There is no prebuilt \033[32mgitstatusd\033[0m for \033[1m%s\033[0m.\n' "$uname_s $uname_m" + >&"$e" printf '\n' + >&"$e" printf 'See: \033[4mhttps://github.com/romkatv/gitstatus#compiling\033[0m\n' + return 1 +} + +if [ -z "${0##*/*}" ]; then + _gitstatus_install_main "${0%/*}" "$@" +else + _gitstatus_install_main . "$@" +fi diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/install.info b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/install.info new file mode 100644 index 00000000..45807be4 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/install.info @@ -0,0 +1,34 @@ +# 3 +# +# This file is used by ./install and indirectly by shell bindings. +# +# The first line is read by powerlevel10k instant prompt. It must +# be updated whenever the content of this file changes. The actual +# value doesn't matter as long as it's unique. Consecutive integers +# work fine. + +# Official gitstatusd binaries. +uname_s_glob="cygwin_nt-10.0"; uname_m_glob="i686"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.4"; sha256="5a8a809dcebdb6aa9b47d37e086c0485424a9d9c136770eec3c26cedf5bb75e3"; +uname_s_glob="cygwin_nt-10.0"; uname_m_glob="x86_64"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.1"; sha256="c84cade0d6b86e04c27a6055f45851f6b46d6b88ba58772f7ca8ef4d295c800f"; +uname_s_glob="darwin"; uname_m_glob="arm64"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.4"; sha256="eae979e990ca37c56ee39fadd0c3f392cbbd0c6bdfb9a603010be60d9e48910a"; +uname_s_glob="darwin"; uname_m_glob="x86_64"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.4"; sha256="9fd3913ec1b6b856ab6e08a99a2343f0e8e809eb6b62ca4b0963163656c668e6"; +uname_s_glob="freebsd"; uname_m_glob="amd64"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.4"; sha256="8e57ad642251e5acfa430aed82cd4ffe103db0bfadae4a15ccaf462c455d0442"; +uname_s_glob="linux"; uname_m_glob="aarch64"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.4"; sha256="32b57eb28bf6d80b280e4020a0045184f8ca897b20b570c12948aa6838673225"; +uname_s_glob="linux"; uname_m_glob="armv6l"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.1"; sha256="4bf5a0d0a082f544a48536ad3675930d5d2cc6a8cf906710045e0788f51192b3"; +uname_s_glob="linux"; uname_m_glob="armv7l"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.1"; sha256="2b9deb29f86c8209114b71b94fc2e1ed936a1658808a1bee46f4a82fd6a1f8cc"; +uname_s_glob="linux"; uname_m_glob="armv8l"; file="gitstatusd-${uname_s}-aarch64"; version="v1.5.4"; sha256="32b57eb28bf6d80b280e4020a0045184f8ca897b20b570c12948aa6838673225"; +uname_s_glob="linux"; uname_m_glob="i686"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.4"; sha256="56d55e2e9a202d3072fa612d8fa1faa61243ffc86418a7fa64c2c9d9a82e0f64"; +uname_s_glob="linux"; uname_m_glob="ppc64le"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.4"; sha256="1afd072c8c26ef6ec2d9ac11cef96c84cd6f10e859665a6ffcfb6112c758547e"; +uname_s_glob="linux"; uname_m_glob="x86_64"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.4"; sha256="9633816e7832109e530c9e2532b11a1edae08136d63aa7e40246c0339b7db304"; +uname_s_glob="msys_nt-10.0"; uname_m_glob="i686"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.1"; sha256="7f9b849fc52e7a95b9b933e25121ad5ae990a1871aad6616922ad7bcf1eebf20"; +uname_s_glob="msys_nt-10.0"; uname_m_glob="x86_64"; file="gitstatusd-${uname_s}-${uname_m}"; version="v1.5.1"; sha256="5d3c626b5ee564dbc13ddba89752dc58b0efe925b26dbd8b2304849d9ba01732"; + +# Fallbacks to official gitstatusd binaries. +uname_s_glob="cygwin_nt-*"; uname_m_glob="i686"; file="gitstatusd-cygwin_nt-10.0-${uname_m}"; version="v1.5.2"; sha256="5a8a809dcebdb6aa9b47d37e086c0485424a9d9c136770eec3c26cedf5bb75e3"; +uname_s_glob="cygwin_nt-*"; uname_m_glob="x86_64"; file="gitstatusd-cygwin_nt-10.0-${uname_m}"; version="v1.5.1"; sha256="c84cade0d6b86e04c27a6055f45851f6b46d6b88ba58772f7ca8ef4d295c800f"; +uname_s_glob="mingw32_nt-*"; uname_m_glob="i686"; file="gitstatusd-msys_nt-10.0-${uname_m}"; version="v1.5.1"; sha256="7f9b849fc52e7a95b9b933e25121ad5ae990a1871aad6616922ad7bcf1eebf20"; +uname_s_glob="mingw32_nt-*"; uname_m_glob="x86_64"; file="gitstatusd-msys_nt-10.0-${uname_m}"; version="v1.5.1"; sha256="5d3c626b5ee564dbc13ddba89752dc58b0efe925b26dbd8b2304849d9ba01732"; +uname_s_glob="mingw64_nt-*"; uname_m_glob="i686"; file="gitstatusd-msys_nt-10.0-${uname_m}"; version="v1.5.1"; sha256="7f9b849fc52e7a95b9b933e25121ad5ae990a1871aad6616922ad7bcf1eebf20"; +uname_s_glob="mingw64_nt-*"; uname_m_glob="x86_64"; file="gitstatusd-msys_nt-10.0-${uname_m}"; version="v1.5.1"; sha256="5d3c626b5ee564dbc13ddba89752dc58b0efe925b26dbd8b2304849d9ba01732"; +uname_s_glob="msys_nt-*"; uname_m_glob="i686"; file="gitstatusd-msys_nt-10.0-${uname_m}"; version="v1.5.1"; sha256="7f9b849fc52e7a95b9b933e25121ad5ae990a1871aad6616922ad7bcf1eebf20"; +uname_s_glob="msys_nt-*"; uname_m_glob="x86_64"; file="gitstatusd-msys_nt-10.0-${uname_m}"; version="v1.5.1"; sha256="5d3c626b5ee564dbc13ddba89752dc58b0efe925b26dbd8b2304849d9ba01732"; diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/mbuild b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/mbuild new file mode 100755 index 00000000..40316fdf --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/mbuild @@ -0,0 +1,406 @@ +#!/usr/bin/env zsh +# +# This script does not have a stable API. +# +# Usage: mbuild [-b git-ref] [kernel-arch]... +# +# Builds a bunch of gitstatusd-* binaries. Without arguments builds binaries +# for all platforms. git-ref defaults to master. +# +# Before using this script you need to set up build servers and list them +# in ~/.ssh/config. There should be a Host entry for every value of `assets` +# association defined below. VMs and cloud instances work as well as physical +# machines, including localhost. As long as the machine has been set up as +# described below and you can SSH to it without password, it should work. +# +# ===[ Build Server Setup ]=== +# +# Linux +# +# - Install docker. +# $ apt install docker.io # adjust appropriately if there is no `apt` +# $ usermod -aG docker $USER # not needed if going to build as root +# - Install git. +# $ apt install git # adjust appropriately if there is no `apt` +# +# macOS +# +# - Install compiler tools: +# $ xcode-select --install +# - Install homebrew: https://brew.sh/. +# $ bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install.sh)" +# +# FreeBSD +# +# - Install git. +# $ pkg install git +# +# Windows +# +# - Disable Windows Defender (optional). +# ps> Set-MpPreference -DisableRealtimeMonitoring $true +# - Install 64-bit and 32-bit msys2: https://www.msys2.org/wiki/MSYS2-installation/. +# - Open each of them after installation, type `pacman -Syu --noconfirm` and close the window. +# - Then run in powershell while having no msys2 or cygwin windows open: +# ps> C:\msys32\autorebase.bat +# ps> C:\msys64\autorebase.bat +# - Install 64-bit and 32-bit cygwin: https://cygwin.com/install.html. +# - Choose to install 32-bit to c:/cygwin32 instead of the default c:/cygwin. +# - Select these packages: binutils, cmake, gcc-core, gcc-g++, git, make, perl, wget. +# +# IMPORTANT: Install msys2 and cygwin one at a time. +# +# IMPORTANT: msys2 builder can reboot the build machine. +# +# Option 1: OpenSSH for Windows +# +# - Install OpenSSH: https://docs.microsoft.com/en-us/windows-server/administration/openssh/openssh_install_firstuse. +# ps> Add-WindowsCapability -Online -Name OpenSSH.Server~~~~0.0.1.0 +# ps> Start-Service sshd +# ps> Set-Service -Name sshd -StartupType 'Automatic' +# - Enable publickey authentication: https://stackoverflow.com/a/50502015/1095235. +# ps> cd $env:USERPROFILE +# ps> mkdir .ssh +# ps> notepad.exe .ssh/authorized_keys +# - Paste your public key, save, close. +# ps> icacls .ssh/authorized_keys /inheritance:r +# ps> notepad.exe C:\ProgramData\ssh\sshd_config +# - Comment out these two lines, save, close: +# # Match Group administrators +# # AuthorizedKeysFile __PROGRAMDATA__/ssh/administrators_authorized_keys +# ps> Restart-Service sshd +# +# Option 2: OpenSSH from WSL +# +# - Install WSL. +# - Install Ubuntu. +# - Install sshd. +# $ apt install openssh-server +# $ dpkg-reconfigure openssh-server +# $ cat >/etc/ssh/sshd_config <<\END +# ClientAliveInterval 60 +# AcceptEnv TERM LANG LC_* +# PermitRootLogin no +# AllowTcpForwarding no +# AllowAgentForwarding no +# AllowStreamLocalForwarding no +# AuthenticationMethods publickey +# END +# service ssh --full-restart +# - Add your public ssh key to ~/.ssh/authorized_keys. +# - Make `sshd` start when Windows boots. + +'emulate' '-L' 'zsh' '-o' 'no_aliases' '-o' 'err_return' +setopt no_unset extended_glob pipe_fail prompt_percent typeset_silent \ + no_prompt_subst no_prompt_bang pushd_silent warn_create_global + +if [[ $ZSH_VERSION != (5.<1->*|<6->.*) || $ZSH_VERSION == 5.4(|.*) ]]; then + print -ru2 -- "[error] unsupported zsh version: $ZSH_VERSION" + return 1 +fi + +zmodload zsh/system + +local -r git_url='https://github.com/romkatv/gitstatus.git' + +local -rA assets=( + # target kernel-arch hostname of the build machine + cygwin_nt-10.0-i686 build-windows-x86_64 + cygwin_nt-10.0-x86_64 build-windows-x86_64 + msys_nt-10.0-i686 build-windows-x86_64 + msys_nt-10.0-x86_64 build-windows-x86_64 + darwin-arm64 build-macos-arm64 + darwin-x86_64 build-macos-x86_64 + freebsd-amd64 build-freebsd-amd64 + linux-aarch64 build-linux-aarch64 + linux-armv6l build-linux-armv7l + linux-armv7l build-linux-armv7l + linux-i686 build-linux-x86_64 + linux-ppc64le build-linux-ppc64le + linux-x86_64 build-linux-x86_64 +) + +local -rA protocol=( + 'cygwin_nt-10.0-*' windows + 'msys_nt-10.0-*' windows + 'darwin-*' unix + 'freebsd-*' unix + 'linux-*' unix +) + +local -r rootdir=${ZSH_SCRIPT:h} +local -r logs=$rootdir/logs +local -r locks=$rootdir/locks +local -r binaries=$rootdir/usrbin + +function usage() { + print -r -- 'usage: mbuild [-b REF] [KERNEL-ARCH]...' +} + +local OPTARG opt git_ref=master +local -i OPTIND +while getopts ":b:h" opt; do + case $opt in + h) usage; return 0;; + b) [[ -n $OPTARG ]]; git_ref=$OPTARG;; + \?) print -ru2 -- "mbuild: invalid option: -$OPTARG" ; return 1;; + :) print -ru2 -- "mbuild: missing required argument: -$OPTARG"; return 1;; + *) print -ru2 -- "mbuild: invalid option: -$opt" ; return 1;; + esac +done + +shift $((OPTIND - 1)) + +(( $# )) || set -- ${(ko)assets} +set -- ${(u)@} + +local platform +for platform; do + if (( ! $+assets[$platform] )); then + print -ru2 -- "mbuild: invalid platform: $platform" + return 1 + fi +done + +local build=' + rm -rf gitstatus + git clone --recursive --shallow-submodules --depth=1 -b '$git_ref' '$git_url' + cd gitstatus + if command -v zsh >/dev/null 2>&1; then + sh=zsh + elif command -v dash >/dev/null 2>&1; then + sh=dash + elif command -v ash >/dev/null 2>&1; then + sh=ash + else + sh=sh + fi + $sh -x ./build -m ' + +function build-unix() { + local intro flags=(-sw) + case $2 in + linux-ppc64le) ;; + linux-*) flags+=(-d docker);; + darwin-arm64) intro='PATH="/opt/homebrew/bin:$PATH"';; + darwin-*) intro='PATH="/usr/local/bin:$PATH"';; + esac + ssh $1 -- /bin/sh -uex <<<" + $intro + cd /tmp + $build ${2##*-} ${(j: :)${(@q)flags}}" + scp $1:/tmp/gitstatus/usrbin/gitstatusd $binaries/gitstatusd-$2 +} + +function build-windows() { + local shell=$(ssh $1 'echo $0') + if [[ $shell == '$0'* ]]; then + local c='c:' + else + local c='/mnt/c' + fi + + local tmp env bin intro flags=(-w) + case $2 in + cygwin_nt-10.0-i686) bin='cygwin32/bin' ;| + cygwin_nt-10.0-x86_64) bin='cygwin64/bin' ;| + msys_nt-10.0-i686) bin='msys32/usr/bin';| + msys_nt-10.0-x86_64) bin='msys64/usr/bin';| + cygwin_nt-10.0-*) + tmp='/cygdrive/c/tmp' + ;| + msys_nt-10.0-*) + tmp='/c/tmp' + env='MSYSTEM=MSYS' + # TODO: fix this (some errors about PGP keys). + # flags+=(-s) + # intro='pacman -S --needed --noconfirm git; ' + intro+='PATH="$PATH:/usr/bin/site_perl:/usr/bin/vendor_perl:/usr/bin/core_perl"' + while true; do + # TODO: run autorebase only when getting an error that can be fixed by autorebasing. + break + local out + out="$(ssh $1 cmd.exe "$c/${bin%%/*}/autorebase.bat" 2>&1)" + [[ $out == *"The following DLLs couldn't be rebased"* ]] || break + # Reboot to get rid of whatever is using those DLLs. + ssh $1 powershell.exe <<<'Restart-Computer -Force' || true + sleep 30 + while ! ssh $1 <<<''; do sleep 5; done + done + () { + while true; do + # TODO: fix this (some errors about PGP keys). + break + local -i fd + exec {fd}< <( + ssh $1 $c/$bin/env.exe $env c:/$bin/bash.exe -l 2>&1 <<<" + pacman -Syu --noconfirm + exit") + { + local line + while true; do + IFS= read -u $fd -r line || return 0 + if [[ $line == *"warning: terminate MSYS2"* ]]; then + # At this point the machine is hosed. A rogue process with a corrupted name + # is eating all CPU. The top SSH connection won't terminate on its own. + ssh $1 powershell.exe <<<'Restart-Computer -Force' || true + sleep 30 + while ! ssh $1 <<<''; do sleep 5; done + break + fi + done + } always { + exec {fd}<&- + kill -- -$sysparams[procsubstpid] 2>/dev/null || true + } + done + } "$@" + ;| + esac + + ssh $1 $c/$bin/env.exe $env c:/$bin/bash.exe -l <<<" + set -uex + $intro + mkdir -p -- $tmp + cd -- $tmp + $build ${2##*-} ${(j: :)${(@q)flags}} + exit" + scp $1:$c/tmp/gitstatus/usrbin/gitstatusd $binaries/gitstatusd-$2 + chmod +x $binaries/gitstatusd-$2 +} + +if [[ -r /proc/version && "$(/dev/null + ( + trap '' TERM PIPE + local fd + while true; do + sysopen -wo create,excl -u fd -- $1 && break + sleep 1 + done + exec {fd}>&- + while true; do + print || break + done + rm -- $1 + ) &! + ) + local REPLY + IFS= read -ru $fd + } +else + function flock() { + : >>$1 + zsystem flock $1 + } +fi + +function build() ( + setopt xtrace + local platform=$1 + local machine=$assets[$platform] + flock $locks/$machine + build-${protocol[(k)$platform]} $machine $platform + local tmp=gitstatusd-$platform.tmp.$$.tar.gz + ( cd -q -- $binaries; tar --owner=0 --group=0 -I 'gzip -9' -cf $tmp gitstatusd-$platform ) + mv -f -- $binaries/$tmp $binaries/gitstatusd-$platform.tar.gz + # Make sure the last command is a built-in (important for flock). + : +) + +function mbuild() { + local platform pid pids=() + for platform; do + build $platform &>$logs/$platform & + print -r -- "starting build for $platform on $assets[$platform] (pid $!)" + pids+=($platform $!) + done + local failed=() + for platform pid in $pids; do + print -rn -- "$platform => " + if wait $pid; then + print -r -- "ok" + else + print -r -- "error" + failed+=$platform + fi + done + (( $#failed )) || return 0 + print + print -r -- "Error logs:" + print + for platform in $failed; do + print -r -- " $platform => $logs/$platform" + done + return 1 +} + +# Copied from https://github.com/romkatv/run-process-tree. +function run-process-tree() { + zmodload zsh/parameter zsh/param/private || return + local -P opt=(${(kv)options[@]}) || return + local -P pat=(${patchars[@]}) || return + local -P dis_pat=(${dis_patchars[@]}) || return + emulate -L zsh -o err_return || return + setopt monitor traps_async pipe_fail no_unset + zmodload zsh/system + + if (( $# == 0 )); then + print -ru2 -- 'usage: run-process-tree command [arg]...' + return 1 + fi + + local -P stdout REPLY + exec {stdout}>&1 + { + { + local -Pi pipe + local -P gid=$sysparams[pid] + local -P sig=(ABRT EXIT HUP ILL INT PIPE QUIT TERM ZERR) + local -P trap=(trap "trap - $sig; kill -- -$sysparams[pid]" $sig) + + exec {pipe}>&1 1>&$stdout + $trap + + { + $trap + while sleep 1 && print -u $pipe .; do; done + } 2>/dev/null & + local -Pi watchdog=$! + + { + trap - ZERR + exec {pipe}>&- + enable -p -- $pat + disable -p -- $dis_pat + options=($opt zle off monitor off) + "$@" + } & + local -Pi ret + wait $! || ret=$? + + trap "exit $ret" TERM + kill $watchdog + wait $watchdog + return ret + } | while read; do; done || return + } always { + exec {stdout}>&- + } +} + +mkdir -p -- $logs $locks $binaries + +() { + run-process-tree mbuild $@ + exit +} "$@" diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/src/algorithm.h b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/src/algorithm.h new file mode 100644 index 00000000..b87b13f0 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/src/algorithm.h @@ -0,0 +1,37 @@ +// Copyright 2019 Roman Perepelitsa. +// +// This file is part of GitStatus. +// +// GitStatus is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// GitStatus is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with GitStatus. If not, see . + +#ifndef ROMKATV_GITSTATUS_ALGORITHM_H_ +#define ROMKATV_GITSTATUS_ALGORITHM_H_ + +#include + +namespace gitstatus { + +// Requires: Iter is a BidirectionalIterator. +// +// Returns iterator pointing to the last value in [begin, end) that compares equal to the value, or +// begin if none compare equal. +template +Iter FindLast(Iter begin, Iter end, const T& val) { + while (begin != end && !(*--end == val)) {} + return end; +} + +} // namespace gitstatus + +#endif // ROMKATV_GITSTATUS_ALGORITHM_H_ diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/src/arena.cc b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/src/arena.cc new file mode 100644 index 00000000..4c137639 --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/src/arena.cc @@ -0,0 +1,118 @@ +// Copyright 2019 Roman Perepelitsa. +// +// This file is part of GitStatus. +// +// GitStatus is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// GitStatus is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with GitStatus. If not, see . + +#include "arena.h" + +#include +#include + +#include "bits.h" +#include "check.h" + +namespace gitstatus { + +namespace { + +size_t Clamp(size_t min, size_t val, size_t max) { return std::min(max, std::max(min, val)); } + +static const uintptr_t kSingularity = reinterpret_cast(&kSingularity); + +} // namespace + +// Triple singularity. We are all fucked. +Arena::Block Arena::g_empty_block = {kSingularity, kSingularity, kSingularity}; + +Arena::Arena(Arena::Options opt) : opt_(std::move(opt)), top_(&g_empty_block) { + CHECK(opt_.min_block_size <= opt_.max_block_size); +} + +Arena::Arena(Arena&& other) : Arena() { *this = std::move(other); } + +Arena::~Arena() { + // See comments in Makefile for the reason sized deallocation is not used. + for (const Block& b : blocks_) ::operator delete(reinterpret_cast(b.start)); +} + +Arena& Arena::operator=(Arena&& other) { + if (this != &other) { + // In case std::vector ever gets small object optimization. + size_t idx = other.reusable_ ? other.top_ - other.blocks_.data() : 0; + opt_ = other.opt_; + blocks_ = std::move(other.blocks_); + reusable_ = other.reusable_; + top_ = reusable_ ? blocks_.data() + idx : &g_empty_block; + other.blocks_.clear(); + other.reusable_ = 0; + other.top_ = &g_empty_block; + } + return *this; +} + +void Arena::Reuse(size_t num_blocks) { + reusable_ = std::min(reusable_, num_blocks); + for (size_t i = reusable_; i != blocks_.size(); ++i) { + const Block& b = blocks_[i]; + // See comments in Makefile for the reason sized deallocation is not used. + ::operator delete(reinterpret_cast(b.start)); + } + blocks_.resize(reusable_); + if (reusable_) { + top_ = blocks_.data(); + top_->tip = top_->start; + } else { + top_ = &g_empty_block; + } +} + +void Arena::AddBlock(size_t size, size_t alignment) { + if (alignment > alignof(std::max_align_t)) { + size += alignment - 1; + } else { + size = std::max(size, alignment); + } + if (size <= top_->size() && top_ < blocks_.data() + reusable_ - 1) { + assert(blocks_.front().size() == top_->size()); + ++top_; + top_->tip = top_->start; + return; + } + if (size <= opt_.max_alloc_threshold) { + size = + std::max(size, Clamp(opt_.min_block_size, NextPow2(top_->size() + 1), opt_.max_block_size)); + } + + auto p = reinterpret_cast(::operator new(size)); + blocks_.push_back(Block{p, p, p + size}); + if (reusable_) { + if (size < blocks_.front().size()) { + top_ = &blocks_.back(); + return; + } + if (size > blocks_.front().size()) reusable_ = 0; + } + std::swap(blocks_.back(), blocks_[reusable_]); + top_ = &blocks_[reusable_++]; +} + +void* Arena::AllocateSlow(size_t size, size_t alignment) { + assert(alignment && !(alignment & (alignment - 1))); + AddBlock(size, alignment); + assert(Align(top_->tip, alignment) + size <= top_->end); + return Allocate(size, alignment); +} + +} // namespace gitstatus diff --git a/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/src/arena.h b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/src/arena.h new file mode 100644 index 00000000..569833ca --- /dev/null +++ b/configurations/price/dots/xdg/config/zsh/config/themes/powerlevel10k/gitstatus/src/arena.h @@ -0,0 +1,273 @@ +// Copyright 2019 Roman Perepelitsa. +// +// This file is part of GitStatus. +// +// GitStatus is free software: you can redistribute it and/or modify +// it under the terms of the GNU General Public License as published by +// the Free Software Foundation, either version 3 of the License, or +// (at your option) any later version. +// +// GitStatus is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. +// +// You should have received a copy of the GNU General Public License +// along with GitStatus. If not, see . + +#ifndef ROMKATV_GITSTATUS_ARENA_H_ +#define ROMKATV_GITSTATUS_ARENA_H_ + +#include +#include +#include +#include +#include +#include +#include +#include + +#include "string_view.h" + +namespace gitstatus { + +// Thread-compatible. Very fast and very flexible w.r.t. allocation size and alignment. +// +// Natural API extensions: +// +// // Donates a block to the arena. When the time comes, it'll be freed with +// // free(p, size, userdata). +// void Donate(void* p, size_t size, void* userdata, void(*free)(void*, size_t, void*)); +class Arena { + public: + struct Options { + // The first call to Allocate() will allocate a block of this size. There is one exception when + // the first requested allocation size is larger than this limit. Subsequent blocks will be + // twice as large as the last until they saturate at max_block_size. + size_t min_block_size = 64; + + // Allocate blocks at most this large. There is one exception when the requested allocation + // size is larger than this limit. + size_t max_block_size = 8 << 10; + + // When the size of the first allocation in a block is larger than this threshold, the block + // size will be equal to the allocation size. This is meant to reduce memory waste when making + // many allocations with sizes slightly over max_block_size / 2. With max_alloc_threshold equal + // to max_block_size / N, the upper bound on wasted memory when making many equally-sized + // allocations is 100.0 / (N + 1) percent. When making allocations of different sizes, the upper + // bound on wasted memory is 50%. + size_t max_alloc_threshold = 1 << 10; + + // Natural extensions: + // + // void* userdata; + // void (*alloc)(size_t size, size_t alignment, void* userdata); + // void (*free)(void* p, size_t size, void* userdata); + }; + + // Requires: opt.min_block_size <= opt.max_block_size. + // + // Doesn't allocate any memory. + Arena(Options opt); + Arena() : Arena(Options()) {} + Arena(Arena&&); + ~Arena(); + + Arena& operator=(Arena&& other); + + // Requires: alignment is a power of 2. + // + // Result is never null and always aligned. If size is zero, the result may be equal to the last. + // Alignment above alignof(std::max_align_t) is supported. There is no requirement for alignment + // to be less than size or to divide it. + inline void* Allocate(size_t size, size_t alignment) { + assert(alignment && !(alignment & (alignment - 1))); + uintptr_t p = Align(top_->tip, alignment); + uintptr_t e = p + size; + if (e <= top_->end) { + top_->tip = e; + return reinterpret_cast(p); + } + return AllocateSlow(size, alignment); + } + + template + inline T* Allocate(size_t n) { + static_assert(!std::is_reference(), ""); + return static_cast(Allocate(n * sizeof(T), alignof(T))); + } + + template + inline T* Allocate() { + return Allocate(1); + } + + inline char* MemDup(const char* p, size_t len) { + char* res = Allocate(len); + std::memcpy(res, p, len); + return res; + } + + // Copies the null-terminated string (including the trailing null character) to the arena and + // returns a pointer to the copy. + inline char* StrDup(const char* s) { + size_t len = std::strlen(s); + return MemDup(s, len + 1); + } + + // Guarantees: !StrDup(p, len)[len]. + inline char* StrDup(const char* p, size_t len) { + char* res = Allocate(len + 1); + std::memcpy(res, p, len); + res[len] = 0; + return res; + } + + // Guarantees: !StrDup(s)[s.len]. + inline char* StrDup(StringView s) { + return StrDup(s.ptr, s.len); + } + + template + inline char* StrCat(const Ts&... ts) { + return [&](std::initializer_list ss) { + size_t len = 0; + for (StringView s : ss) len += s.len; + char* p = Allocate(len + 1); + for (StringView s : ss) { + std::memcpy(p, s.ptr, s.len); + p += s.len; + } + *p = 0; + return p - len; + }({ts...}); + } + + // Copies/moves `val` to the arena and returns a pointer to it. + template + inline std::remove_const_t>* Dup(T&& val) { + return DirectInit>>(std::forward(val)); + } + + // The same as `new T{args...}` but on the arena. + template + inline T* DirectInit(Args&&... args) { + T* res = Allocate(); + ::new (const_cast(static_cast(res))) T(std::forward(args)...); + return res; + } + + // The same as `new T(args...)` but on the arena. + template + inline T* BraceInit(Args&&... args) { + T* res = Allocate(); + ::new (const_cast(static_cast(res))) T{std::forward(args)...}; + return res; + } + + // Tip() and TipSize() allow you to allocate the remainder of the current block. They can be + // useful if you are flexible w.r.t. the allocation size. + // + // Invariant: + // + // const void* tip = Tip(); + // void* p = Allocate(TipSize(), 1); // grab the remainder of the current block + // assert(p == tip); + const void* Tip() const { return reinterpret_cast(top_->tip); } + size_t TipSize() const { return top_->end - top_->tip; } + + // Invalidates all allocations (without running destructors of allocated objects) and frees all + // blocks except at most the specified number of blocks. The retained blocks will be used to + // fulfil future allocation requests. + void Reuse(size_t num_blocks = std::numeric_limits::max()); + + private: + struct Block { + size_t size() const { return end - start; } + uintptr_t start; + uintptr_t tip; + uintptr_t end; + }; + + inline static size_t Align(size_t n, size_t m) { return (n + m - 1) & ~(m - 1); }; + + void AddBlock(size_t size, size_t alignment); + bool ReuseBlock(size_t size, size_t alignment); + + __attribute__((noinline)) void* AllocateSlow(size_t size, size_t alignment); + + Options opt_; + std::vector blocks_; + // Invariant: !blocks_.empty() <= reusable_ && reusable_ <= blocks_.size(). + size_t reusable_ = 0; + // Invariant: (top_ == &g_empty_block) == blocks_.empty(). + // Invariant: blocks_.empty() || top_ == &blocks_.back() || top_ < blocks_.data() + reusable_. + Block* top_; + + static Block g_empty_block; +}; + +// Copies of ArenaAllocator use the same thread-compatible Arena without synchronization. +template +class ArenaAllocator { + public: + using value_type = T; + using pointer = T*; + using const_pointer = const T*; + using reference = T&; + using const_reference = const T&; + using size_type = size_t; + using difference_type = ptrdiff_t; + using propagate_on_container_move_assignment = std::true_type; + template + struct rebind { + using other = ArenaAllocator; + }; + using is_always_equal = std::false_type; + + ArenaAllocator(Arena* arena = nullptr) : arena_(*arena) {} + + Arena& arena() const { return arena_; } + + pointer address(reference x) const { return &x; } + const_pointer address(const_reference x) const { return &x; } + pointer allocate(size_type n, const void* hint = nullptr) { return arena_.Allocate(n); } + void deallocate(T* p, std::size_t n) {} + size_type max_size() const { return std::numeric_limits::max() / sizeof(value_type); } + + template + void construct(U* p, Args&&... args) { + ::new (const_cast(static_cast(p))) U(std::forward(args)...); + } + + template + void destroy(U* p) { + p->~U(); + } + + bool operator==(const ArenaAllocator& other) const { return &arena_ == &other.arena_; } + bool operator!=(const ArenaAllocator& other) const { return &arena_ != &other.arena_; } + + private: + Arena& arena_; +}; + +template +struct LazyWithArena; + +template