Skip to main content

ℹ️ Zsh Plugin Standard

This page defines what a Zsh plugin is, how it is structured, and how plugins and plugin managers interoperate. Following the portable core lets people source your plugin directly or load it through different frameworks and plugin managers without learning a repository-specific architecture first.

Status of this document

This is ecosystem guidance, not an official Zsh language specification. Zsh guarantees are identified and linked to the official manual. Everything else is a recommendation for interoperability.

Where each rule lives

This page owns the plugin interoperability contract: what makes a directory a plugin, and how a manager and a plugin talk to each other.

It does not own general Zsh authoring rules. For language semantics, options, quoting, expansion, and safety rules, follow the canonical Zsh Scripting Standard. For idioms and worked techniques, see the Zsh Native Scripting Handbook. Official Zsh documentation remains authoritative for shell semantics.

Conformance language​

This page publishes version 2 of the portable contract. The terms in this page have these meanings:

  • Zsh guarantee describes behavior documented by the current Zsh manual.
  • MUST, MUST NOT, SHOULD, and MAY have their usual normative meanings. A documented reason is required when a plugin does not follow a SHOULD rule.
  • Portable core describes manager-independent requirements for a plugin. It is the architecture, loading, namespace, configuration, lifecycle, and testing contract below.
  • Loader interface describes an optional facility that a plugin manager may expose. It is not part of portable conformance.
  • Optional profile describes conventions implemented by named managers. A plugin can use a profile, but must not silently require it.

A portable plugin does not require a manager, a manager-owned global parameter, or a manifest. There is no plugin manifest standard defined by this page.

Version 2 is a clean contract, not a compatibility mode. Older conventions can be documented as history, but they are not alternative ways to claim current portable conformance.

Each optional loader interface carries a STATUS block recording which managers implement it, with pinned source citations.

What is a Zsh plugin?​

Zsh plugins were first defined in practice by Oh My Zsh. They provide a way to package together files that extend or configure the shell's functionality in a particular way.

At a simple level, a plugin is a directory with one documented sourceable Zsh entrypoint. It may also contain private sourced libraries, autoload functions, completions, user-invoked programs, and documentation. Each directory has the execution semantics defined by the portable layout below.

A plugin can be sourced directly without a manager. A framework or manager may discover the entrypoint and arrange fpath, but the portable plugin must not require manager state merely to load or unload.

Optional loader interfaces​

The following numbered interfaces document facilities implemented by existing plugin managers. They are not portable requirements and a plugin does not need to implement or inspect any of them. A plugin that deliberately opts into one must feature-test that exact facility, retain its direct-source behavior, and test the named manager profile independently.

These interfaces are retained as manager interoperability reference, not as a legacy conformance mode.

1. Standardized source-path handoff​

Portable plugins use the canonical scoped loader defined in the portable core. Its final argument is evaluated at the sourced file's call site, before the anonymous loader function begins:

Manager-compatible source-path handoff
"${ZERO:-${${0:#$ZSH_ARGZERO}:-${(%):-%N}}}"

The expression will:

  1. Be backward compatible with normal $0 setting and usage.

  2. Use ZERO if it is not empty.

    2.1. The plugin manager is then easily able to alter the effective $0 before loading a plugin.

    2.2. This allows, for example, eval "$(<plugin)", which can be faster than source (comparison). Note that this does not hold for a compiled script. This is an eval-based interface and it belongs to the manager, not to the plugin: it is recorded here to explain why ZERO exists. A plugin must never evaluate its own or another plugin's text this way, and must never pass untrusted data through such a call.

  3. Use $0 if it differs from ZSH_ARGZERO, the shell invocation name.

    3.1. A plugin manager can still set $0, although this is more difficult: it requires unsetopt function_argzero before sourcing the plugin script, and a 0=… assignment afterwards.

    3.2. unsetopt function_argzero is detected, because it causes $0 to hold the path to the Zsh binary rather than the plugin script, unless overwritten by a 0=… assignment.

  4. Fall back to the %N prompt expansion flag, which reports the name of the script, sourced file, or function currently being executed. See the official %N definition. It reports the execution name or path, and is not guaranteed to be absolute. A plugin manager cannot alter it, so no advanced loading is possible through it, but plain plugin-file sourcing without a plugin manager is saved from breaking.

Keep this expression after the anonymous function's closing brace. Inside that function, %N is (anon), not the sourced file path. The loader receives the value as $1, normalizes it with :a, and stores it in a readonly local parameter. The :a modifier resolves . and .. components and makes a relative path absolute without resolving symlinks; see Zsh filename modifiers. Use :A or :P only when you intentionally want symlink resolution.

Do not assign the result to special parameter 0. Keeping it in loader-local state preserves the caller and remains valid when posix_argzero makes 0 read-only.

The goal is flexibility. The essential motivation is to support manager-side eval "$(<plugin)" loading while working under no_function_argzero and posix_argzero.

Use in standalone scripts​

The same call-site expression works in a standalone script, one run through a #! line, to find the directory the script file resides in. A standalone process does not need the anonymous loader merely to protect its caller, but it must still store the result in a purpose-specific parameter rather than repurposing 0. Verified on Zsh 5.9.2 when invoked by absolute path, from an unrelated working directory, by relative path, and through a symlink.

Two differences apply outside a plugin manager:

  • ZERO is inert, because nothing sets it. The %N branch does the work.
  • :a does not resolve symlinks, so a script reached through a symlink resolves to the directory holding the link, not the target. Use :A when you want the target's directory.
%N must remain at the sourced-file call site

Inside a function, %N expands to the function name. Moving the fallback into the loader body would therefore resolve against the current directory instead of failing:

$ zsh -f -c 'f() { print -r -- ${(%):-%N} }; f'
f
$ zsh -f -c 'myplugin() { print -r -- ${${(%):-%N}:a:h} }; myplugin'
/current/working/directory # not the plugin directory

The canonical loader avoids this trap by evaluating the handoff expression after the closing brace, while Zsh is still executing the sourced file.

Change from earlier revisions

Earlier revisions assigned the resolved path to 0, then made it absolute with either $PWD or :a. That mutation could replace caller state and fails when posix_argzero makes 0 read-only:

