zsh

Is the zsh anonymous function without parameters the same as just using `{ ... }` encapsulation?


Take powerlevel10k configuration file as example, there is an anonymous function "() { ... }" like follow:

# 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

  # ... SNIPPED >1000 LINES

}

# 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'

The file is long, the complete version is at https://github.com/romkatv/powerlevel10k/blob/master/config/p10k-classic.zsh (with a few more examples in the same folder)

Question:

According to my understanding, zsh anonymous function parameters, if any, have to follow the closing brace } on the same line. However, I don't find any in the example or my local config.

For anonymous function without parameter, is it the same to just use a { ... } encapsulation? Or did I misunderstand how zsh anonymous function works? Or there are other considerations for not doing that?

PS: This is more of a zsh script question, not specific to p10k.


Solution

  • Some things can be local to a function, such as options, variables, etc., but not to a simple {...} enclosed block. In this specific case, the code is using emulate -L, and from the documentation for emulate, emphasis added:

    If the -L switch is given, the options LOCAL_OPTIONS, LOCAL_PATTERNS and LOCAL_TRAPS will be set as well, causing the effects of the emulate command and any setopt, disable -p or enable -p, and trap commands to be local to the immediately surrounding shell function, if any; normally these options are turned off in all emulation modes except ksh. The -L switch is mutually exclusive with the use of -c in flags.

    If this code used a simple { ... } block, then the effect of emulate -L would have been on your current interactive shell session, instead of just the block.