$ zsh -f -c 'setopt posix_argzero; typeset -p 0'
typeset 0=zsh
$ zsh -f -c 'setopt posix_argzero; 0=x'
zsh:1: read-only variable: 0

The scoped loader supersedes those forms while retaining the ZERO manager handoff.

Do not infer the repository directory from the caller's current directory.

STATUS: [ zero-handling ]​

2. Functions directory​

Current-standard plugins have their main directory added to $fpath. A cleaner approach is proposed: plugins use a subdirectory called functions to store their completions and autoload functions. The plugin manager should add that directory to $fpath. Where a manager lacks support, the plugin can resolve it through the activity indicator:

Self-fpath through the activity indicator
if [[ ${zsh_loaded_plugins[-1]} != */kalc && -z ${fpath[(r)${0:h}/functions]} ]]; then
fpath+=( "${0:h}/functions" )
fi

or through the PMSPEC parameter:

Self-fpath through PMSPEC
if [[ $PMSPEC != *f* ]]; then
fpath+=( "${0:h}/functions" )
fi

Either snippet, added to the plugin.zsh file, adds the directory to $fpath while preserving compatibility with managers that already handle it. The existence of the functions subdirectory cancels the normal adding of the main plugin directory to $fpath.

Store each native completion in a file named _command. See Completions and compinit ownership for who is responsible for running compinit.

Note on a widespread typo

Many published plugins link to #funtions-directory, missing the first c. That fragment is kept alive on this page so those links resolve, but the correct anchor is #functions-directory.

STATUS: [ functions-directory ]​

  • Zi: implemented. Advertises f in PMSPEC.
  • zcomet: implemented. Advertises f in its PMSPEC.
  • zgenom: implemented. Sets PMSPEC in options.zsh.
  • Zinit: implemented. Advertises f in its bootstrap.
  • Adoption: the *f* guard is the most widely used capability check in the z-shell organization.

3. Binaries directory​

Plugins sometimes provide a runnable script or program, either for internal use or for the end user. For the latter, the plugin should use a bin/ subdirectory inside its main directory. For internal use, call the runnable through the $0 value obtained in requirement 1.

The runnable should be placed in that directory with the +x access right set. The plugin manager should:

  1. Before sourcing the plugin's script, test whether the bin/ directory exists within the plugin directory.

  2. If it does, add the directory to $PATH.

  3. Alternatively, instead of extending $PATH, create a shim, that is a forwarder script, or a symbolic link inside a common directory that is already on $PATH, to limit how far $PATH grows.

  4. Optionally ensure +x access rights on the directory contents.

The $PMSPEC code letter for the feature is b. It allows the plugin to handle the $PATH extension itself when the manager does not:

Self-PATH through PMSPEC
if [[ $PMSPEC != *b* ]]; then
path+=( "${0:h}/bin" )
fi
This is a guarded extension, not an unconditional one

The guard is the point. The plugin yields to any manager that advertises b, and only acts when nothing else will. Do not extend path unconditionally, and do not add $ZPFX/bin from a plugin; see requirement 8.

STATUS: [ binaries-directory ]​

  • zcomet: implemented. Advertises b in its PMSPEC.
  • zgenom: implemented conditionally. Sets the letter according to its automatic bin setting in options.zsh.
  • Zi, Zinit: do not advertise b, so the guarded plugin-side extension is the operative path under both.
  • Adoption: four plugin entrypoints in the z-shell organization use the *b* guard.

4. Unload function​

If a plugin is named kalc, and is available through the any-user/kalc plugin ID, then it can provide a function kalc_plugin_unload that a plugin manager calls to undo the effects of loading that plugin.

A plugin manager can implement its own tracking of the changes a plugin makes, so this is optional in general. However, to properly unload something like a prompt, dedicated tracking, which is easy for the plugin author to write, gives better and more predictable results. Uncommon effects of loading a plugin can only be undone by a dedicated function.

An interesting compromise is available: withdraw only the special effects through the plugin-provided function and leave the rest to the plugin manager. Maintaining a function that withdraws all side effects can be a daunting task requiring constant attention during development.

The unload function should also delete itself. Use unfunction kalc_plugin_unload rather than unfunction $0, for compatibility with the *_argzero options.

A namespaced unload function
kalc_plugin_unload() {
emulate -L zsh

autoload -Uz add-zsh-hook
add-zsh-hook -d precmd _kalc_precmd

unfunction _kalc_precmd kalc_plugin_unload
unset KALC_STATE
}

Keep cleanup idempotent, list each owned resource explicitly, and tolerate partial initialization. See Lifecycle and resource ownership for the full inventory of what counts as an owned resource.

STATUS: [ unload-function ]​

5. @zsh-plugin-run-on-unload call​

The plugin manager can provide a function @zsh-plugin-run-on-unload with the following call syntax:

Register unload snippets
@zsh-plugin-run-on-unload "{code-snippet-1}" "{code-snippet-2}" …

The function registers pieces of code to be run by the plugin manager on the unloading of the plugin. Execution is done by the eval builtin, in the same order the snippets are passed. The code runs in the plugin's directory, in the current shell. The mechanism provides a second way, alongside the unload function, for a plugin to participate in unloading.

This is an eval-based interface

Because the manager evaluates these strings, never pass untrusted or externally-derived data into the call. Prefer a named, idempotent unload function as the primary mechanism and treat this as manager-profile compatibility rather than portable lifecycle practice.

STATUS: [ run-on-unload-call ]​

  • Zi: implemented. Stores manager callback strings; see Zi's callback source. Advertises U in PMSPEC.
  • Zinit: implemented separately; see Zinit's callback source. Advertises U.
  • Shared name, separate implementations. Support in both projects is shared convention, not evidence that they are the same manager. Test each profile you opt into.

6. @zsh-plugin-run-on-update call​

The plugin manager can provide a function @zsh-plugin-run-on-update with the following call syntax:

Register update snippets
@zsh-plugin-run-on-update "{code-snippet-1}" "{code-snippet-2}" …

The function registers pieces of code to be run by the plugin manager on an update of the plugin. Execution is done by the eval builtin in the order the snippets are passed. The code runs in the plugin's directory, possibly in a subshell, after downloading any new commits to the repository.

The same warning about evaluated strings applies. A portable plugin should also expose an explicit update or migration command, and must not assume that any manager evaluates update callbacks. Keep persisted formats versioned and migrate them atomically.

STATUS: [ run-on-update-call ]​

7. Plugin manager activity indicator​

Plugin managers should set the $zsh_loaded_plugins array to contain all previously loaded plugins and the plugin currently being loaded, as the last element.

This allows any plugin to:

  1. Check which plugins are already loaded.

  2. Check whether it is being loaded by a plugin manager, rather than simply sourced.

The first item allows a plugin to issue a notice about missing dependencies, or to satisfy them from resources it ships. For example, the pure prompt bundles a zsh-async dependency library that is normally a separate project. Consequently the prompt could decide to source its private copy, having also a reliable $0 from requirement 1. Note that pure does not normally do this.

The second item allows a plugin to set up $fpath itself, knowing the plugin manager will not:

Self-fpath when no manager is present
if [[ ${zsh_loaded_plugins[-1]} != */kalc && -z ${fpath[(r)${0:h}]} ]]; then
fpath+=( "${0:h}" )
fi

This lets a user reliably source the plugin without a plugin manager. The code wraps parameters in braces, as in ${fpath…}, for compatibility with the KSH_ARRAYS option, and quotes ${0:h} for compatibility with the SH_WORD_SPLIT option.

A plugin may also accept a manager-supplied ZERO as its execution path. This does not authorize evaluating the plugin text or overwriting 0. The contents and timing of zsh_loaded_plugins belong to the manager, so do not use it to decide whether the plugin must initialize its own portable behavior.

STATUS: [ activity-indicator ]​

8. Global parameter with PREFIX for make, configure, and similar​

Plugin managers may export the parameter $ZPFX, holding a path to a directory dedicated to user-land software, giving $ZPFX/bin, $ZPFX/lib, $ZPFX/share, and so on. The suggested directory name is polaris. Zi uses that name and places the directory at ${ZI[HOME_DIR]}/polaris by default.

Users can then configure hooks to invoke, for example, make PREFIX=$ZPFX install on clone and update, to install software such as tj/git-extras. This is the developing role of Zsh plugin managers as package managers, where .zshrc has a role similar to a Chef or Puppet configuration and allows the user to declare system state and reproduce it across accounts and machines.

Facts related to $ZPFX:

  1. export ZPFX="$HOME/polaris", or ${ZI[HOME_DIR]}/polaris

  2. make PREFIX=$ZPFX install

  3. ./configure --prefix=$ZPFX

  4. cmake -DCMAKE_INSTALL_PREFIX=$ZPFX .

  5. zi ice make"PREFIX=$ZPFX install"

  6. zi … hook-build:"make PREFIX=$ZPFX install"

$ZPFX is an optional manager-provided installation prefix. It is not an XDG variable and not a portable requirement. Use it only during an explicit installation or build action:

Use an explicitly supplied installation prefix
if [[ -n ${ZPFX-} ]]; then
command make install "PREFIX=$ZPFX"
fi

Do not run this during normal plugin loading, and do not add $ZPFX/bin to PATH from a plugin. Leave that policy to the user or the manager.

STATUS: [ global-parameter-with-prefix ]​

  • Zi: implemented. Exports ZPFX in its bootstrap. Advertises P.
  • Zinit: implemented independently. Exports ZPFX in its bootstrap. Advertises P.
  • zgenom: implemented. Defines ZPFX in options.zsh. Advertises P.
  • zcomet: advertises P in its PMSPEC.

9. Global parameter holding the plugin manager's capabilities​

Each numbered requirement above constitutes a capability of the plugin manager. It makes sense for those capabilities to be discoverable. The global parameter PMSPEC, from plugin-manager specification, holds Latin letters, each telling the plugin that the manager supports a given feature:

LetterCapabilityRequirement
0provides the ZERO parameter1
fsupports the functions/ subdirectory2
bsupports the bin/ subdirectory3
ucalls the unload function4
Uprovides @zsh-plugin-run-on-unload5
pprovides @zsh-plugin-run-on-update6
iprovides the zsh_loaded_plugins indicator7
Pprovides the ZPFX global parameter8
sprovides PMSPEC itself, so it is always presentthis requirement

The plugin verifies support by testing for the letter:

Feature-test a manager capability
if [[ $PMSPEC != *b* ]]; then
path+=( "${0:h}/bin" )
fi
Corrections to earlier revisions of this table

Earlier revisions of this page published a table that could not be applied as written. Three defects are corrected above:

  1. The letter b was defined twice, once for the bin/ subdirectory and once for the ZPFX parameter. b means bin/. Four plugin entrypoints in the z-shell organization rely on that meaning.
  2. The letter P appeared in the "fully compliant" string but was never defined. P means ZPFX, which is how implementations use it.
  3. The closing example guarded a bin/ PATH extension on *P* instead of *b*.

Published implementations set different strings, so a plugin must not treat any letter list as a universal capability registry. Feature-test the exact letter you need, and provide a manager-independent path.

Observed values:

ManagerPMSPEC
Zi0fuUpiPsX
Zinit0uUpiPsf
zcomet0fbuiPs

Zi's X has no definition in any published source and no consumer anywhere in the z-shell organization. Treat it as an unallocated Zi extension observed in the wild; this page does not assign it a meaning.

There is no conformance target

This page defines the meaning of each letter. It does not define a required set, and it does not rank managers by how many letters they advertise.

Earlier revisions stated that a fully compliant manager should advertise 0fuUpiPs. That target is withdrawn. No published manager advertises it, no two of the managers above agree, and a plugin gains nothing from comparing a string against a fixed list.

A manager is not non-conforming because it omits a letter; it advertises what it implements. Correspondingly, a plugin must feature-test the exact letter it needs and keep a manager-independent path, rather than testing for a set:

Test one capability, not a set
if [[ $PMSPEC != *f* ]]; then
fpath+=( "${0:h}/functions" )
fi

STATUS: [ global-parameter-with-capabilities ]​

  • Zi: implemented. Sets PMSPEC=0fuUpiPsX in its bootstrap.
  • Zinit: implemented independently. Sets PMSPEC=0uUpiPsf in its bootstrap.
  • zcomet: implemented. Sets PMSPEC=0fbuiPs in zcomet.zsh.
  • zgenom: implemented conditionally, according to its automatic bin setting, in options.zsh.
  • Adoption: across all 57 plugin and library entrypoints in the z-shell organization, f is tested 31 times, b four times, P once, and X never.

Portable core​

The portable core begins here. Conformance does not depend on any interface in the preceding optional loader reference. The rules in this section through Tests define the manager-independent contract.

Entrypoints and repository layout​

Provide one authoritative, sourceable Zsh entrypoint. A file named after the repository, such as example.plugin.zsh, is widely recognized: Antidote searches for it first, while Oh My Zsh identifies plugins by that name.

Entrypoint discovery is not universal. For example, zcomet has its own ordered entrypoint search, and Znap exposes znap.zsh as its entrypoint. Therefore:

  1. State the exact source command in the README.
  2. Do not depend on a manager sourcing the "first" matching file.
  3. Keep alternate entrypoints, if supplied, as thin wrappers around one implementation.
  4. Make repeated loading harmless, or reject it with a clear diagnostic.

Resolve the entrypoint directory from the sourced file, not from the caller's working directory. The standard expression accepts an optional manager-supplied ZERO, preserves ordinary source behavior through $0, falls back to %N, and makes the result absolute without resolving symlinks:

Resolve the authoritative entrypoint
() {
builtin emulate -L zsh

local -r source_path=${1:a}
local -r plugin_dir=${source_path:h}

# Plugin initialization.
} "${ZERO:-${${0:#$ZSH_ARGZERO}:-${(%):-%N}}}"

The anonymous function provides local scope, and emulate -L zsh establishes native Zsh option behavior while localizing option, pattern, and trap changes. local -r makes the two path invariants explicit and readonly. Zsh parses local name=value as a declaration assignment, so the unquoted scalar value remains one word. Keep the complete source-path expression at the call site; see the loader interoperability reference for manager evaluation details and the official Zsh filename modifiers for :a, :A, and :P.

A maintainable layout is:

Example plugin layout
example/
├── example.plugin.zsh # authoritative entrypoint
├── lib/ # optional private, eagerly sourced helpers
│ └── setup.zsh
├── functions/ # optional autoload functions
│ └── example_command
├── completions/ # optional completion functions
│ └── _example
├── bin/ # optional user-invoked executables
├── LICENSE
└── README.md

The directory names describe execution, not merely organization:

  • lib/ contains private implementation files that the entrypoint must source eagerly. Do not add it to fpath, and do not retain setup-only functions after loading.
  • functions/ contains functions loaded through Zsh autoload, normally one function per file. Use it for work not needed during every shell startup.
  • completions/ contains native _command completion functions and follows completion-system ownership rules.
  • bin/ contains programs the user invokes explicitly. Plugin loading must not execute them as initialization.

Omit a directory when the plugin does not need that execution profile. A different directory name must have equally explicit documented semantics; it must not blur eager sourcing and autoloading.

Document which directories a direct-source installation should add to fpath or PATH. A plugin may add its own functions/ or completions/ directory to fpath after checking that the exact path is absent. Do not mutate PATH during ordinary loading; document bin/ for the user or manager instead.

Loading contract and security​

Loading a plugin must be safe and predictable. During ordinary loading, a plugin must not:

  • access the network, or download or install packages;
  • evaluate untrusted text, or text fetched at load time;
  • mutate PATH;
  • write into its own checkout, which may be read-only or manager-controlled;
  • change global options as an incidental effect;
  • change the working directory without restoring it, or disturb the directory stack;
  • print routine success output;
  • prompt interactively when the shell is non-interactive.

Send actionable diagnostics to standard error and stay silent on success. A shell that starts cleanly should print nothing. Defer cache creation and expensive discovery until the feature is actually used, rather than doing the work at load time.

Do not access the network while loading. Network activity must be an explicit user action, such as a command the user runs, not a side effect of starting a shell.

Do not automatically prepend or append to PATH. Document the plugin's bin/ directory for explicit user or manager configuration.

Treat all user-supplied and externally-derived text as untrusted data, never as code.

Sourcing versus evaluating​

The rule differs by who is doing the loading.

A plugin or a user must not use eval merely to load a file. Use the builtin and end the options so a leading dash or a path containing one cannot be reinterpreted:

Load a file as a plugin or a user
source -- "$file"

A plugin manager may load a plugin by evaluating its text, for example with eval "$(<plugin)", which can be faster than source. This is an eval-based interface and it belongs to the manager alone: never pass untrusted or externally-derived text through it. A manager that evaluates a plugin must supply ZERO, because evaluated text has no %N path of its own to fall back on. This optional hand-off is documented in the loader interoperability reference.

There is no contradiction between the two: a plugin must never evaluate its own or another plugin's text, while a manager evaluating a plugin it loaded is a documented loading mode with a matching obligation.

Function and option scope​

Zsh guarantee: emulate -L zsh establishes native Zsh emulation and localizes option changes to the function. The -R flag is a separate operation that resets all settable options to their default values. See the official emulate documentation.

Every non-trivial function should establish the option environment it needs and declare its parameters:

Scope a public function
example_do_work() {
emulate -L zsh
setopt localtraps pipefail

local input=$1
local -a results
local -A metadata

# Function implementation.
}

Use builtin or command when calling a command whose name may be shadowed. Quote substitutions unless intentional Zsh splitting or globbing is required.

An entrypoint can use a temporary loader function to contain options and temporary parameters:

Contain entrypoint setup
_example_load() {
emulate -L zsh
setopt localtraps

# Register the plugin's persistent functions, hooks, and state.
}

() {
_example_load "$@"
local loader_status=$?
unfunction _example_load
return "$loader_status"
} "$@"

See Standard recommended options for the specific option set, and the Zsh Scripting Standard for the full normative rules.

Names and persistent state​

Choose one stable, portable ASCII project identifier and document it in the README. Prefix every persistent function, parameter, widget, style context, hook callback, and other shell-visible name with that identifier. Public names use example_...; private callbacks and state use _example_...:

Use a project namespace
typeset -gA _example_state
_example_state[enabled]=1

example_refresh() {
emulate -L zsh
# Public operation.
}

_example_precmd() {
emulate -L zsh
# Internal callback.
}

Prefix matching must respect a name boundary. An identifier of example owns example_refresh and _example_precmd; it does not own exampled merely because the bytes begin the same way.

Maintain a documented public shell surface. It lists every public function, parameter, widget, style context, hook, alias, path entry, and unload function. Everything else must be private, temporary, or local. Loading must not retain setup-only functions, and a plugin must not create generic helper names that unrelated plugins could reasonably choose.

Zsh has no plugin-local namespace for persistent callbacks, so a small number of project-prefixed globals can be necessary. Minimize and explicitly allowlist them rather than encoding arrays into one scalar or retaining every helper from an eagerly sourced library.

See Standard parameter naming, Shared Plugins hash, Standard function name-space prefixes, and Preventing parameter pollution.

Configuration contract​

Public configuration must use one coherent project-owned interface. For ordinary declarative Zsh configuration, use a namespaced zstyle context:

Configure a plugin through one style context
zstyle ':example:config' mode compact
zstyle ':example:config' features history matching

Read scalar values with zstyle -s, arrays with zstyle -a, booleans with zstyle -t, and document defaults, value types, accepted values, and when each setting is read. Supply defaults as local lookup fallbacks rather than registering them in the global style database, where an exact default could override a broader user pattern. Contexts must begin with the project identifier, and a plugin must not reuse another subsystem's style context.

Use a project-owned global parameter only when persistent runtime state needs a Zsh type or mutation model that styles cannot provide. Such parameters are private implementation state, not a second public configuration interface. Keep real indexed and associative arrays when their shape matters.

A conforming plugin must not expose a scatter of independent global parameters for ordinary settings. It also must not use exported environment variables as a substitute for namespacing. Environment variables are appropriate only when a value must cross an exec boundary or be inherited by a child process.

Runtime commands may provide a public mutation interface when validation, atomic updates, or immediate reconfiguration is required. They must write the same documented configuration model rather than introduce a parallel one.

Organizing plugin configuration​

The file in which a user stores plugin configuration is not part of portable conformance. Users with a small configuration may keep style declarations in .zshrc. To keep that startup file concise, the recommended companion file is:

Recommended plugin configuration file
${ZDOTDIR:-${XDG_CONFIG_HOME:-$HOME/.config}/zsh}/plugin-config.zsh

ZDOTDIR keeps the file beside an intentionally relocated Zsh configuration. When ZDOTDIR is unset, the path follows the XDG user-configuration location. The name describes the file's purpose; zstyle is the configuration mechanism, not the subject of the file.

Source the file from .zshrc before loading a plugin manager or directly sourcing plugins, because a plugin may read its settings once during initialization:

Load plugin configuration before plugins
source -- "${ZDOTDIR:-${XDG_CONFIG_HOME:-$HOME/.config}/zsh}/plugin-config.zsh"

# Load the plugin manager and plugins after this point.

Group declarations by project identifier and keep a repository or documentation link plus any useful local note beside each group:

Group settings by plugin
# example/example
# https://github.com/example/example
# Use the compact display; the documented default is full.
zstyle ':example:config' mode compact

The shell configuration owns this file. A plugin must not locate or source it. When one file becomes difficult to maintain, users may split it into plugin-config.d/<project>.zsh fragments and source them in deterministic order before loading plugins. This is an optional organization technique, not a portable plugin interface.

Completions and compinit ownership​

Store each native completion in a file named _command. Make the directory available on fpath before completion initialization, either through the plugin's exact-path membership check, explicit user configuration, or manager configuration.

The plugin should not run compinit during ordinary loading. The shell configuration, framework, or manager owns completion initialization and should normally perform it once after constructing fpath. This avoids repeated startup work and preserves the owner's security policy.

Zsh guarantee: compinit checks completion files and directories for ownership and unsafe write permissions and can rerun those checks through compaudit. Review the official completion security rules. Do not bypass them with compinit -u inside a plugin. Oh My Zsh provides a representative framework-owned sequence that builds fpath, autoloads compaudit and compinit, and then applies its completion security policy.

If a feature needs completion immediately after compinit has already run, document the integration step. Do not silently reinitialize the entire completion system.

Lifecycle and resource ownership​

Treat every persistent side effect as an owned resource:

  • hooks and ZLE hook widgets;
  • functions, aliases, widgets, key bindings, and styles;
  • temporary files, cache files, and lock files;
  • background workers, coprocesses, and timers;
  • file descriptors and signal traps;
  • modules loaded by the plugin and special parameters created by those modules;
  • entries intentionally added to path, fpath, or other global arrays.

Provide a namespaced cleanup function whose name is derived from the documented project identifier, for example example_plugin_unload. It must stop only known worker process IDs, wait for them when appropriate, close only stored file descriptors, remove only named hooks and functions, and tolerate partial initialization.

Capture prior state before the first mutation. During unload, restore a prior value only when the current value is still the value the plugin installed. If the user or another component changed it after load, preserve the newer value. Remove a project-created container only when it is still project-owned and empty; never delete state another component subsequently adopted.

An unload contract is exact, not best effort. Test it in a clean zsh -f process by taking a baseline before load, recording the declared load surface, unloading, and comparing the final shell to the baseline. The observation harness must initialize any modules or special parameters it needs before the baseline so it does not attribute its own effects to the plugin.

At minimum, compare functions, parameters and attributes, aliases, options, traps, loaded modules, hooks, widgets, key bindings, styles, path, and fpath. Also test repeated source, partial initialization failure, hostile caller options, non-interactive loading, and user changes made after load.

In a separate clean-shell case, load, unload, and load again. Prove that the second load restores the same declared load surface as the first and that the restored resources perform their intended behavior. Resource presence or a successful return status alone is insufficient; observe the effect of a restored handler, hook, widget, or other resource.

Update and migration work should be explicit commands or manager hooks, not ordinary load-time behavior.

Startup performance​

Keep the entrypoint small. Prefer autoloaded functions for work that is not needed during every shell startup. Avoid subprocesses, repository scans, unconditional completion generation, and synchronous network access while loading.

Measure before optimizing:

Profile shell startup
zmodload zsh/zprof
source ./example.plugin.zsh
zprof

The official zsh/zprof module reports function call counts and times. Also compare end-to-end startup with a representative .zshrc; micro benchmarks can miss completion, process, and I/O costs.

If work runs asynchronously, record every worker PID and file descriptor as soon as it is created. Cleanup must terminate and reap only those workers, close only those descriptors, and remove any associated temporary files.

Cache, state, and data directories​

Use the XDG base-directory variables when the platform and user configuration provide them:

Derive project-owned storage paths
example_prepare_storage() {
emulate -L zsh

local cache_dir=${XDG_CACHE_HOME:-$HOME/.cache}/example
local state_dir=${XDG_STATE_HOME:-$HOME/.local/state}/example
local data_dir=${XDG_DATA_HOME:-$HOME/.local/share}/example

# Create only the directory needed by the explicit operation.
}

Use cache for reproducible data, state for persistent operational state, and data for durable user data. Create directories lazily with restrictive, user-appropriate permissions. Do not write into the plugin checkout during loading. A manager installation prefix is not a substitute for these user directories.

Versions and feature compatibility​

Declare the oldest supported Zsh version in the README and continuous integration. Prefer feature checks over assumptions:

Check an optional feature
if [[ -o interactive ]]; then
if zmodload zsh/zle && (( ${+builtins[zle]} )); then
# ZLE integration is available.
fi
fi

When a strict version check is necessary, autoload Zsh's is-at-least helper rather than comparing version strings manually:

Enforce a minimum Zsh version
autoload -Uz is-at-least
if ! is-at-least 5.8; then
print -u2 -- 'example requires Zsh 5.8 or newer'
return 1
fi

Fail without leaving partial hooks, workers, or state. Document degraded behavior for optional features.

Tests​

At minimum, automate these checks:

Portable smoke tests
zsh -n ./example.plugin.zsh
zsh -f -c 'source ./example.plugin.zsh'
zsh -f -c 'source ./example.plugin.zsh; source ./example.plugin.zsh'
zsh -f -c 'setopt ksharrays shwordsplit globsubst; source ./example.plugin.zsh'
zsh -f -c 'setopt nofunctionargzero posixargzero; source ./example.plugin.zsh'

The last line verifies the scoped entrypoint form: under posix_argzero the parameter 0 is read-only, so a plugin that assigns to it fails there.

Run the suite on every supported Zsh version. Add assertions for exported functions and parameters, hook registration, repeated loading, explicit cleanup, and non-interactive behavior. Test interactive and ZLE features in a pseudo-terminal rather than weakening their guards.

For each failure path, verify that the plugin returns non-zero with an actionable diagnostic and leaves no worker, open descriptor, temporary file, or partially registered hook.

Zsh plugin-programming best practices​

This page defines a Zsh plugin, and also serves as an information source for plugin creators. This section covers practices that apply specifically to plugin code.

Scope of this section

These are plugin-facing conventions. General Zsh authoring rules, covering options, quoting, expansion, arithmetic, traps, descriptors, and safety, live in the canonical Zsh Scripting Standard. Worked idioms live in the Zsh Native Scripting Handbook.

Use of add-zsh-hook to install hooks​

Zsh guarantee: the distributed add-zsh-hook function manages multiple callbacks for the supported hook entries, which are chpwd, periodic, precmd, preexec, zshaddhistory, zshexit, and zsh_directory_name. Its -d option removes a callback. For the meaning of each entry see the official hook function documentation. The invocation syntax is:

add-zsh-hook syntax
add-zsh-hook [ -L | -dD ] [ -Uzk ] hook function

Autoload it before use, register a named callback, and remove that exact callback during cleanup:

Register and remove a shell hook
autoload -Uz add-zsh-hook

_example_precmd() {
emulate -L zsh
# Update plugin state.
}

add-zsh-hook precmd _example_precmd

example_plugin_unload() {
emulate -L zsh
autoload -Uz add-zsh-hook
add-zsh-hook -d precmd _example_precmd
unfunction _example_precmd example_plugin_unload
unset _example_state
}

Keep cleanup idempotent and list each owned resource explicitly. Do not compare the global function table before and after loading and then delete every new function; another component may have created one. See Preventing function pollution for the safe narrowed form.

Use of add-zle-hook-widget to install Zle Hooks​

The Zle editor is the part of Zsh responsible for receiving text from the user. It is based on widgets, which are Zsh functions allowed to run in Zle context, plus a few differences such as the $WIDGET parameter that the editor sets automatically.

Zsh guarantee: add-zle-hook-widget adds widgets to documented ZLE hooks and supports -d for removal. See add-zle-hook-widget in the user-contributions manual. The syntax is:

add-zle-hook-widget syntax
add-zle-hook-widget [ -L | -dD ] [ -Uzk ] hook widget_name

The call resembles add-zsh-hook. The differences are that it takes a widget_name rather than a function name, and that hook is one of isearch-exit, isearch-update, line-pre-redraw, line-init, line-finish, history-line-set, or keymap-select. Their meanings are explained in the Zsh documentation: Special Widgets.

Use this function because it allows installing multiple hooks per hook entry. Before it existed, the only way was to define a widget named after one of the special widgets. It has been available since Zsh 5.3 and should be used instead.

Only configure line-editor behavior in an interactive shell with ZLE available:

Register an interactive ZLE hook
if [[ -o interactive ]]; then
if zmodload zsh/zle && (( ${+builtins[zle]} )); then
autoload -Uz add-zle-hook-widget

_example_line_init() {
emulate -L zsh
# ZLE-only behavior.
}

add-zle-hook-widget line-init _example_line_init
fi
fi

Cleanup must repeat the guards, autoload the helper, remove the exact hook with add-zle-hook-widget -d, delete any project-owned widgets with zle -D, and unfunction the callbacks. Do not assume that zle can run in a non-interactive shell or outside an active widget.

Standard parameter naming​

Use descriptive lowercase names for local parameters and explicit typeset, local, or integer declarations for their types. Use the stable project identifier for persistent parameters, with a leading underscore for private state, such as _example_state and _example_items.

Capitalization is not a type system in Zsh. The shell's REPLY and reply conventions remain relevant when implementing APIs that specify those names, but a plugin must not rely on capitalization alone to communicate a parameter's type or ownership. Declare the type and namespace explicitly.

Native completion functions retain the required _command file and function naming convention.

Shared Plugins hash​

Older z-shell plugins used a shared hash named Plugins as a registry for plugin paths and state. It has no ownership boundary: one plugin can create the parameter, another can add keys, and neither can determine safely whether the container should disappear during unload.

A version 2 portable plugin must not create, require, or write this shared hash. A plugin manager may maintain its own registry as an optional manager profile, but portable plugin code must work without observing or mutating it. Use the configuration contract for public settings and project-prefixed typed parameters only for necessary private runtime state.

The following snippet is recommended at the beginning of each of the main functions provided by the plugin:

Recommended option baseline
builtin emulate -L zsh ${=${options[xtrace]:#off}:+-o xtrace}
builtin setopt extended_glob warn_create_global typeset_silent no_short_loops rc_quotes no_auto_pushd

emulate -L zsh emulates a clean Zsh environment local to the function it is called from. The flags are:

  • -L: makes the emulation local to the function, so it does not affect the shell environment outside it. This is the flag used above.

  • -R: additionally resets all options to their default values, as if the shell had just started. Use emulate -LR zsh when you want that stronger reset; it is a different operation from -L alone.

Reference: Zsh shell builtin commands

The emulation is then altered with the following options:

  • ${=${options[xtrace]:#off}:+-o xtrace} keeps xtrace active if it was already active at the entry to the function, so tracing is not silently lost.

  • extended_glob enables one of the main Zsh features, the advanced built-in globbing mechanism.

  • warn_create_global prints a warning each time a global variable is defined without an explicit typeset, local, or declare call. It catches typos and missing localizations.

  • typeset_silent allows calling typeset or local more than once on the same variable. Without it, the second call prints the variable contents. It allows declaring variables inside loops, near the place of use.

  • no_short_loops disables the short-loops syntax, because when enabled it limits the parser's ability to detect errors. See this zsh-workers post for details.

  • rc_quotes adds the ability to insert an apostrophe into an apostrophe-quoted string by doubling it, so 'a string''s example' yields a string's example.

  • no_auto_pushd disables automatically pushing the directory passed to cd onto the directory stack, so internal directory changes made by the plugin do not pollute the global stack.

For the full normative rules on options and emulation, including when option state must outlive a single function call, see zsh/options/localize and zsh/options/declare-correctness-state in the Zsh Scripting Standard.

It is good to localize the following variables at the entry of the main function of a plugin:

Localize pattern-matching parameters
local MATCH REPLY; integer MBEGIN MEND
local -a match mbegin mend reply

The variables starting with m and M are used by substitutions employing the (#b) and (#m) flags respectively. They should not leak to the global scope. Their automatic creation would also trigger a warning from the warn_create_global option.

The reply and REPLY parameters are normally used to return an array or a scalar from a function. That is the standard way of passing values out of functions.

Their use is naturally limited to functions called from the main function of a plugin. They should not be used to pass data around between prompts, so it is natural to localize them in the main function.

Standard function name-space prefixes​

Use portable ASCII names derived from the stable project identifier:

  • example_action for a documented public function;
  • _example_callback for a private hook, widget, or style callback;
  • _example_helper for a private persistent helper when autoloading or later callbacks genuinely require it;
  • _command only for the native completion function for command.

Public and private names are part of the same shell command namespace, so the underscore marks visibility but does not replace the project identifier. An unprefixed _callback is not project-owned.

Do not assign semantic roles through punctuation-only or non-ASCII prefixes. Names beginning with ., +, /, or similar role markers are harder to autoload, type, search, and represent consistently as file names. Manager API names beginning with @, such as the optional unload and update callbacks, are manager-owned names, not a pattern for plugin-defined functions.

Historical function-name prefixes​

Earlier revisions proposed symbolic prefixes for private, hook, output, debugging, and API functions. The anchor remains so historical source comments still reach an explanation, but those prefixes are not part of version 2 portable conformance. Refactored plugins should replace them with the ASCII project-owned forms above.

Preventing function pollution​

When writing a larger autoload function, it is often the case that the function contains definitions of other functions. When the main function finishes executing, those sub-functions remain defined, which pollutes the command namespace.

The following snippet, added to the main function, unsets the sub-functions on leaving it:

Unset project sub-functions on exit
example_main() {
emulate -L zsh

local -a _example_pre=( ${(k)functions} )

{
# Define and use _example_* sub-functions here.
} always {
unset -f -- ${(M)${(k)functions[@]:|_example_pre}:#_example_*} 2>/dev/null
}
}

The snippet works as follows:

  1. local -a _example_pre=( ${(k)functions} ) records the functions defined at entry, so the list excludes anything the body is about to define. Keeping it local means the record itself does not leak.

  2. The always { } block runs on normal completion and on error alike, so no EXIT and INT trap pair is required and no trap state escapes the function.

  3. ${(k)functions[@]:|_example_pre} subtracts the entry list from the current list using the :| array-subtraction operator, leaving only functions defined inside the block.

  4. ${(M)…:#_example_*} then keeps only the names matching the project's own prefix, and unset -f removes them.

Reading older plugins

Published plugins often name the saved list prjef or a project-specific variant such as rustef. In that convention prj stands for the project name and ef for "entry functions". _example_pre above is the same idea with a clearer name. The older name is fine; what matters is that the list is local and that the cleanup is filtered by prefix.

Do not omit the prefix filter

Step 4 is not cosmetic. Without it, the subtraction deletes every function created during the block, including ones the plugin did not create. An autoload triggered inside the block is a common case:

$ zsh -f -c 'f(){ local -a p=( ${(k)functions} )
{ autoload -Uz is-at-least; is-at-least 5.8 } always {
unset -f -- "${(k)functions[@]:|p}" 2>/dev/null }
}; f; print ${+functions[is-at-least]}'
0

is-at-least was destroyed by cleanup that did not create it. With the _example_* filter in place, it survives and only the project's own sub-functions are removed. Replace _example with your own project prefix.

Preventing parameter pollution​

When writing a plugin one often needs to keep state during the Zsh session. It is natural to use global parameters for this. As the number of parameters grows, one may want to limit it.

A single private project-owned parameter can be sufficient for flat scalar runtime state:

One project-owned hash for flat state
typeset -gA _example_state

_example_state[loaded]=1
_example_state[mode]=fast

This replaces a scatter of individual globals with one inspectable parameter. It remains private runtime state and must not become a second public configuration interface. Use the configuration contract for user settings.

Do not use this to encode arrays or nested structures

Earlier revisions of this page recommended flattening real arrays and hashes into delimiter-encoded keys, such as _example_state[some_array__1], and described the technique as unproblematic. Testing does not support that. Three traps apply, verified on Zsh 5.9.2:

  1. Sorting silently misorders the result. The obvious (o) sort is lexicographic, which is wrong for numeric indices. Numeric (on) is required, and nothing warns you:

    $ # keys arr__1 arr__2 arr__3 arr__9 arr__10 arr__11
    $ print -r -- ${(o)keys}
    arr__1 arr__10 arr__11 arr__2 arr__3 arr__9
    $ print -r -- ${(on)keys}
    arr__1 arr__2 arr__3 arr__9 arr__10 arr__11

    A plugin that flattens an array and sorts with (o) has an ordering bug that stays invisible until the tenth element exists.

  2. Key order is not insertion order. Two hashes filled with the same keys in opposite orders enumerate identically. Key order is a property of the hash, not of how it was filled, and the manual does not specify it, so there is no "read the keys back" shortcut.

  3. The delimiter is ambiguous. Zsh hash keys accept arbitrary content, __ included, so _example_state[user__name] and _example_state[user__name__first] cannot be decoded to a unique structure.

Additionally, ${#array}, ${array[-1]}, and ${array[2,4]} all work directly on a real array; flattened, each becomes a pattern scan plus a numeric sort plus manual arithmetic.

Keep real arrays and real hashes whenever order or shape matters.

Optional manager interoperability profiles​

This appendix records how named managers implement the optional loader interfaces above. It does not add anything to the portable core. Detect each facility before using it and retain direct-source behavior. Exact capability strings and behavior are manager implementation details, not Zsh guarantees.

Zi profile: canonical for z-shell​

Status: implemented in Zi's active source.

The canonical z-shell manager is Zi. Its bootstrap independently declares zsh_loaded_plugins, exports ZPFX and PMSPEC, and derives its own location with a ZERO fallback in zi.zsh. Its loader records entries in zsh_loaded_plugins. Zi also calls a plugin-named *_plugin_unload function and processes its own stored unload callback in lib/zsh/autoload.zsh.

Zi sets PMSPEC=0fuUpiPsX. Its @zsh-plugin-run-on-unload and @zsh-plugin-run-on-update functions store manager callback strings, as shown in Zi's callback source.

For z-shell projects, test the portable core by direct sourcing and add Zi tests for any Zi profile behavior you intentionally support.

Zinit profile: separate alternative project​

Status: implemented independently in Zinit's active source.

Zinit is an alternative project under zdharma-continuum; it is not Zi. Zinit separately declares zsh_loaded_plugins, derives ZINIT[ZERO], exports ZPFX, and sets PMSPEC=0uUpiPsf in its zinit.zsh bootstrap.

Zinit separately implements @zsh-plugin-run-on-unload and @zsh-plugin-run-on-update and invokes a plugin-named unload function in zinit-autoload.zsh. Support for these names in both projects is shared convention, not evidence that Zi and Zinit are the same manager. Test them separately if your plugin opts into both profiles.

zcomet and zgenom profiles​

zcomet status: implemented, with unload explicitly described by its source as an incomplete attempt. zcomet sets PMSPEC=0fbuiPs in zcomet.zsh. Its loader supplies ZERO and appends zsh_loaded_plugins. Its zcomet_unload function conditionally invokes *_plugin_unload, but the source itself says the routine needs work. Do not infer broader lifecycle guarantees.

zgenom status: implemented for the listed variables; no unload claim is made here. zgenom sets a PMSPEC value according to its automatic bin setting, defines ZPFX, and initializes zsh_loaded_plugins in options.zsh. Its loader supplies ZERO and appends the repository ID before sourcing in functions/zgenom-load.

The differing PMSPEC values demonstrate why plugins must not treat any letter list as a universal capability registry.

Review checklist​

Before publishing a plugin, confirm that:

  • one documented entrypoint works with source under zsh -f;
  • self-location uses the scoped entrypoint form and remains valid under posix_argzero;
  • lib/, functions/, completions/, and bin/ follow their documented eager, autoload, completion, and executable profiles;
  • functions/ and completions/ use exact fpath membership checks, while ordinary loading does not mutate PATH;
  • a project-identifier-derived unload function exists, and every hook, widget, worker, descriptor, and file has explicit cleanup;
  • functions localize options and parameters;
  • the README declares one stable ASCII project identifier and the complete public shell surface;
  • persistent names and state are project-owned and setup-only helpers do not remain after load;
  • public configuration uses one namespaced style context or a justified runtime command, not scattered global parameters;
  • portable code neither requires nor mutates shared manager or plugin registry parameters;
  • completion initialization remains under user, framework, or manager control;
  • non-interactive loading does not touch ZLE;
  • loading performs no network access, untrusted evaluation, package installation, or unguarded PATH mutation;
  • cache, state, and data use appropriate user directories;
  • startup cost has been measured with zsh/zprof and end-to-end timing;
  • supported Zsh versions and hostile option combinations are tested;
  • a clean-process lifecycle test proves the declared load surface and exact ownership-aware restoration after unload; and
  • every deliberately supported optional manager interface is feature-tested, has an independent profile test, and retains direct-source behavior.

Next Steps​